Solved

Java issue - how to force my code to exit when it hangs

Posted on 2013-02-04
7
420 Views
Last Modified: 2013-02-05
I have a Java method that I use for decrypting files by executing the GPG binary and passing in some parameters (see code sample below).

Sometimes for reasons beyond my control, the file that the program is attempting to decrypt is corrupted and cannot be decrypted.  In those cases, I want the program to abort and raise an error.  The problem I am having is that the the program often just hangs and never completes - it is as if it were stuck in an infinite loop.  So rather than trapping the problem and exiting, the program just sits there and never completes.

Is there any way I can force this program so that it will ALWAYS complete - either successfully or by raising an error?

Thanks.



	public static String decryptFile(String gpgBinaryPath, String passphrase,
			 String decryptedFilePath, String encryptedFilePath) {

		//System.out.println("encryptedFilePath: " + encryptedFilePath);
		//System.out.println("decryptedFilePath: " + decryptedFilePath);
		//System.out.println("gpgBinaryPath: " + gpgBinaryPath);
		//System.out.println("passphrase: " + passphrase);
		
		String strExecReturn = "";
		
		String[] cmdArray = new String[] {
				gpgBinaryPath,
				"--no-tty",
				"--yes",
				"-q",
				"-d",
				"--passphrase",
				passphrase,
				"-o",
				decryptedFilePath,
				encryptedFilePath };
		java.lang.Runtime runtime = java.lang.Runtime.getRuntime();
		java.lang.Process ps = null;
		try 
		{
			ps  = runtime.exec(cmdArray);
		} //end try
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//end catch - IOException
		try
		{
			int exitStatus = ps.waitFor();
			//System.out.println ("exit Status = "+exitStatus);
			if(exitStatus!=0)
			{
				InputStream e = ps.getErrorStream();
				String error = "";
				
				BufferedInputStream bre = new BufferedInputStream(e);
				try 
				{
					int readInt = bre.read();
					System.out.println ("readInt = "+readInt);
					while (readInt != -1) 
					{
						char c = (char) readInt;
						error = error + c;
						readInt = bre.read();
					}//end while
				}//end try 
				catch (IOException e1) 
				{
					e1.printStackTrace();
				}//end catch
				
				System.out.println("ERROR_COMMAND "+ error);
				strExecReturn = "ERROR:"+error;
				throw new Exception("Some problem while copying - "+error);
			}//end if
			else if(exitStatus==0)
			{
				strExecReturn = "SUCCESS";
			}//end else if
		}//end try
		catch (java.lang.InterruptedException e) 
		{
			System.out.println("EXCEPTION_TRACE "+ e);
			e.printStackTrace();
		}//end catch - InterruptedException
		catch(Throwable t)
		{
			t.printStackTrace();
		}//end catch - Throwable
		//System.out.println("Hello " + message + " !"); //$NON-NLS-1$ //$NON-NLS-2$
		
		return strExecReturn;
	}//end method - decryptFile

Open in new window

0
Comment
Question by:jbaird123
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
7 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 38852845
0
 
LVL 27

Accepted Solution

by:
dpearson earned 500 total points
ID: 38853842
The place where you are potentially waiting forever is here:

int exitStatus = ps.waitFor();

I would suggest replacing that with a timeout.  Let's say you're willing to wait for at most 5 minutes before deciding the process has hung and aborting.

You could implement that in a very simple way like this:

Thread.sleep(1000*60*5) ; // Wait 5 mins
int exitStatus = ps.exitValue() ; // Note - this will throw an exception if process has NOT finished (i.e. it's hung)
... now process the output like before

The only downside of this simple approach is you'll always wait 5 mins.  A smarter version would loop, checking the exitValue() every 10 secs or so.  If you get a valid exit code, you process the output.  If you don't get a valid exit code before 5 mins you abort with an error.

Hope that helps,

Doug
0
 

Author Closing Comment

by:jbaird123
ID: 38855634
Thank you, Doug.  This was exactly what I needed.
0
Major Incident Management Communications

Major incidents and IT service outages cost companies millions. Often the solution to minimizing damage is automated communication. Find out more in our Major Incident Management Communications infographic.

 
LVL 86

Expert Comment

by:CEHJ
ID: 38855759
The place where you are potentially waiting forever is here:

int exitStatus = ps.waitFor();

I would suggest replacing that with a timeout.  Let's say you're willing to wait for at most 5 minutes before deciding the process has hung and aborting.
That's not going to help you really. It's far more likely that your app is what is hanging - for the reason given at my link and sublinks. If it's really the process that's hung then it will be down to a bug in GPG
0
 

Author Comment

by:jbaird123
ID: 38855847
CEHJ,

I looked over the information you gave me, but I'm afraid I am still too new to Java to be able to make sense of it all.  

Is it possible to simplify all of that information into a simple call that I can add to my code?

Thanks.
0
 
LVL 27

Expert Comment

by:dpearson
ID: 38857334
CEHJ,

I'm not convinced that it's hanging due to his reading of the error stream.  I think the only place that could happen (if it was an issue with reading the streams) is here:

int readInt = bre.read();

But that shouldn't block when reading an error stream after the process has terminated.  If it did that would be a pretty nasty bug in the JDK wouldn't it?

I think the links you posted are more to solve the problem of how to read the output stream and the error stream while a process is running (a thorny problem).  But that doesn't seem to apply here?

Doug
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 38857384
I don't know what the sequence of events is here. In almost all cases, hanging with Runtime.exec is caused by not consuming process streams in separate threads.

Of course, if the gpg code is problematic when run outside java, then it could be that the process itself is a problem. I didn't get that impression, If that's the case, i missed it
0

Featured Post

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
The viewer will learn how to implement Singleton Design Pattern in Java.

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question