I try to run a batch file from the servlet application. I could not get any response.It shows no error or warning.The same code works in simple java program.I referred following link for batch file execution
http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html
http://p2p.wrox.com/servlets/71150-invoking-batch-file-servlet.html
I read both the inputstream and errorstream of the process but no response.please help to run a batch file from servlet.Here my code
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String cmdarr[] = new String[4];
cmdarr[0] = "cmd.exe";
cmdarr[1] = "/c";
cmdarr[2] = "start";
cmdarr[3] = "C://notepad.bat";
Runtime run = Runtime.getRuntime();
try {
out.println("Start Running the batch file\n");
Process p = run.exec(cmdarr);
p.waitFor();
out.println("Completed:");
}
catch (Exception e)
{
out.println("Exception"+e);
}
} finally {
out.close();
}
Related
I have a shell script script.sh which needs to be run both by a java servlet and by hand. Its content is:
service avahi-daemon restart
instance=MyInstance
avahi-publish -s -d local $instance _temp._tcp 443 "model=Model1" > /dev/null 2>&1 &
# update: publish other services.
Update:
It is unable to remove the trailing &, because the avahi-publish would't return but keeps running once started and I need to publish other services.
And the servlet is:
public class DefaultServlet extends HttpServlet{
#Override
protected void service(HttpServletRequest request, HttpServletResponse response) {
try {
Process process = Runtime.getRuntime().exec("bash script.sh");
process.waitFor();
}catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
}
The problem is, the service MyInstance won't be published if the servlet is accessed in a browser. But appending sleep 0.1s to the script file would solve it.
My question is that, is there any magic in the Runtime.exec() and why the sleep instruction is needed?
avahi-publish -s -d local $instance _temp._tcp 443 "model=Model1" > /dev/null 2>&1 &
Because of the trailing &, this script will exit and Process.waitFor() will return before the avahi-publish command has finished.
Remove the trailing &.
You should also remove the redirection, and consume the output in the servlet, and test the exit status of the process. To assist in that I would use exec for the avahi-publish process.
Finally I found that ProcessBuilder helps me. Here are my psudo code:
protected void service(HttpServletRequest request, HttpServletResponse response) {
new HandlerThread("avahi-publish","-s","-d", "local","MyInstance", "_https._tcp",
"443","model=abc")
.start();
}
private static class HandlerThread extends Thread {
Process process;
HandlerThread(String... args) {
ProcessBuilder processBuilder = new ProcessBuilder(args);
process = processBuilder.start();
}
public void run() {
StringBuilder stringBuilder = new StringBuilder();
try {
process.waitFor();
readStream(process.getInputStream(),stringBuilder);
readStream(process.getErrorStream(),stringBuilder);
}catch( IOException|InterruptedException ioe){
System.out.println(ioe.getMessage());
}
System.out.println(stringBuilder);
}
private static String readStream(InputStream inputStream, StringBuilder sb) throws IOException {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append('\n');
}
} finally {
if(br!=null) br.close();
}
return sb.toString();
}
}
when exception in servlet then is not working but for jsp its work properly
web.xml code
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error.jsp</location>
</error-page>
servlet code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/*
* TODO output your page here. You may use following sample code.
*/
String a=null;
a.toString();//this line will throw exception
}
finally {
out.close();
}
}
it does not redirect to error.jsp
Servlet code
this will throw the exception to the general error page
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/*
* TODO output your page here. You may use following sample code.
*/
String a=null;
a.toString();
}
catch(Exception e)
{
throw new ServletException(e);
}
finally {
//dont write out.close();
}
}
when we write catch block in servlet it does not work and when we does not write catch block its work properly.
Servlet Code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
DAL db=null;
ResultSet rs=null;
parameter p1=new parameter();
// Object param[];
// List<Object> param=new ArrayList<Object>();
long myId=0;
try {
db=new DAL();
String name=request.getParameter("fn");
db.setQuery("{call usp_StudentInsertData(?,?)}");
db.setInParam(1,name);
db.setInParam(2,1000);
db.insertUpdate();
out.println("insert");
response.sendRedirect("home.jsp");
}
catch(Exception e)
{
}
finally {
}
}
I'm trying to add a server side event servlet to my web application. Below is the code for my servlet: ( Several different versions )
Using getOutputStream():
#WebServlet(urlPatterns = {"/hello"}, asyncSupported = true)
public class HelloServlet extends HttpServlet
{
private static final long serialVersionUID = 2889150327892593198L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/event-stream");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Connection", "keep-alive");
response.setCharacterEncoding("UTF-8");
ServletOutputStream out = response.getOutputStream();
try{
for(int i=0; i<10; i++) {
out.print("id: "+ i +"\n");
out.print("data: "+ System.currentTimeMillis() +"\n\n");
out.flush();
response.flushBuffer();
System.out.println("time sent:"+ System.currentTimeMillis());
System.out.println("IsCommitted:" + response.isCommitted() );
Thread.sleep(1000);
}
}
catch(Exception e)
{
e.printStackTrace();
}
out.close();
}
}
Using PrintStream:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/event-stream");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Connection", "keep-alive");
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
try{
for(int i=0; i<10; i++) {
writer.write("id: "+ i +"\n");
writer.write("data: "+ System.currentTimeMillis() +"\n\n");
writer.flush();
response.flushBuffer();
System.out.println("time sent:"+ System.currentTimeMillis());
System.out.println("IsCommitted:" + response.isCommitted() );
Thread.sleep(1000);
}
}
catch(Exception e)
{
e.printStackTrace();
}
writer.close();
}
An Async Version using https://github.com/mariomac/jeasse
SseDispatcher dispatcher = null;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
System.out.println("test started. Async mode.");
startThread();
dispatcher = new SseDispatcher(req).ok().open();
}
private void startThread()
{
Thread thread = new Thread()
{
#Override public void run()
{
System.out.println("Thread started");
try {
for(int i=0; i<10; i++)
{
System.out.println("Sending message " + i);
onGivenEvent("message"+1, System.currentTimeMillis()+"" ) ;
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
dispatcher.close();
System.out.println("Thread ending");
}
};
thread.setDaemon(true);
thread.setName("testsse");
thread.start();
System.out.println("Starting thread");
}
public void onGivenEvent(String eventName, String data) throws IOException
{
if( dispatcher != null)
{
dispatcher.send(eventName, data);
}
}
For all version I'm using curl to validate it:
curl -i -H "Accept: application/json" -X GET http://localhost:8080/testsse/hello
The output only comes at the end when the connection is closed by the server. If the servlet does not close the connection you never get the output.
I need the events to arrive after the server sends them, and not when the connection is closed. What am I doing wrong? This cannot be the way its supposed to work.
I've googled and tried many examples and they all suffer from this same issue.
I've tried many different versions of tomcat 7.0.67, 7.0.34, 7.0.62. I'm using 64 bit version of JDK 8.0.65 on Windows or JDK 8.0.45 on Linux.
Does anyone have this working? What am I doing wrong?
I figured out a solution to this. I switched to using Jersey SSE and it functions as expected.
I could never get the above solution to function correctly. The Server buffered all the IO until the connection closed. I tried all kinds of flushing and manipulating the buffer size.
Hopefully this helps... Start with another framework such as Jersey SSE.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I am trying to save a String, containing data from an http post request, to a new file in a /database directory on my server.
public class TestIO {
public static void main(String[] args) {
try {
File newFile = new File("database.txt");
FileWriter fileWriter = new FileWriter(newFile);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.println("test");
fileWriter.close();
printWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
makes a file database.txt in the project root directory with the text "test" just fine. But,
#WebServlet("/TestIO")
public class TestIO extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//doGet
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
File newFile = new File("database.txt");
FileWriter fileWriter = new FileWriter(newFile);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.println("test");
fileWriter.close();
printWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
does nothing. No file created, no errors thrown.
PrintWriter swallows exceptions so you may have missed those by not calling checkError().
However if you also tried FileWriter and got no exceptions, the answer is that the file was indeed created - just not where you expected. Have a look in the Tomcat bin directory for example. If you want it created in a path within the web-app you will have to use ServletContext.getRealPath() and friends.
If on the other hand what you're getting is an empty file, the reason is here:
fileWriter.close();
printWriter.close();
This is incorrect. You're closing the FileWriter without giving the PrintWriter a chance to flush, and when you close the PrintWriter it tries to flush and swallows the exception. Remove the first of these two closes altogether.
I am using struts2 in my web application. I want to render a pdf stream on a jsp. i am currently doing this:
public String renderPDF() throws Exception
{
myService.rederPDF(getServletResponse().getServletOutputStream());
return SUCCESS;
}
The rederPDF method of myService gets a pdf stream and writes to the servlet response output stream. But this throws an exception that "The response has already been committed".
This exception occurs when you already sent some thing to client before you forward.
I am using Servlets for downloading files. Have a look.
public class FileDownloadServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
byte[] b = null;
ServletOutputStream sop = null;
try {
response.setContentType("application/pdf");
response.setHeader("Content-Disposition","attachment; filename=yourFileName.pdf");
sop = response.getOutputStream();
b = myService.getFileData(); /* your code */
sop.write(b);
return;
} catch (Exception e) {
/* some code*/
}
finally{
/* some code*/
}
}
}