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!
Related
Here mentioned code successfully passed by the test run.But it was not showed the login button click and the logged-user name.(I have try to print the messages by try-catch ).but result shows as passed without those messages.
I just wanted to why can't I see the button click and assertEqual messages?
is there any coding issue or practice should be able to use to overcome this?
I have used the xml file to send the browser type.Further,I pasted only the relevant code sections.
1.TestCommands.java
public class TestCommands {
public void assertText(By locator,WebDriver driver,String expectedValue){
try {
WebElement element = driver.findElement(locator);
assertEquals(element.getText(), expectedValue);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
System.out.println("Not equal");
}
System.out.println("Equal");
System.out.println("captured web element: "+ locator);
System.out.println("captured expectedValue: "+ expectedValue);
}
}
2.LoginPage.java
public class LoginPage extends TestCommands{
public void loginToApplication(WebDriver driver,String userName,String password,String loggedUser){
type(userName(),driver,userName);
type(password(),driver,password);
click(loginButton(),driver);
selectByVisibleText(loggedUser(),driver,loggedUser);
}
3.TC_LoginToTest.java
public class TC_LoginToTest {
WebDriver driver ;
String baseUrl;
LoginPage login = new LoginPage();
#Parameters("browser")
#BeforeMethod
public void beforeMethod(String browser) {
if (browser.equals("firefox")) {
System.setProperty("webdriver.gecko.driver", "drivers\\geckodriver.exe");
driver = new FirefoxDriver();
//baseUrl = "https://test.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
} else if (browser.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "drivers\\chromedriver.exe");
driver = new ChromeDriver();
//baseUrl = "https://test.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
}
#DataProvider
public Object[][] tc001() {
return new Object[][] {
new Object[] {"nadee","12345678","Testnadee"},
};
}
#Test(dataProvider="tc001")
public void tc001(String userName , String password ,String loggedUser) {
login.openApplication("https://test.com", driver);
login.loginToApplication(driver, userName, password, loggedUser);
}
}
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.
In my application, the first I do is request the user to login using the controlsFX LoginDialog. If the login is successful, I display the application, however if it fails the login window will close.
I would rather the login window stay open to allow the user to attempt to login again.
public void start(Stage stage) throws Exception {
LoginDialog ld = new LoginDialog(new Pair<String, String>("", ""), new Callback<Pair<String,String>, Void>() {
#Override
public Void call(Pair<String, String> info) {
boolean success = login(info.getKey(), info.getValue());
if(success){
openDriverWindow(stage);
}else {
//Display error message
}
return null;
}
});
ld.show();
}
If the login is unsuccessful, the dialog closes - which requires the user to reopen the application.
You can use Dialog from JDK8u40 which will be released at march 2015 or use dialogs from ConrolsFX (openjfx-dialogs-1.0.2). There is a code to implement Dialog which will not be closed until authentication is not passed.
// Create the custom dialog.
Dialog<Pair<String, String>> dialog = new Dialog<>();
dialog.setTitle("Login Dialog");
dialog.setHeaderText("Look, a Custom Login Dialog");
dialog.setGraphic(new ImageView(this.getClass().getResource("login.png").toString()));
// Set the button types.
ButtonType loginButtonType = new ButtonType("Login", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL);
// Create the username and password labels and fields.
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 150, 10, 10));
TextField username = new TextField();
username.setPromptText("Username");
PasswordField password = new PasswordField();
password.setPromptText("Password");
grid.add(new Label("Username:"), 0, 0);
grid.add(username, 1, 0);
grid.add(new Label("Password:"), 0, 1);
grid.add(password, 1, 1);
// Enable/Disable login button depending on whether a username was entered.
Button loginButton = (Button)dialog.getDialogPane().lookupButton(loginButtonType);
loginButton.setDisable(true);
**// Prevent closing dialog if not authenticated**
loginButton.addEventFilter(ActionEvent.ACTION, (event) -> {
if (!authenticated()) {
event.consume();
}
});
// Do some validation (using the Java 8 lambda syntax).
username.textProperty().addListener((observable, oldValue, newValue) -> {
loginButton.setDisable(newValue.trim().isEmpty());
});
dialog.getDialogPane().setContent(grid);
// Request focus on the username field by default.
Platform.runLater(() -> username.requestFocus());
// Convert the result to a username-password-pair when the login button is clicked.
dialog.setResultConverter(dialogButton -> {
if (dialogButton == loginButtonType) {
return new Pair<>(username.getText(), password.getText());
}
return null;
});
Optional<Pair<String, String>> result = dialog.showAndWait();
result.ifPresent(usernamePassword -> {
System.out.println("Username=" + usernamePassword.getKey() + ", Password=" + usernamePassword.getValue());
});
this example was given from this article where you can find many useful examples
Try this:
public class Main extends Application{
private boolean login(String key, String value){
Pair loginData = new Pair<String, String>("test", "test");
if (loginData.getKey().equals(key) && loginData.getValue().equals(value)) {
return true;
}
else {
//Вывести Alert.
Platform.runLater(new Runnable() {
#Override
public void run() {
try {
Alert alert = new Alert(Alert.AlertType.ERROR, "Вы ввели неправильное имя или пароль");
alert.setTitle("Error");
alert.showAndWait();
} catch (Exception e) {
e.printStackTrace();
}
}
});
return false;
}
}
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Terminal Kuban-electro");
getLogin(primaryStage);
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent t) {
System.exit(0);
}
});
}
private void getLogin(Stage primaryStage){
LoginDialog ld = new LoginDialog(new Pair<String, String>("", ""), new Callback<Pair<String, String>, Void>() {
#Override
public Void call(Pair<String, String> info) {
boolean success = login(info.getKey(), info.getValue());
if (success) {
Scene scene = null;
try {
scene = new Scene(FXMLLoader.load(getClass().getClassLoader().getResource("fxml/main.fxml")));
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
}
} else {
getLogin(primaryStage);
}
return null;
}
});
ld.setHeaderText("Введите имя пользователя и пароль");
ld.setTitle("Авторизация");
ld.show();
}
public static void main(String[] args) throws MalformedURLException {
//Инициализация формы в потоке
Thread myThready = new Thread(() -> {
launch(args);
});
myThready.start();
}
}
I had an rcp application which runs for only first run, when a user attempts to re-execute the application, second instance behaves as a client which encodes and sends its arguments over the socket to the first instance which acts as a server and then exits silently. The first instance receives and decodes that message, then behaves as if it had been invoked with those arguments.
so far so good i made internal protocol specification for passing arguments between two instances.
I could not bring the first instance(RCP application) to front. It is in minimized state only,
this is in continuation to my previous question
the change i made to previous post is start method of application class
public Object start(IApplicationContext context) throws Exception {
if (!ApplicationInstanceManager.registerInstance()) {
return IApplication.EXIT_OK;
}
ApplicationInstanceManager
.setApplicationInstanceListener(new ApplicationInstanceListener() {
public void newInstanceCreated() {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
System.out.println("New instance detected...");
//Display.getCurrent().getActiveShell()
.forceActive();// this gives null
// pointer exception
// hence commented
}
});
}
});
Display display = PlatformUI.createDisplay();
try {
int returnCode = PlatformUI.createAndRunWorkbench(display,
new ApplicationWorkbenchAdvisor());
if (returnCode == PlatformUI.RETURN_RESTART)
return IApplication.EXIT_RESTART;
else
return IApplication.EXIT_OK;
} finally {
display.dispose();
}
}
below line is stopping me to bring Application to front
Display.getCurrent().getActiveShell().forceActive();
generates null pointer exception at getActiveShell()
how can i maximize the previous instance or bring it to front
I wrote an instance manager to restrict my RCP to a single instance.
Here's the code that goes in Application.java, in the start method:
if (!ApplicationInstanceManager.registerInstance()) {
return IApplication.EXIT_OK;
}
ApplicationInstanceManager
.setApplicationInstanceListener(new ApplicationInstanceListener() {
public void newInstanceCreated() {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
if (DEBUG)
System.out.println("New instance detected...");
Display.getCurrent().getActiveShell().forceActive();
}
});
}
});
Here's the listener interface:
public interface ApplicationInstanceListener {
public void newInstanceCreated();
}
And here's the Manager class:
public class ApplicationInstanceManager {
private static final boolean DEBUG = true;
private static ApplicationInstanceListener subListener;
/** Randomly chosen, but static, high socket number */
public static final int SINGLE_INSTANCE_NETWORK_SOCKET = 44331;
/** Must end with newline */
public static final String SINGLE_INSTANCE_SHARED_KEY = "$$RabidNewInstance$$\n";
/**
* Registers this instance of the application.
*
* #return true if first instance, false if not.
*/
public static boolean registerInstance() {
// returnValueOnError should be true if lenient (allows app to run on
// network error) or false if strict.
boolean returnValueOnError = true;
// try to open network socket
// if success, listen to socket for new instance message, return true
// if unable to open, connect to existing and send new instance message,
// return false
try {
final ServerSocket socket = new ServerSocket(
SINGLE_INSTANCE_NETWORK_SOCKET, 10, InetAddress
.getLocalHost());
if (DEBUG)
System.out
.println("Listening for application instances on socket "
+ SINGLE_INSTANCE_NETWORK_SOCKET);
Thread instanceListenerThread = new InstanceListenerThread(socket);
instanceListenerThread.start();
// listen
} catch (UnknownHostException e) {
EclipseLogging.logError(RabidPlugin.getDefault(),
RabidPlugin.PLUGIN_ID, e);
return returnValueOnError;
} catch (IOException e) {
return portTaken(returnValueOnError, e);
}
return true;
}
private static boolean portTaken(boolean returnValueOnError, IOException e) {
if (DEBUG)
System.out.println("Port is already taken. "
+ "Notifying first instance.");
try {
Socket clientSocket = new Socket(InetAddress.getLocalHost(),
SINGLE_INSTANCE_NETWORK_SOCKET);
OutputStream out = clientSocket.getOutputStream();
out.write(SINGLE_INSTANCE_SHARED_KEY.getBytes());
out.close();
clientSocket.close();
System.out.println("Successfully notified first instance.");
return false;
} catch (UnknownHostException e1) {
EclipseLogging.logError(RabidPlugin.getDefault(),
RabidPlugin.PLUGIN_ID, e);
return returnValueOnError;
} catch (IOException e1) {
EclipseLogging
.logError(
RabidPlugin.getDefault(),
RabidPlugin.PLUGIN_ID,
"Error connecting to local port for single instance notification",
e);
return returnValueOnError;
}
}
public static void setApplicationInstanceListener(
ApplicationInstanceListener listener) {
subListener = listener;
}
private static void fireNewInstance() {
if (subListener != null) {
subListener.newInstanceCreated();
}
}
public static void main(String[] args) {
if (!ApplicationInstanceManager.registerInstance()) {
// instance already running.
System.out.println("Another instance of this application "
+ "is already running. Exiting.");
System.exit(0);
}
ApplicationInstanceManager
.setApplicationInstanceListener(new ApplicationInstanceListener() {
public void newInstanceCreated() {
System.out.println("New instance detected...");
// this is where your handler code goes...
}
});
}
public static class InstanceListenerThread extends Thread {
private ServerSocket socket;
public InstanceListenerThread(ServerSocket socket) {
this.socket = socket;
}
#Override
public void run() {
boolean socketClosed = false;
while (!socketClosed) {
if (socket.isClosed()) {
socketClosed = true;
} else {
try {
Socket client = socket.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
String message = in.readLine();
if (SINGLE_INSTANCE_SHARED_KEY.trim().equals(
message.trim())) {
if (DEBUG)
System.out.println("Shared key matched - "
+ "new application instance found");
fireNewInstance();
}
in.close();
client.close();
} catch (IOException e) {
socketClosed = true;
}
}
}
}
}
}
After your IApplication start up, you can also check and lock the OSGi instance location using org.eclipse.osgi.service.datalocation.Location.isSet() and org.eclipse.osgi.service.datalocation.Location.lock()
The location is usually retrieved from your Activator using code like:
public Location getInstanceLocation() {
if (locationTracker == null) {
Filter filter = null;
try {
filter = context.createFilter(Location.INSTANCE_FILTER);
} catch (InvalidSyntaxException e) {
// ignore this. It should never happen as we have tested the
// above format.
}
locationTracker = new ServiceTracker(context, filter, null);
locationTracker.open();
}
return (Location) locationTracker.getService();
}
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.