Java JButton and swing problem - java

I am doing a networking project. I compiled a code under Java Project console app and it works. But when I create a GUI and assign the code to run when a button is pressed, it hangs on clicking the button.
This is the source code:
#Action
public void EstablishConnection() {
serverAddress = jTextFieldServerAddress.getText();
serverPort = Integer.parseInt(jTextFieldPort.getText());
serverUName = jTextFieldUName.getText();
serverUPwd = jTextFieldUPwd.getText();
try {
client = new FTPClient();
client.connect(serverAddress, serverPort);
boolean login = client.login(serverUName, serverUPwd);
if(login) {
System.out.println("Successfully logged in\n");
}
else {
System.out.println("Unable to login\n");
}
}
catch(Exception ex) {
System.out.println("Exception Raised: " + ex);
}
}
The action is called when a button is pressed in the swing app. It is not working for me. But it is working very fast for a console app.

Anytime I see the word "hang" I assume you need to be using a separate Thread to execute the hanging code. See Concurrency in Swing for the solution.

I would suggest that you should run code that depends on external factors, like accessing a remote server etc., that could delay the response, in a thread of it's own.
Display a MessageDialog with an indeterminate progress bar:
connProgressBar.setIndeterminate(true);
You neither know whether your connection will terminate, nor if it will, so add a button that allows the user to kill the connection thread, whenever she feels like it.
Since you are probably connecting to an ftp server in order to upload and download files, after the connection has been established, use a determinate progressbar that shows the download percentage of the file or files progress, that runs in a new thread.

Related

Using java to open a web browser on another computer

So, this is a rather unusual question, and I can't find anything else anywhere which has been helpful on how to do this, or if its even possible to do so.
I'm working on a game server wrote in java, and I'm trying to get the users default web browser to open to a specific link, when a command is typed into the chat box and sent to the server.
The current Issue I have is, when a user issues the command, it opens the browser on the host system, and not the players system.
I haven't been able to try any other methods, as I am unable to find any information regarding my specific situation!
#CommandHandlerMethod(accessLevel = EAccessLevel.USER)
public static Object[] vote(final Player player, final String... params) {
try {
Desktop desktop = java.awt.Desktop.getDesktop();
URI oURL = new URI("www.example.com");
desktop.browse(oURL);
} catch (Exception e) {
e.printStackTrace();
}
return AbstractCommandHandler.getAcceptResult("");
}
What I was hoping for via this code, was to open the web browser on the players system to allow them to view a specific webpage, but this has not been the case, and opens it on the server host system.

.msi file launched with java closes after a few seconds.

I am trying to launch MySql server installer which is in my resources folder but it terminates after a few seconds. However if I launch it manually it runs okay until the end. Below is my code.
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
String fileUrl = classloader.getResource("mysql.msi").getFile();
Runtime rf = Runtime.getRuntime();
Process pf = rf.exec("msiexec /i \"\\" + fileUrl + "\"");
} catch (Exception e) {
// System.out.println(e.toString()); // not necessary
e.printStackTrace();
}
}
});
t.start();
Okay, it was just an advice, lets come to your case, Windows OS has certain set of security restrictions which allows only administrator to install or remove any application.
That is why, we see a promt window asking for Administrator password (or Admin's permission as YES/NO type, in case user has logged in as admin), and the promt screen is the heart of it's security, as it don't allow ANY OTHER APPLICATION TO HAVE CONTROL ON IT.
If you do a remote desktop via third party, you will never see the client machines promt screen (this is because of security constraints), so in your case, your java application is third party app which don't have enough permission to continue the operation further.
Hence it closes after few seconds.
How ever, you can start and stop already installed services by allowing permission once in your windows service control. So I was suggesting you to play with service only.

Java - Showing message dialogue halts the TimerTask that's running

I made a simple application that automatically uploads/downloads files to and from a server given that there are files to upload or download. I am using a Timer Task to periodically check if there are files locally to upload, or files online to download.
Everything is working fine, and I decided that every time that there is a successful upload/download, I'll show a message dialogue to show the user that a file was successfully uploaded/downloaded.
So far, this is what I have, I am calling this function infoBox. Note that I am doing this in the TimerTask:
public static void infoBox(String infoMessage, String titleBar){
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, infoMessage, titleBar,
JOptionPane.INFORMATION_MESSAGE);
}
Then based on whether or not I got a file or I sent a file, I call it as such:
infoBox("Files Sent!", "Files were sent successfully!");
Or
infoBox("Files Received!", "Files were downloaded successfully!");
And it works fine. If I get a file from the server, or upload a file to it, the message pops up fine.
However, it seems that the TimerTask stops whenever it shows the message dialogue. I have to click "Ok" for the dialogue to close and for the TimerTask to do its thing again.
What I want to happen is for the TimerTask to execute over and over again, regardless how many message dialogues it has shown.
I have a feeling I misplaced where I declared and called my infoBox function. Is there a way for a programs routine task to continually execute as I show message dialogues?
Found an answer here.
Just run the code in a thread, and it won't stop the main thread any more.
public static void infoBox(String infoMessage, String titleBar){
Thread t = new Thread(new Runnable(){
public void run(){
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, infoMessage, titleBar, JOptionPane.INFORMATION_MESSAGE);
}
});
t.start();
}

Launch Firefox and Wait until it is Closed

Question
I want to start the Firefox web browser as process to visit a specific website, then wait until it is closed.
A special situation is that the browser may already be open and running, as the user may have visited some website already.
In that case, the browser would probably open a new tab in an existing window and the newly launched process will be terminated immediately. This should not confuse my waiting process: Either, I want a new browser window (if that can somehow be enforced, maybe via command line arguments) and wait until that is closed, or keep the existing browser window and wait until all the tabs resulting from my process are closed.
Environment
I think it doesn't matter, but my programming environment is Java and you can assume that I know the path of the browser.
Example
The only browser for which I can obtain the expected behavior is Internet Explorer (sigh.). Here, I need to basically create a new batch script in a temp folder with something like
start /WAIT "" "C:\Program Files\Internet Explorer\iexplore.exe" -noframemerging http://www.test.com/
I then run the batch script instead of directly the browser and delete it once I am finished with waiting.
Intended Process
To make the intended process clearer:
My program starts.
My program launches the Firefox browser as separate process and provides an URL to visit as argument to that process.
The Firefox browser runs asynchronously, as a new process, and visits the provided URL. So far, this is easy.
After launching the new process (the Firefox browser), my own program should wait for the said process to terminate. This is the hard part, as
Many modern browsers start multiple processes. I would need to wait for all of them.
Many modern browsers may somehow "detach" themselves from the process that I launched. Sorry, I don't know a better word, what I mean is: I start a process which then starts another process and terminates immediately while the other process keeps running. If I wait for the browser process originally started by my program, the waiting will be finished while the browser is still open.
A special case of the above is tabbed browsing as realized in many browsers: If the browser is already open (in a separate process started by the user) when I launch it, my newly started browser process may simple communicate the URL to visit to the existing process and terminate. The user is still on my provided URL while my program thinks she has closed the browser. This issue can maybe be forbidden by specifying a special command line argument, like noframemerging for the IE.
Once the browser has terminated or all tabs related to the URL I provide have been closed, my program will cease to wait and instead continue doing its business.
The use case is that I have a web application which can either run locally or on a server. If it is run locally, it launches a web server, then opens the browser to visit the entry page. Once the browser is closed, that web application should shut down as well. This works reliable for Internet Explorer, for all other cases, the user has to close the browser and then, explicitly, the web application. Thus, if I could wait reliably for Firefox to finish, this would make the user experience much better.
Solution Preferences:
Solutions are prefered in the following order
Anything which ships with the pure Java JRE. This includes special command line arguments to the browser.
Things that require me to, e.g., create a batch script (such as in the IE case.)
Anything that requires 3rd party open source libraries.
Anything that requires 3rth party closed source libraries.
Any platform independent answer (working both Windows and Linux) is prefered over platform-dependent ones.
Reason: In the ideal case, I would like to know what exactly is done and include it into my own code. As I want to support different browsers (see "PS" below), I would like to avoid having to include one library per browser. Finally, I cannot use commercial or closed source libraries, but if no better answer turns up, of course, I will honor any working solution with an accept. I will accept the first (reasonably nice) working answer of type "1". If answers of lower preference turn up, I will wait a few days before accepting the best one among them.
PS
I will launch a couple of similar questions for other browsers. Since I believe that browsers are quite different in the command line arguments they digest, the way the launch threads and sub-processes, I think this makes sense.
Similar question regarding Chrome: Launch Chrome and Wait Until it is Closed
Similar question regarding Opera: Launch Opera and Wait Until it is Closed
Similar question regarding Chromium: Launch Chromium and Wait Until it is Closed
Similar question regarding Edge: Launch Edge Browser and Wait Until it is Closed
Similar question regarding Safari: Launch Safari and Wait Until it is Closed
Here is a sample program that may somehow manages to demonstrate the capability of a selenium library to fulfill what you want. You need to download the selenium library and set it to your IDE first before you can run this program.
The program allows you to click a button. Then the firefox browser automatically opens and launch a website in a few seconds. Please wait while the website is loading. After that you may close the Firefox browser. The program shall also automatically close after 2 seconds.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.net.ConnectException;
import javax.swing.*;
import org.openqa.selenium.NoSuchWindowException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class AnotherTest extends JFrame {
WebDriver driver;
JLabel label;
public AnotherTest() {
super("Test");
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width - 400) / 2, (screenSize.height - 100) / 2, 400, 100);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
quitApplication();
}
});
JButton jButton1 = new javax.swing.JButton();
label = new JLabel("");
JPanel panel = new JPanel(new FlowLayout());
panel.add(jButton1);
add(panel, BorderLayout.CENTER);
add(label, BorderLayout.SOUTH);
jButton1.setText("Open Microsoft");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
label.setText("Loading browser. Please wait..");
java.util.Timer t = new java.util.Timer();
t.schedule(new java.util.TimerTask() {
#Override
public void run() {
openBrowserAndWait();
}
}, 10);
}
});
}
private void openBrowserAndWait() {
driver = new FirefoxDriver();
String baseUrl = "https://www.microsoft.com";
driver.get(baseUrl);
java.util.Timer monitorTimer = new java.util.Timer();
monitorTimer.schedule(new java.util.TimerTask() {
#Override
public void run() {
while (true) {
checkDriver();
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
}
}
}
}, 10);
}
private void checkDriver() {
if (driver == null) {
return;
}
boolean shouldExit = false;
try {
label.setText(driver.getTitle());
} catch (NoSuchWindowException e) {
System.out.println("Browser has been closed. Exiting Program");
shouldExit = true;
} catch (Exception e) {
System.out.println("Browser has been closed. Exiting Program");
shouldExit = true;
}
if (shouldExit) {
this.quitApplication();
}
}
private void quitApplication() {
// attempt to close gracefully
if (driver != null) {
try {
driver.quit();
} catch (Exception e) {
}
}
System.exit(0);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AnotherTest().setVisible(true);
}
});
}
}
Selenium is primarily used for testing automation of web applications. It can directly open browsers and read the html contents in it. See http://www.seleniumhq.org/ for additional information.

Launch Opera and Wait Until it is Closed [duplicate]

Question
I want to start the Firefox web browser as process to visit a specific website, then wait until it is closed.
A special situation is that the browser may already be open and running, as the user may have visited some website already.
In that case, the browser would probably open a new tab in an existing window and the newly launched process will be terminated immediately. This should not confuse my waiting process: Either, I want a new browser window (if that can somehow be enforced, maybe via command line arguments) and wait until that is closed, or keep the existing browser window and wait until all the tabs resulting from my process are closed.
Environment
I think it doesn't matter, but my programming environment is Java and you can assume that I know the path of the browser.
Example
The only browser for which I can obtain the expected behavior is Internet Explorer (sigh.). Here, I need to basically create a new batch script in a temp folder with something like
start /WAIT "" "C:\Program Files\Internet Explorer\iexplore.exe" -noframemerging http://www.test.com/
I then run the batch script instead of directly the browser and delete it once I am finished with waiting.
Intended Process
To make the intended process clearer:
My program starts.
My program launches the Firefox browser as separate process and provides an URL to visit as argument to that process.
The Firefox browser runs asynchronously, as a new process, and visits the provided URL. So far, this is easy.
After launching the new process (the Firefox browser), my own program should wait for the said process to terminate. This is the hard part, as
Many modern browsers start multiple processes. I would need to wait for all of them.
Many modern browsers may somehow "detach" themselves from the process that I launched. Sorry, I don't know a better word, what I mean is: I start a process which then starts another process and terminates immediately while the other process keeps running. If I wait for the browser process originally started by my program, the waiting will be finished while the browser is still open.
A special case of the above is tabbed browsing as realized in many browsers: If the browser is already open (in a separate process started by the user) when I launch it, my newly started browser process may simple communicate the URL to visit to the existing process and terminate. The user is still on my provided URL while my program thinks she has closed the browser. This issue can maybe be forbidden by specifying a special command line argument, like noframemerging for the IE.
Once the browser has terminated or all tabs related to the URL I provide have been closed, my program will cease to wait and instead continue doing its business.
The use case is that I have a web application which can either run locally or on a server. If it is run locally, it launches a web server, then opens the browser to visit the entry page. Once the browser is closed, that web application should shut down as well. This works reliable for Internet Explorer, for all other cases, the user has to close the browser and then, explicitly, the web application. Thus, if I could wait reliably for Firefox to finish, this would make the user experience much better.
Solution Preferences:
Solutions are prefered in the following order
Anything which ships with the pure Java JRE. This includes special command line arguments to the browser.
Things that require me to, e.g., create a batch script (such as in the IE case.)
Anything that requires 3rd party open source libraries.
Anything that requires 3rth party closed source libraries.
Any platform independent answer (working both Windows and Linux) is prefered over platform-dependent ones.
Reason: In the ideal case, I would like to know what exactly is done and include it into my own code. As I want to support different browsers (see "PS" below), I would like to avoid having to include one library per browser. Finally, I cannot use commercial or closed source libraries, but if no better answer turns up, of course, I will honor any working solution with an accept. I will accept the first (reasonably nice) working answer of type "1". If answers of lower preference turn up, I will wait a few days before accepting the best one among them.
PS
I will launch a couple of similar questions for other browsers. Since I believe that browsers are quite different in the command line arguments they digest, the way the launch threads and sub-processes, I think this makes sense.
Similar question regarding Chrome: Launch Chrome and Wait Until it is Closed
Similar question regarding Opera: Launch Opera and Wait Until it is Closed
Similar question regarding Chromium: Launch Chromium and Wait Until it is Closed
Similar question regarding Edge: Launch Edge Browser and Wait Until it is Closed
Similar question regarding Safari: Launch Safari and Wait Until it is Closed
Here is a sample program that may somehow manages to demonstrate the capability of a selenium library to fulfill what you want. You need to download the selenium library and set it to your IDE first before you can run this program.
The program allows you to click a button. Then the firefox browser automatically opens and launch a website in a few seconds. Please wait while the website is loading. After that you may close the Firefox browser. The program shall also automatically close after 2 seconds.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.net.ConnectException;
import javax.swing.*;
import org.openqa.selenium.NoSuchWindowException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class AnotherTest extends JFrame {
WebDriver driver;
JLabel label;
public AnotherTest() {
super("Test");
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width - 400) / 2, (screenSize.height - 100) / 2, 400, 100);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
quitApplication();
}
});
JButton jButton1 = new javax.swing.JButton();
label = new JLabel("");
JPanel panel = new JPanel(new FlowLayout());
panel.add(jButton1);
add(panel, BorderLayout.CENTER);
add(label, BorderLayout.SOUTH);
jButton1.setText("Open Microsoft");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
label.setText("Loading browser. Please wait..");
java.util.Timer t = new java.util.Timer();
t.schedule(new java.util.TimerTask() {
#Override
public void run() {
openBrowserAndWait();
}
}, 10);
}
});
}
private void openBrowserAndWait() {
driver = new FirefoxDriver();
String baseUrl = "https://www.microsoft.com";
driver.get(baseUrl);
java.util.Timer monitorTimer = new java.util.Timer();
monitorTimer.schedule(new java.util.TimerTask() {
#Override
public void run() {
while (true) {
checkDriver();
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
}
}
}
}, 10);
}
private void checkDriver() {
if (driver == null) {
return;
}
boolean shouldExit = false;
try {
label.setText(driver.getTitle());
} catch (NoSuchWindowException e) {
System.out.println("Browser has been closed. Exiting Program");
shouldExit = true;
} catch (Exception e) {
System.out.println("Browser has been closed. Exiting Program");
shouldExit = true;
}
if (shouldExit) {
this.quitApplication();
}
}
private void quitApplication() {
// attempt to close gracefully
if (driver != null) {
try {
driver.quit();
} catch (Exception e) {
}
}
System.exit(0);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AnotherTest().setVisible(true);
}
});
}
}
Selenium is primarily used for testing automation of web applications. It can directly open browsers and read the html contents in it. See http://www.seleniumhq.org/ for additional information.

Categories

Resources