How do I upload file in Vaadin ui Portlet? - liferay-6

I am creating a Portlet project using Vaadin and Liferay6.0.
I need to upload a csv file from ui and read the file.
My class is as fllows:
#SuppressWarnings("serial")
public void init() {
Window window = new Window("Vaadin Portlet Application");
setMainWindow(window);
window.addComponent(new Label("Hello Vaadin user!"));
window.addComponent(new Label("We are here"));
final TextField tf = new TextField("Device Name:");
// Create the Upload component.
final Upload upload =
new Upload("Upload the file here", null);
// Use a custom button caption instead of plain "Upload".
upload.setButtonCaption("Upload Now");
try{
System.out.println("I am here only");
final DeviceManager dManager = new DeviceManager();
final DeviceSoap[] devices = dManager.getAll();
//getDeviceByName("207.20.47.137");
for (DeviceSoap deviceSoap : devices) {
window.addComponent(new Label("Device Name! "+deviceSoap.getName()));
}
window.addComponent(tf);
Button submitBttn = new Button("Add Device");
Button updateBttn = new Button("Update Device");
window.addComponent(submitBttn);
// Handle button clicks
submitBttn.addListener(new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
// If the field value is bad, set its error.
// (Allow only alphanumeric characters.)
DeviceSoap d = new DeviceSoap();
d.setName(tf.getValue().toString());
try {
dManager.createDevice(d);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
updateBttn.addListener(new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
// If the field value is bad, set its error.
// (Allow only alphanumeric characters.)
DeviceSoap d = devices[1];
d.setName(tf.getValue().toString());
try {
dManager.createDevice(d);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
upload.addListener((Upload.SucceededListener) this);
upload.addListener((Upload.FailedListener) this);
window.addComponent(upload);
}catch(Exception e){
e.printStackTrace();
}
}
Thanks
Hiamsnhu

I'm doing the same thing, and in reading your code, I see that you forgot making:
window.addComponent(updateBttn);
Hope this works.

Related

Pass data from android to flutter

I have added my Android side code:
I know that I need to use a platform channel to pass data,I am unable to figure out:
import io.flutter.embedding.android.FlutterActivity;
public class MainActivity extends AppCompatActivity {
private Button Btn;
// Intent defaultFlutter=FlutterActivity.createDefaultIntent(activity);
String path;
private Button bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Btn = findViewById(R.id.btn);
isStoragePermissionGranted();
Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
path=takeScreenshot();
// activity.startActivity(defaultFlutter);
}
});
//write flutter xode here
//FlutterActivity.createDefaultIntent(this);
}
private String takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
Log.d("path",mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
return mPath;
///openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
return "Error";
}
}
public boolean isStoragePermissionGranted() {
String TAG = "Storage Permission";
if (Build.VERSION.SDK_INT >= 23) {
if (this.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission is granted");
return true;
} else {
Log.v(TAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
}
I will receive a file from the android side, upon receiving I need to display it in a flutter. I also need to use cached engine for transferring data as normally it would cause a delay
You can use the cached engine, this will help me cover up for the delay.
Then you can add a invoke method onpressed that you can send method name and the data you want to pass.
On flutter side,you can create a platform and invoke method through which you can receive requirements and further process it,

Javafx Task for Bluetooth data reciever

I am creating javafx application where I have this case that I need to listen for data sent over Bluetooth.
I have one fxml window on which I need to initialize Bluetooth and start listening from data.
Following is my Code for fxml controller:
//all imports
public class NewBarcodeInvoicePaneController implements Initializable{
private BluetoothController bc;
public BluetoothController getBc() {
return bc;
}
#Override
public void initialize(URL location, ResourceBundle resources) {
try {
bc = new BluetoothController();
new Thread(bc).start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
And BluetoothController is task where I initialize bluettoth and listen to the data
public class BluetoothController extends Task<Void> {
#Override
protected Void call() throws Exception {
LocalDevice local = null;
StreamConnectionNotifier notifier;
StreamConnection connection = null;
// setup the server to listen for connection
try {
local = LocalDevice.getLocalDevice();
try {
local.setDiscoverable(DiscoveryAgent.GIAC);
} catch (BluetoothStateException e) {
}
UUID uuid = new UUID(80087355); // "04c6093b-0000-1000-8000-00805f9b34fb"
String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth";
notifier = (StreamConnectionNotifier) Connector.open(url);
} catch (Exception e) {
e.printStackTrace();
return null;
}
try {
System.err.println("THIS IS HAPENING");
connection = notifier.acceptAndOpen();
System.err.println("HAPENING???????????????????????????");
InputStream inputStream = connection.openInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String lineRead = bReader.readLine();
connection.close();
inputStream.close();
notifier.close();
local.setDiscoverable(DiscoveryAgent.NOT_DISCOVERABLE);
JSONParser parser = new JSONParser();
Object obj = parser.parse(lineRead);
JSONArray array = (JSONArray) obj;
array.stream().map((o) -> (String) o).forEach((stringObj) -> {
System.out.println(stringObj);
});
System.out.println("AFTER DATA RECIEVED");
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
}
It Works fine if I send data over bluetooth and blocking call to notifier.acceptAndOpen() is unblocked.
My problem is when we do not pass any data and I just want to close the window I opened..
It still have blocking call open with extra thread by the task.
I tried to cancel BluetoothController task in Main controller where I open this window like following
private void openNewBarcodeInvoicePane(ActionEvent ae) {
//following are custom classes to open windows from fxml and getting controller back for further manipulation
PostoryModalWindow modalWindow = new PostoryModalWindow();
modalWindow.openNewModalPaneWithParent("New Invoice", "fxml/newbarcodeinvoicepane.fxml", ae);
//getting controller object
NewBarcodeInvoicePaneController controller = (NewBarcodeInvoicePaneController) modalWindow.getDswFromController();
controller.getWindowStage().showAndWait();
BluetoothController bc = controller.getBc();
if(bc != null){
System.err.println("CANCELLING");
bc.cancel(true);
}
}
But it doesn't throw InterrupttedExeption (In which I might have Choice to close Bluetooth thread) and after research I found that waiting on Socket doesn't work on interrupt.
Any help on this?
Thanks
Got Solution After Some Research.
I just added new task to call notifier.acceptAndOpen();
And added method to close Bluetooth notifier.
public class BluetoothController extends Task<Void> {
private final ObservableList<Item> items = FXCollections.observableArrayList();
public ObservableList<Item> getItems() {
return items;
}
StreamConnectionNotifier notifier;
#Override
protected Void call() throws Exception {
try {
BluetoothConnectionTask bct = new BluetoothConnectionTask(items);
new Thread(bct).start();
Thread.sleep(2000);
notifier = bct.getNotifier();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
public void cancelandExit() {
try {
if (notifier != null) {
notifier.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Here is new task for blocking call
public class BluetoothConnectionTask extends Task<Void>{
private StreamConnectionNotifier notifier;
private StreamConnection connection;
private ObservableList<Item> items = FXCollections.observableArrayList();
public StreamConnection getConnection() {
return connection;
}
public StreamConnectionNotifier getNotifier() {
return notifier;
}
public BluetoothConnectionTask(ObservableList<Item> is){
items = is;
}
#Override
protected Void call() throws Exception {
try {
LocalDevice local = LocalDevice.getLocalDevice();
try {
local.setDiscoverable(DiscoveryAgent.GIAC);
} catch (BluetoothStateException e) {
}
UUID uuid = new UUID(80087355); // "04c6093b-0000-1000-8000-00805f9b34fb"
String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth";
notifier = (StreamConnectionNotifier) Connector.open(url);
} catch (Exception e) {
e.printStackTrace();
return null;
}
connection = notifier.acceptAndOpen();
InputStream inputStream = connection.openInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String lineRead = bReader.readLine();
connection.close();
inputStream.close();
notifier.close();
LocalDevice local = LocalDevice.getLocalDevice();
local.setDiscoverable(DiscoveryAgent.NOT_DISCOVERABLE);
JSONParser parser = new JSONParser();
Object obj = parser.parse(lineRead);
JSONArray array = (JSONArray) obj;
ItemDAO idao = new ItemDAO();
array.stream().map((o) -> (String) o).forEach((stringObj) -> {
String barcode = (String) stringObj;
Item i = idao.getItemByBarCode(barcode);
System.err.println("Adding Item "+i.getName());
items.add(i);
});
System.out.println("AFTER DATA RECIEVED");
return null;
}
}
Now for cancelling closing my bluetooth thread I am calling cancelandExit() after window is closed.

Launching Dialog Box with Data from TableView Row

I'm attempting to launch an Edit Customer Window with text fields filled with reference from the rows of a table. The Table and Dialog both have different controller classes.
Here's the code snippet from the table in question that gives us the required customerID when a user double clicks on a row.
Table Controller: CustomersController:
#Override
public void initialize(URL location, ResourceBundle resources) {
populateCustomerTable();
tableListeners(null);
}
void tableListeners(CustomerData customerData){
tblcustomer.setRowFactory(tr -> {
TableRow<CustomerData> row = new TableRow<>();
row.setOnMouseClicked(event -> {
if (event.getClickCount() == 2 && (!row.isEmpty())) {
int selectedCustomerID = row.getItem().getCustomerID();
System.out.println("A certain row: " + selectedCustomerID + " has been clicked!");
Stage stage = new Stage();
FXMLLoader loader = new FXMLLoader();
try {
Parent root = loader.load(getClass().getResource("../view/popups/edit_customer.fxml"));
stage.setScene(new Scene(root));
stage.setTitle("Editing Existing Customer's Details");
stage.initModality(Modality.APPLICATION_MODAL);
stage.initOwner(btnEditCustomer.getScene().getWindow());
stage.showAndWait();
} catch (IOException e) {
e.printStackTrace();
}
}
});
return row;
});
}
I want selectedCustomerID from the above piece of code to be parsed into the EditCustomerController class hence when the dialog launches, it's text fields should be prepoulated with values suppled from the select query that queries the database with the where condition being tht selectedCustomerID from the CustomersController class.
Code snippet from EditCustomerController class:
#Override
public void initialize(URL location, ResourceBundle resources) {
//populateEditCustomerFields(1);
}
void populateEditCustomerFields(int customerID){
this.customer_ID=customerID;
System.out.println(customer_ID);
try {
con = DatabaseConnection.getConnected();
stmt = con.createStatement();
rs = con.createStatement().executeQuery("SELECT * FROM `h_customers` WHERE `customerID`=" + customer_ID);
while (rs.next()) {
title.setText(rs.getString("title"));
firstName.setText(rs.getString("firstName"));
lastName.setText(rs.getString("lastName"));
nationalID.setText(String.valueOf(rs.getInt("nationalID")));
//dob.setText(rs.getString("DOB"));
mobilePhone.setText(rs.getString("mobilePhone"));
workPhone.setText(rs.getString("workPhone"));
email.setText(rs.getString("email"));
}
} catch (SQLException ex) {
Logger.getLogger(NewRoomController.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
The Idea here is to parse selectedCustomerID from CustomersController into the initialize method of EditCustomerController so the Dialog can launch with the customer details that require editing. I've searched for solutions all over the web and here on StackOverflow, some come close to answering me, some are too complex for my newbie mind, but none has helped. Any solution would be highly appreciated. I will provide any further clarification required.
You can get the controller class and invoke its necessary methods. See this answer for getting controller, then do
editCustomerController.populateEditCustomerFields(selectedCustomerID);
on table row double click.
Further to improve performance, you can load the edit_customer.fxml only once and when the user double clicks, refresh its rendered data with editCustomerController.populateEditCustomerFields(selectedCustomerID).

How to remove MenuBar/ select in lwuit form

I'm trying to remove this select area which shows up as soon as I add a button to my form.
Have attached a screenshot of the same which might help you understand my plight here. I don't want this select area to appear at the bottom of screen.
Please, any suggestion or any pointer would be of great help.
regards.
Below is the code which I'm using.(Xlet project)
public void showMainForm() {
try {
mf = new MainForm();
mf.createMainForm();
mf.show();
} catch (Exception e) {
}
}
public class MainForm extends Form {
MainForm() {
super();
}
private static Container c;
public void createMainForm() {
try {
c = new Container(new CoordinateLayout(800,480));
Button btn = new Button();
btn.setX(0); btn.setY(0);
c.addComponent(btn);
this.getContentPane().addComponent(c);
} catch (Exception e) {
}
}
}
Form code which I tried again...
Form frm = new Form();
frm.getStyle().setBgTransparency(0);
//frm.addComponent(new Button("Button"));
frm.show();
I think that this issue can be solved adding the Command to the Form,not to the Container as you are doing in the attached code.
ADD
I think that I didn't understand what you want to say. Try this code, with my suggestions included
public void showMainForm() {
try {
mf = new MainForm();
mf.createMainForm();
mf.show();
} catch (Exception e) {
}
}
public class MainForm extends Form {
MainForm() {
super();
}
private static Container c;
public void createMainForm() {
try {
c = new Container(new CoordinateLayout(800,480));
// Button btn = new Button();
// btn.setX(0); btn.setY(0);
// c.addComponent(btn);
// this.getContentPane().addComponent(c);
Command c = new Command("command");
addCommand(c);
} catch (Exception e) {
}
}
}

Connecting e-mail client, recieving works but sending does not

I have a problem with a code. It's (supposed to be) an email-client with options to read messages and send them - the problem is, that it does not download the messages and is not able to send them - I assume that the problem lies in the connectiong.
The program includes following classes
EmailClient: The main class for the e-mail client application
ConnectDialog: This class displays a dialog for entering e-mail server connection settings.
MessagesTableModel: This class manages the e-mail table's data.
MessageDialog: This class displays the dialog used for creating messages.
Here's the main class, the most interesting are methods named sendMessage() and connect():
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.swing.*;
import javax.swing.event.*;
// The E-mail Client.
public class EmailClient extends JFrame {
// Message table's data model.
private MessagesTableModel tableModel;
// Table listing messages.
private JTable table;
// This the text area for displaying messages.
private JTextArea messageTextArea;
/* This is the split panel that holds the messages
table and the message view panel. */
private JSplitPane splitPane;
// These are the buttons for managing the selected message.
private JButton replyButton, forwardButton, deleteButton;
// Currently selected message in table.
private Message selectedMessage;
// Flag for whether or not a message is being deleted.
private boolean deleting;
// This is the JavaMail session.
private Session session;
// Constructor for E-mail Client.
public EmailClient() {
// Set application title.
setTitle("E-mail Client");
// Set window size.
setSize(640, 480);
// Handle window closing events.
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
actionExit();
}
});
// Setup file menu.
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
JMenuItem fileExitMenuItem = new JMenuItem("Exit",
KeyEvent.VK_X);
fileExitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionExit();
}
});
fileMenu.add(fileExitMenuItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
// Setup buttons panel.
JPanel buttonPanel = new JPanel();
JButton newButton = new JButton("New Message");
newButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionNew();
}
});
buttonPanel.add(newButton);
// Setup messages table.
tableModel = new MessagesTableModel();
table = new JTable(tableModel);
table.getSelectionModel().addListSelectionListener(new
ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
tableSelectionChanged();
}
});
// Allow only one row at a time to be selected.
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// Setup E-mails panel.
JPanel emailsPanel = new JPanel();
emailsPanel.setBorder(
BorderFactory.createTitledBorder("E-mails"));
messageTextArea = new JTextArea();
messageTextArea.setEditable(false);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
new JScrollPane(table), new JScrollPane(messageTextArea));
emailsPanel.setLayout(new BorderLayout());
emailsPanel.add(splitPane, BorderLayout.CENTER);
// Setup buttons panel 2.
JPanel buttonPanel2 = new JPanel();
replyButton = new JButton("Reply");
replyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionReply();
}
});
replyButton.setEnabled(false);
buttonPanel2.add(replyButton);
forwardButton = new JButton("Forward");
forwardButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionForward();
}
});
forwardButton.setEnabled(false);
buttonPanel2.add(forwardButton);
deleteButton = new JButton("Delete");
deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionDelete();
}
});
deleteButton.setEnabled(false);
buttonPanel2.add(deleteButton);
// Add panels to display.
getContentPane().setLayout(new BorderLayout());
getContentPane().add(buttonPanel, BorderLayout.NORTH);
getContentPane().add(emailsPanel, BorderLayout.CENTER);
getContentPane().add(buttonPanel2, BorderLayout.SOUTH);
}
// Exit this program.
private void actionExit() {
System.exit(0);
}
// Create a new message.
private void actionNew() {
sendMessage(MessageDialog.NEW, null);
}
// Called when table row selection changes.
private void tableSelectionChanged() {
/* If not in the middle of deleting a message, set
the selected message and display it. */
if (!deleting) {
selectedMessage =
tableModel.getMessage(table.getSelectedRow());
showSelectedMessage();
updateButtons();
}
}
// Reply to a message.
private void actionReply() {
sendMessage(MessageDialog.REPLY, selectedMessage);
}
// Forward a message.
private void actionForward() {
sendMessage(MessageDialog.FORWARD, selectedMessage);
}
// Delete the selected message.
private void actionDelete() {
deleting = true;
try {
// Delete message from server.
selectedMessage.setFlag(Flags.Flag.DELETED, true);
Folder folder = selectedMessage.getFolder();
folder.close(true);
folder.open(Folder.READ_WRITE);
} catch (Exception e) {
showError("Unable to delete message.", false);
}
// Delete message from table.
tableModel.deleteMessage(table.getSelectedRow());
// Update GUI.
messageTextArea.setText("");
deleting = false;
selectedMessage = null;
updateButtons();
}
// Send the specified message.
private void sendMessage(int type, Message message) {
// Display message dialog to get message values.
MessageDialog dialog;
try {
dialog = new MessageDialog(this, type, message);
if (!dialog.display()) {
// Return if dialog was cancelled.
return;
}
} catch (Exception e) {
showError("Unable to send message.", false);
return;
}
try {
// Create a new message with values from dialog.
Message newMessage = new MimeMessage(session);
newMessage.setFrom(new InternetAddress(dialog.getFrom()));
newMessage.setRecipient(Message.RecipientType.TO,
new InternetAddress(dialog.getTo()));
newMessage.setSubject(dialog.getSubject());
newMessage.setSentDate(new Date());
newMessage.setText(dialog.getContent());
// Send new message.
Transport.send(newMessage);
} catch (Exception e) {
showError("Unable to send message.", false);
}
}
// Show the selected message in the content panel.
private void showSelectedMessage() {
// Show hour glass cursor while message is loaded.
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
messageTextArea.setText(
getMessageContent(selectedMessage));
messageTextArea.setCaretPosition(0);
} catch (Exception e) {
showError("Unabled to load message.", false);
} finally {
// Return to default cursor.
setCursor(Cursor.getDefaultCursor());
}
}
/* Update each button's state based off of whether or not
there is a message currently selected in the table. */
private void updateButtons() {
if (selectedMessage != null) {
replyButton.setEnabled(true);
forwardButton.setEnabled(true);
deleteButton.setEnabled(true);
} else {
replyButton.setEnabled(false);
forwardButton.setEnabled(false);
deleteButton.setEnabled(false);
}
}
// Show the application window on the screen.
public void show() {
super.show();
// Update the split panel to be divided 50/50.
splitPane.setDividerLocation(.5);
}
// Connect to e-mail server.
public void connect() {
// Display connect dialog.
ConnectDialog dialog = new ConnectDialog(this);
dialog.show();
// Build connection URL from connect dialog settings.
StringBuffer connectionUrl = new StringBuffer();
connectionUrl.append(dialog.getType() + "://");
connectionUrl.append(dialog.getUsername() + ":");
connectionUrl.append(dialog.getPassword() + "#");
connectionUrl.append(dialog.getServer() + "/");
/* Display dialog stating that messages are
currently being downloaded from server. */
final DownloadingDialog downloadingDialog =
new DownloadingDialog(this);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
downloadingDialog.show();
}
});
// Establish JavaMail session and connect to server.
Store store = null;
try {
// Initialize JavaMail session with SMTP server.
Properties props = new Properties();
props.put("mail.smtp.host", dialog.getSmtpServer());
session = Session.getDefaultInstance(props, null);
// Connect to e-mail server.
URLName urln = new URLName(connectionUrl.toString());
store = session.getStore(urln);
store.connect();
} catch (Exception e) {
// Close the downloading dialog.
downloadingDialog.dispose();
// Show error dialog.
showError("Unable to connect.", true);
}
// Download message headers from server.
try {
// Open main "INBOX" folder.
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
// Get folder's list of messages.
Message[] messages = folder.getMessages();
// Retrieve message headers for each message in folder.
FetchProfile profile = new FetchProfile();
profile.add(FetchProfile.Item.ENVELOPE);
folder.fetch(messages, profile);
// Put messages in table.
tableModel.setMessages(messages);
} catch (Exception e) {
// Close the downloading dialog.
downloadingDialog.dispose();
// Show error dialog.
showError("Unable to download messages.", true);
}
// Close the downloading dialog.
downloadingDialog.dispose();
}
// Show error dialog and exit afterwards if necessary.
private void showError(String message, boolean exit) {
JOptionPane.showMessageDialog(this, message, "Error",
JOptionPane.ERROR_MESSAGE);
if (exit)
System.exit(0);
}
// Get a message's content.
public static String getMessageContent(Message message)
throws Exception {
Object content = message.getContent();
if (content instanceof Multipart) {
StringBuffer messageContent = new StringBuffer();
Multipart multipart = (Multipart) content;
for (int i = 0; i < multipart.getCount(); i++) {
Part part = (Part) multipart.getBodyPart(i);
if (part.isMimeType("text/plain")) {
messageContent.append(part.getContent().toString());
}
}
return messageContent.toString();
} else {
return content.toString();
}
}
// Run the E-mail Client.
public static void main(String[] args) {
EmailClient client = new EmailClient();
client.show();
// Display connect dialog.
client.connect();
}
}
Adding printStackTrace() to exceptions gives the following message:
javax.mail.NoSuchProviderException: No provider for NORMAL
at javax.mail.Session.getProvider(Session.java:464)
at javax.mail.Session.getStore(Session.java:539)
at EmailClient.connect(EmailClient.java:296)
at EmailClient.main(EmailClient.java:365)
I'm grateful for all the help I can get!