Can I get a code snippet or a reference to any website on how to run and close an external application from the JSP page or through a servlet? Like, Is it possible to run MS-WORD through a click on the JSP page?

andy flack

a simple class i created, (one of my first out of college), you may want to improve it, or use it as it is:

import java.io.*;
import java.lang.Process;
import java.lang.Runtime;

/**
 * This Program is used to execute an external application. developed to execute a C util for linux. 
 * The output stream from the executed program is returned to System.out (stdout)
 * This program uses two threads, one thread kicks off another thread which executes the proccess. if the thread has not terminated within 120 seconds the main thread destroys the proccess and stops the executing thread, the return code is 10000, This handles process lockups. 
 * @author Andrew Flack 
 * @version v1.1 18th Oct 2001
 *  Added functionality to run system/promgram commands in the background whilst the main promgram continues. 
 * @see java.lang.Process
 * @see java.lang.Runtime
 */


public class CommandRunner extends Thread{  

	
	/**
	 * this stores the command passed by the user
	 * @see #executeProccessBackGround(String)
	 * @see #executeProgram(String)
	 */
	private String stCommand;  

	/**
	 * Temp return value from thread
	 */
	private static int iRetVal;

	/*
	 * The executed program runs using this process identifier
	 */
	protected static Process p;

	/**
	 * Temp storage of the stdout of the executed proccess read from an InputStream. 
	 */
	private static StringBuffer sb = null;

	/**
	 * Thread that spawns process and monitors its status. once the proccess finishes execution the output of the program is outputted to console from this method.  
	 * this thread talks to main program using static variables. 
	 * @see #sb
	 * @see #p
	 * @see #iRetVal
	 */
	
	public void run(){	//thread method
		
		int iRetVal = -1; //initialize variable with error code (fail)

		try{

				
			//Process p; 
			int iOut = 0; 
			sb = new StringBuffer();
			Runtime t = Runtime.getRuntime();

			p = t.exec(stCommand);  //execute the passed command
			

			if(p.waitFor() != 0){  //wait for proccess to terminate
				//System.out.println("Execution failed");
			}
			
			iRetVal = p.exitValue();
			InputStream pOut = p.getInputStream();  //get the output from the called program

			while((iOut = pOut.read()) != -1){
				//iOut = pOut.read();
				sb.append((char)iOut);	//append the output to a stringbuffer
			}

			System.out.println("p.exitValue()= " + p.exitValue() + ", iRetVal = " + iRetVal );
			System.out.print(sb.toString());  //print the output of the terminated proccess			

			//System.out.println("Thread Stoped");

		}
		//catch any errors that may of occured and display error to console (not web app)
		catch(IOException ioe){
			System.out.println("IOException occurred when executing " + stCommand + ": " + ioe.getMessage()); 
		}
		catch(InterruptedException ie){
			System.out.println("InterruptedException occurred when executing " + stCommand + ": " + ie.getMessage()); 
		}

		//the return value was returned as a static variable to the main thread
		

	}


	public String getGetOuputFromNonBackGroundProc(){
		return sb.toString();
	}

	/**
	 * spawns a new proccess directly from this thread and continues the execution of this thread. allowing the program being executed to be monitored with getProccessOutputStream
	 * @param stCommandin String the command to be executed on the machine. i.e. "ping 193.123.117.1"
	 * @return InputStream, streaming output of the executed programs stdout. 
	 * @see #getProccessOutputStream()
	 * @see #getProccessErrorStream()
	 * @see #getExitValue()
	 * @see #destroyProcess()
	 */
	public InputStream  executeProccessBackGround(String stCommandin){
		
		try{
				
			//int iOut = 0; 
			//StringBuffer sb = new StringBuffer();
			Runtime t = Runtime.getRuntime();

			p = t.exec(stCommandin);  //execute the passed command

			return p.getInputStream();
		}
		catch(Exception e){
			System.out.println("Error: " + e.getMessage() );
		}
		return null;
		
	}
	
	/**
	 * returns the protected process object to allow direct manipulation of the object. 
	 */
	public Process getProcessObj(){
		return p;
	}

	/**
	 * Returns the process OutputStream (stdout) as an InputStream object for reading.
	 * @see #executeProccessBackGround(String)

	 */
	public OutputStream getProccessOutputStream(){
		return p.getOutputStream(); 
	}

	/**
	 * Returns the process ErrorStream (stderr) as an InputStream object for reading.
	 * @see #executeProccessBackGround(String)
	 */

	public InputStream getProccessErrorStream(){
		return p.getErrorStream();
	}

	/**
	 * Gets the return value from an executed proccess running in the background.
	 * @see #executeProccessBackGround(String)
	 * @return process exit value or -1 on error. 
	 */

	public int getExitValue(){
		try{
			int i = p.exitValue();
			return i;
		}
		catch(IllegalThreadStateException itse){
			return -1;
		}
		catch(Exception e){
			return -1;
		}
	}

	/**
	 * Kills the process currently being executed
	 */
	protected void destroyProcess(){
		p.destroy();
	}

		
	/**
	 * executes an external  proccess in a child thread created by this method. 
	 * This methods thread will wait for the child thread to die, then get the return value of the executed proccess,
	 * if the proccess does not die within 2 mins, then the chile thread is killed, killing the proccess being executed
	 * @return int value representing the return value from the executed proccess. 16 is returned if the method times-out when waiting for the
	 * proccess to finish
	 * @param stCommandin String the command to executed passed as a string e.g. "ls /tmp/"
	 */
	public int executeProgram(String stCommandin){

	
		CommandRunner crThrd = new CommandRunner();
		crThrd.stCommand = stCommandin;		//pass the command to run to the thread
		crThrd.start();  //start a new thread to execute the external program
		try{
			int iwaitfor = 240;	//2 mins
			while(crThrd.isAlive() == true && iwaitfor > 0){	//wait till thread dead or "iwaitfor" in time.
				iwaitfor--;
				
				sleep(500);  //sleep this thread for 500ms
			}	
			if (crThrd.isAlive()){	//if thread is still alive kill it, with the proccess
				p.destroy();
				crThrd.stop();
				iRetVal = 16;  //set a return value not zero (10000 in table as 9984 is added to get the errorcode displayed)
		
			}
			else{
				iRetVal = p.exitValue();
			}

		}
		catch (InterruptedException ie){
			System.out.println("InterruptedException Occured : " + ie.getMessage());
		}
		System.out.println("Return Value in java is:" + iRetVal );
		return iRetVal;
	}

	
	/**
	 * Same as  executeProgram(String) but allows the caller of the method to pass a timeout in seconds. 
	 * @see #executeProgram(String)
	 * @return int value representing the return value from the executed proccess. 16 is returned if the method times-out when waiting for the
	 * proccess to finish
	 * @param stCommandin String the command to executed passed as a string e.g. "ls /tmp/"
	 */

	public int executeProgram(String stCommandin, int iTimeout){

		CommandRunner crThrd = new CommandRunner();
		crThrd.stCommand = stCommandin;		//pass the command to run to the thread
		crThrd.start();  //start a new tread to execute the external program
		try{
			
			int iwaitfor = iTimeout * 2;	//this converts time passed into seconds
			while(crThrd.isAlive() == true && iwaitfor > 0){	//wait till thread dead or 20 mins
				iwaitfor--;
				
				sleep(500);  //sleep this thread for 500ms
			}	
			if (crThrd.isAlive()){	//if thread is still alive kill it, with the proccess
				p.destroy();
				crThrd.stop();
				iRetVal = 16;  //set a return value not zero
		
			}
			else{
				iRetVal = p.exitValue();
			}
		}
		catch (InterruptedException ie){
			System.out.println("InterruptedException Occured : " + ie.getMessage());
		}
		
		System.out.println("Return Value in java is:" + iRetVal );
		return iRetVal;
	}

	/**
	 * Static test harness used for development of this class. 
	 * @param args[] String Not used
	 */
	
	public static void main(String args[]){

		CommandRunner cr = new CommandRunner();
		int i = cr.executeProgram("rsh -l root 193.123.117.224 /usr/xmsutils/xms_ping/xms_ping -N000000104100 -P0 -I193.123.117.38");


		System.out.println("The proccess executed returned the value:" + i);

		//i = cr.executeProgram("gnp");
		//System.out.println("The proccess executed returned the value:" + i);

		

	}


}
This is the complete class and it has been used under linux, it also works in windows with now problems.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact