Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Execute program from servlet

Status
Not open for further replies.

MAF

Programmer
Sep 13, 2000
6
ES
Hi!!

I want to execute an .exe program from a servlet. Can you give me an idea on how can this be done?
Thanks
M. [sig][/sig]
 
Similar to execute from an application. Here is a simle code:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;


public class GnuplotServlet extends HttpServlet {
static String gnuplot="D:/Program Files/gnuplot/wgnupl32.exe";

public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
ServletOutputStream out=res.getOutputStream();
String plotIn="/gnuplot"+Math.random();
String plotOut=plotIn+".gif";
String[] command={gnuplot, plotIn};

// Create command file for gnuplot
try {
PrintStream fileIn=new PrintStream(new FileOutputStream(plotIn));
fileIn.println("set terminal gif");
fileIn.println("set output \""+plotOut+"\"");
fileIn.println("set xrange [0:12.5663]");
fileIn.println("plot sin(x)");
fileIn.println("reset");
fileIn.close();
} catch (Exception e) {}

try {
byte[] buffer = new byte[4096];
int read;
BufferedInputStream pOut;

Runtime r=Runtime.getRuntime();
Process p=r.exec(command);
p.waitFor();
pOut=new BufferedInputStream(new FileInputStream(plotOut));
res.setContentType("image/gif");
while ((read=pOut.read(buffer))!=-1) {
if (read>0) { out.write(buffer, 0, read); }
}
pOut.close();
} catch (Exception e) { out.println(e.toString()); }
out.close();
try { new File(plotIn).delete();
} catch (Exception e) {}
try { new File(plotOut).delete();
} catch (Exception e) {}
}
public void init(ServletConfig config) throws ServletException {
String s;

super.init(config);
// paramTterek beolvasßsa
if ((s=getInitParameter("GnuplotPath"))==null) {
gnuplot=s;
}
}
}

The main code is: Runtime.getRuntime().exec(command);
This code runs the wgnupl32.exe, redirect the output to a file (gif image), and then give the image back to the browser.

Good luck. Bye, Otto.
[sig][/sig]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top