Using Desktop.browse doesn't allow program to exit automatically - java

If I make a simple program that browses to google.com, the program doesn't exit automatically when reaching the end of the main method. I would rather not call System.exit(0), so I was wondering if there was a way to "close" the desktop thread so it can exit automagically.
public static void main(String[] args) {
try {
Desktop.getDesktop().browse(new URI("http://google.com"));
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}

Related

Java URL open and Close after random time

I need code that will open url and close it after some random time(3-10minutes)
Something like:
Desktop d = Desktop.getDesktop();
d.browse(new URI("http://google.pl"));
d.wait(1000);
d.destroy(); //error there is no destroy function here
any ideas?
I looked into this some more, the Desktop class does not have a close() feature to it.
If you want to launch another program via Java you should use the Process class. Doing something similar to this:
import java.io.IOException;
public class Process {
public static void main(String[] args) {
try {
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec("notepad");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
process.destroy();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Java Assertion in Try with multiple catchs

Scenario:
class Assert {
public static void main(String []args) {
try {
assert false;
}
catch (RuntimeException re) {
System.out.println("In the handler of RuntimeException");
}
catch (Exception e) {
System.out.println("In the handler of Exception");
}
catch (Error ae) {
System.out.println("In the handler of Error");
}
catch (Throwable t) {
System.out.println("In the handler of Throwable");
}
}
}
I am expecting 'In the handler of Error' because AssertionError is subclass of Error but it doesn't show anything and terminate normal. after then to check the out put I added this one catch handler before Error handler .
catch (AssertionError t) {
System.out.println("In the handler of Throwable");
}
in know it's not a good practice to catch Error but if we does not need to catch why the program was not crashed it terminate normally?
By default assertions are disabled, add -ea in the command line when you execute your code with java:
java -ea Assert

Java shutdown hook and writing to an Excel Sheet

So high level I have a program that reads data from an Excel SpreadSheet stores it in a list of hash maps, does dome operations, gets a status, and then writes the information back the Excel SpreadSheet. As of right now if an Exception of some sort causes the program to crash or the program finishes normally everything is fine.
Now I am trying to handle what if a user terminates the run by pressing Ctrl + C. I figured the best way to do this would be implementing my own shutdown hook.
private static class TerminationThread extends Thread
{
public void run() {
for(UserCredential user : creds)
{
Accel.setRow(user.getMap(), user.getRowIndex());
}
try {
Accel.writeToFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In my Main() I register this as a shutdown hook
TerminationThread sH = new TerminationThread();
Runtime.getRuntime().addShutdownHook(sH);
When the program enters the shutdown hook everything is fine until it gets to the portion that writes to the file then it starts throwing a bunch of exceptions and at the end i get a corrupted spreadsheet.
Here is my write code:
public void writeToFile() throws IOException
{
try
{
fileOut = new FileOutputStream(theFile);
theWorkbook.write(fileOut);
}
catch (IOException e)
{
throw new IOException("Exception in writeToFile(). " + e);
}
finally
{
try
{
fileOut.flush();
fileOut.close();
}
catch(IOException e)
{
throw new IOException("Exception closing FileOutputStream. " + e);
}
}
}
What I am assume is happening is that the object that handles my excel spreadsheet is getting wiped out before the write is completed or the list of hash maps where i store the data before writing it is getting wiped out.
I have looked at Thread Joins as a possible solution to my problem but upon looking at them I don't think they are the solution to my problem.
So I guess my question is how do i get this to work the way I would like it to work
Cheers,
Meinert
EDIT: Here is the exception
Exception in thread "Thread-4" org.apache.xmlbeans.impl.values.XmlValueDisconnectedException
at org.apache.xmlbeans.impl.values.XmlObjectBase.check_orphaned(XmlObjectBase.java:1213)
at org.apache.xmlbeans.impl.values.XmlObjectBase.newCursor(XmlObjectBase.java:243)
at org.apache.xmlbeans.impl.values.XmlComplexContentImpl.arraySetterHelper(XmlComplexContentImpl.java:1073)
at org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTDefinedNamesImpl.setDefinedNameArray(Unknown Source)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.saveNamedRanges(XSSFWorkbook.java:1270)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.commit(XSSFWorkbook.java:1291)
at org.apache.poi.POIXMLDocumentPart.onSave(POIXMLDocumentPart.java:313)
at org.apache.poi.POIXMLDocument.write(POIXMLDocument.java:173)
at com.cba.statuschecker.ExcelManager.writeToFile(ExcelManager.java:179)
at com.cba.statuschecker.Main$TerminationThread.run(Main.java:495)
EDIT 2: Well I figured out my own problem. I was approaching this the wrong way. My code is correct the only problem was that in my finally block I also have a file write. So when my program would execute all the way through without interruption it would execute the write twice which was the cause of the exception. I fixed this by checking if the finally block was executed and if it was the write in the shutdown hook is skipped.
Finally:
finally
{
// Print out statuses
printStatus();
for(UserCredential user : creds)
{
Accel.setRow(user.getMap(), user.getRowIndex());
}
try {
Accel.writeToFile();
} catch (IOException e) {
e.printStackTrace();
}
didFinally = true;
LOGGER.info(Log("Fin."));
System.exit(0);
}
Shutdown Hook
private static class TerminationThread extends Thread
{
public void run() {
System.out.println("Shutdown Initiated...");
if(!didFinally){
for(UserCredential user : creds)
{
Accel.setRow(user.getMap(), user.getRowIndex());
}
System.out.println("Writing to file...");
try {
Accel.writeToFile();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Terminated!");
}
}
Well I figured out my own problem. I was approaching this the wrong way. My code is correct the only problem was that in my finally block I also have a file write. So when my program would execute all the way through without interruption it would execute the write twice which was the cause of the exception. I fixed this by checking if the finally block was executed and if it was the write in the shutdown hook is skipped.
Finally:
finally
{
// Print out statuses
printStatus();
for(UserCredential user : creds)
{
Accel.setRow(user.getMap(), user.getRowIndex());
}
try {
Accel.writeToFile();
} catch (IOException e) {
e.printStackTrace();
}
didFinally = true;
LOGGER.info(Log("Fin."));
System.exit(0);
}
Shutdown Hook
private static class TerminationThread extends Thread
{
public void run() {
System.out.println("Shutdown Initiated...");
if(!didFinally){
for(UserCredential user : creds)
{
Accel.setRow(user.getMap(), user.getRowIndex());
}
System.out.println("Writing to file...");
try {
Accel.writeToFile();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Terminated!");
}
}

Android / Java: how to define a code block and leave it without custom exceptions?

I seem to be stuck with a very simple task that would require GOTO statements and, in my opinion, would justify a use of those.
I have the very simple task to exit a void on different conditions. Within its code, several dozen operations are being done and most of them can fail. I test them with try {}.
Now, based on the criticality of the operation, I either need to exit immediately and do nothing else, or, I just need to interrupt control flow and jump to a final point to do some cleaning up and then exit the method.
MWE:
public void myMethod () {
try { op1(); } catch (Exception e) { return; } // Fail here: exit immediately
try { op2(); } catch (Exception e) { cleanUpFirst(); return; } // Fail here: do Cleaning up first, then exit
try { op3(); } catch (Exception e) { return; } // Fail here: exit immediately
try { op4(); } catch (Exception e) { cleanUpFirst(); return; } // Fail here: do Cleaning up first, then exit
try { op5(); } catch (Exception e) { cleanUpFirst(); return; } // Fail here: do Cleaning up first, then exit
// ....
}
public void cleanUpFirst() { /* do something to clean up */ }
For code readability, I'd like to a) avoid a separate function and b) do not have more than one statement within the catch block; it just blows up the code. So, in my opinion this would perfectly justify the use of a GOTO statement.
However, the only solution I came up with, given that only two outcomes are possible, is this:
public void myMethod () {
do {
try { op1(); } catch (Exception e) { return; }
try { op2(); } catch (Exception e) { break; }
try { op3(); } catch (Exception e) { return; }
try { op4(); } catch (Exception e) { break; }
try { op5(); } catch (Exception e) { break; }
// ....
} while (1==0);
/* do domething to clean up */
}
Yes, I have heard of exceptions and that is is the Java way. Is that not as overkilled as using the separate void? I do not need the specifics, I simply need a yes/no result from each operation. Is there a better way?
why not
boolean cleanupfirst = false;
try {
op1 ();
cleanupfirst = true;
op2 ();
cleanupfirst = false;
op3 ();
} catch (Exception e) {
if (cleanupfirst)
cleanup ();
return;
}
You're over-thinking it.
4 minor adjustments.
Let Opn() return a boolean for success or failure, rather than throwing an Excpetion.
Let CleanupFirst handle program termination (you can rename it to clean exit if you want). The new parameter passed to CleanExit is the System.exit code.
Use System.Exit to return a proper return code to the OS, so you can use it in scripting.
It does not seem like your program has a successful path.
if (!op1())
System.exit(1); // <- send a failed returncode to the OS.
if(!op2())
cleanExit(2);
if (!op3())
System.exit(3); // <- send a failed returncode to the OS.
if (!op4())
cleanExit(4);
if (!op5())
cleanExit(5);
cleanExit(0);
More methods for better readability:
public void myMethod() {
try {
tryOp1();
tryOp2();
...
} catch(Exception ignore) {}
}
public void tryOp1() throws Exception {
op1();
}
public void tryOp2() throws Exception {
try {
op1();
} catch (Exception e) {
cleanUp();
throw e;
}
}

Java event is killed when a function for audio playing is called

I am facing a strange programming problem. It has exhausted me but with no solution found!
My program is mainly dependent on an event (Java Listener) that is fired from an external hardware for receiving an audio message from that hardware.Inside the eventHandler i do the following
pass the received message to a static method "decode" from another class which returns data
then I open FileOutputStream, write these data "audio" to a file,and close the FileOutputStream.
I call a static method "play" from another class to play the audio file.
The problem is: whenever the method "Play" is called for the first time, it executes correctly but it causes the event to stop raising and the program to terminate but without exceptions. When I comment out the play method, everything becomes okay!
Do you have some idea about a method causing program termination ?
public void messageReceived(int to,Message message)
{
speexAudioMsg msg = (speexAudioMsg)message;
try{
byte[] output = jspeexDecoder.decode(msg.get_frame());
os = new FileOutputStream(file);
os.write(output);
os.close();
Player.play();
}
catch (IOException ex) {ex.printStackTrace();}
}
You are probably using the event thread to play the music. Try calling Player.play() in a new thread.
new Thread(new Runnable() { public void run() {Player.play()}}).start();
here is an example:
static String url = "http://www.stackoverload.com";
public static void threadTest() {
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
URL url2 = new URL(url);
url2.openStream();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).run();

Categories

Resources