Calling Java application from servlet

Hi !
I'm trying to run a Java application from within a servlet with Tomcat 4. I'm using the Runtime.getRuntime ().exec () method. So the application is run in a different JVM as a subprocess of the servlet. I use ObjectInputStream and ObjectOutputStream and a serializable object to enable communication between the servlet and the application.
I tested the application and the serializable object with another Java application that works as the caller and it works fine. However, replacing the caller application with the servlet I get a StreamCorruptedException. The structure of the caller application and the servlet is the same.
My questions are:
- Is there something I should configure in Tomcat to create a subprocess ?
- What is the cause of the StreamCorruptedException ? How do I get it with the servlet and not with the application ?
- Should I use an environment with the call to Runtime.getRuntime ().exec () ? How do I use it ?
- Is the called application forced to run in my servlet's context ?
- Is there a better way to do this ?
Thanks to all

Here's my code:
1. The serializable object:
// Object Obj
import java.io.*;
public class Obj implements Serializable
public int n;
public Obj ()
n = 0;
public Obj (int n)
this.n = n;
public String toString ()
return getClass ().getName () + " -> (n = " + n + ")";
2. The application Sub (subprogram)
// Application Sub
import java.io.*;
public class Sub
private static File f;
private static FileWriter fw;
public static void main (String [] args)
throws IOException, InterruptedException, ClassNotFoundException
ObjectInputStream ois;
ObjectOutputStream oos;
Obj obj;
ois = new ObjectInputStream (System.in);
obj = (Obj) ois.readObject ();
f = new File ("Sub.txt");
fw = new FileWriter (f);
fw.write (obj.toString ());
fw.close ();
oos = new ObjectOutputStream (System.out);
oos.writeObject (obj);
ois.close ();
oos.close ();
3. The application AMain (caller application)
// Application AMain
import java.io.*;
class AMain
private static File f;
private static FileWriter fw;
public static void main (String [] args)
throws IOException, ClassNotFoundException
Runtime r;
Process p;
ObjectInputStream ois;
ObjectOutputStream oos;
Obj obj, obj2;
r = Runtime.getRuntime ();
p = r.exec ("java Sub");
oos = new ObjectOutputStream (p.getOutputStream ());
obj = new Obj (5);
oos.writeObject (obj);
oos.flush ();
B.comunica (obj);
System.out.println ("AMain sends to Sub: " + obj.toString ());
try
p.waitFor ();
catch (InterruptedException e)
System.out.println ("Subprogram was interrupted");
System.out.println (e.toString ());
ois = new ObjectInputStream (p.getInputStream ());
System.out.print ("Sub sends to AMain: ");
obj2 = (Obj) ois.readObject ();
System.out.println (" " + obj2.toString ());
oos.close ();
ois.close ();
p.destroy ();
4. The servlet SMain (the calling servlet)
// Servlet SMain
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.io.*;
import java.util.*;
public class SMain extends HttpServlet
public void doPost (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
Runtime r;
Process p;
ObjectInputStream ois;
ObjectOutputStream oos;
Obj obj, obj2;
int state, i;
res.setContentType ("text/html");
ServletOutputStream out = res.getOutputStream ();
out.println ("<html>");
out.println ("<head><title>Sub</title></head>");
out.println ("<body>");
out.println ("Invoking subprogram...");
out.println ("<br>");
try
r = Runtime.getRuntime();
p = r.exec ("java -cp .;c:\\Programs\\Apache~1.0\\webapps\\SMain\\WEB-INF\\classes Sub");
out.println ("...invoked<br>");
oos = new ObjectOutputStream (p.getOutputStream ());
obj = new Obj (5);
oos.writeObject (obj);
oos.flush ();
out.println ("<br>SMain sends to Sub: " + obj.toString () + "<br>");
try
p.waitFor ();
catch (InterruptedException e)
out.println ("<br>Subprogram was interrupted<br>");
out.println ("<br>" + e.toString () + "<br>");
state = p.exitValue ();
out.println ("<br>Subprogram state: " + state + "<br>");
ois = new ObjectInputStream (p.getInputStream ());
out.print ("<br>Sub sends to SMain: ");
obj2 = (Obj) ois.readObject ();
p.destroy ();
catch (SecurityException e)
out.println ("<br>SecurityException<br>");
out.println ("<br>" + e.toString () + "<br>");
catch (IOException e)
out.println ("<br>IOException<br>");
out.println ("<br>" + e.toString () + "<br>");
catch (Exception e)
out.println ("<br>Exception<br>");
out.println ("<br>" + e.toString () + "<br>");
out.println ("</body>");
out.println ("</html>");
So, as you can see, both application AMain and servlet SMain invoke application Sub and pass it the serializable object Obj. Oddly enough, application AMain works fine whereas servlet SMain throws a StreamCorruptedException exception.
johnpoole said:
�It's hard to guess what would cause the exception without seeing code, but the interaction between the processes would differ from that between two applications, because the servlet process is started with a different class loader. I'm not sure which one the jvm started by the call would use.�
How can I enforce that a System classloader be used in the call to Runtime.getRuntime ().exec () ? (I mean by System classloader a classloader equals to the one applications are launched from console).
johnpoole said
�Is there a reason why you aren't starting the second process manually and then connecting to it on a port?�
The idea is providing a Web interface for an application running in the server. The servlet is used to restrict access to this application but once access is granted (passing the servlet) the application should not be constrained.

Similar Messages

  • Calling java application from servlet using servletexec servlets

    We are using servletexec 3.0,IIS 5.0, sun Java SDK 1.3.1_12.
    I have a servlet which works fine. This servlet is being called from the submit of the form in a html file.
    It works fine.
    But now i have to use a third party credit card application from my servlet.How can i do that.
    I have added the third party jar files in the classpath of servletexec.
    How can i use their methods.
    Please let me know.

    Something like this ?
    import thirdparty.*;
    import javax.servlet.http.*;
    public class MyServlet extends HttpServlet {
      public void doGet(HttpServletRequest request, HttpServletResponse response) {
        ThirdPartyClass t = new ThirdPartyClass();
        t.someMethod();
    }

  • Calling Java Application from another

    How can i call a Java Application from another java App.
    eg., If my Java application is called MyApp and i would like call another java application from within it.
    One way could be by using "System". I would like to know if there is any other method and is portable.
    Thanks in advance.

    hi,
    it works and not!
    if you start an other class with a command like this the 2nd prog/class terminates too if you terminate the caller-class!
    dear
    oliver scorp

  • Calling java application from Oracle forms button

    Hi all,
    I have a problem. The idea is to call Java desktop application when button is pressed. I have used this (above) line of code, but there is no results. When I start form in local everything is fine but when I start from server it doesn't work. Does anyone has that kind of problem and how is solved?
    Thanks in advance.
    __Code is:__
    DECLARE
    v_path VARCHAR2(1000);
    BEGIN
    v_path:= '\\location\Java_Application.jar';
    HOST(v_path);
    END;

    First, please start here:
    http://blogs.oracle.com/shay/2007/03/02/
    As for what you are doing and the problem, it will be difficult to give an exact reason, but here are a few comments which will apply regardless of the platform, version, and installation type.
    1. In most case, when calling HOST from Forms the shell that is started does not include all of the system environment variables. This means for example, if a java.exe is needed (on Windows), you would need to specify its path as part of the call or use a batch file rather than calling a command or app directly. The batch file would first set all the needed environment variables (i.e. PATH, CLASSPATH, etc)
    2. If you are running a newer version of Forms, you have a middle tier. This is were your HOST call will be executed. So, if you are expecting this to occur on the client it will not work. You would need WebUtil for client side calls.
    3. Calling a network resource (i.e. shared drive) is not permitted on Windows platforms when called from a Windows Service. Doing so can be seen as a security vulnerability. This can be overridden, but I would suggest that doing so is not a good idea. All files needed to run your app should be made available locally. If files exist on a remote machine, they should be temporarily brought to the machine (e.g. using ftp, sftp, etc) where they are needed and removed later if necessary. If you are running a newer version of Forms, the Forms runtime process belongs to a Windows Service, even if indirectly as a child.
    4. Calling a jar directly is not the proper way to call a java app. Refer to the following:
    http://download.oracle.com/javase/tutorial/deployment/jar/run.html

  • Calling java application from jsp using onUnload

    I have tried to find the answer to this by searching many jsp, js and java forums, but have not had much luck. I hope someone here can help out. I have written a jsp page that passes a sql string to a java application when it loads. That application creates an xml file (a report) and returns the filename, which is the target of an onclick event. What I want to do, is to delete the file when the page unloads. I have written a separate application that will delete the file, but onclick and onunload events apparently only take JavaScript commands. I have tried to embed the jsp code into an onunload event, but it runs when the page is originally loaded. In addition, I created a separate jsp page that deletes the file, and I call that page onunload using window.open(). I can set that page to self.close(), but I can't get the page to not show itself. Even if I set the height and width to 0 (or 1), it seems to appear 100X100. Can anyone give me any suggestions on what to do in this situation? Thanks.

    When my jsp page loads, I create the file using this code:
    String filename = printtasktest.createxml(closed,encodedSQLString);
    printtasktest is a java application on the server, that
    creates a file on the server, and passes the filename back to the jsp page. Later I use this filename as a target of an onclick event:
    <div class="button" onclick="printTask('<%=filename%>')">Print This Page</div>
    printTask() is a javascript function that opens the printable page using window.print() and self.close().
    The problem I have is that the file hangs around after, and I want to delete it when the user leaves the page.

  • How to call a WD JAVA application from a WD ABAP application

    Hi experts,
    Here I have two applications with me. One has been created through WebDynpro ABAP while the other one has been created through WebDynpro JAVA. Now i have to call upon the JAVA aplication from my ABAp application. In other words in need to integrate both the applications so as to have an easy navigation in between them.
    In the whole process I need to take care that the data is not lost from both ABAP or JAVA side.
    Please help me someone knows the solution.
    Regards,
    Kaustubh Maithani

    Hi,
    Usally to run WebDynpro for Java Application, we get the Application URL.
    If you want to call this WebDynpro Java Application from Webdynpro Abap, then create UI element like Link to Action or LinktoURL and give the url as WebDynpro for Java URL.
    Regards,
    Lakshmi Prasad.

  • Calling Webdynpro Java Application from Webdynpro ABAP Application.

    Hi,
    We have developed one Application using Webdynpro Java and I m in need to call the Webdynpro Java application from Webdynpro ABAP.
    Require Suggestions to acheive this.
    Thanks In advance.
    Reg,
    Ajay.

    Dear Ajay,
    Assuming that both your applications WDA & WDJ are in the portal & you don't have to pass any parameters to the WDJ application.
    Write the following code on the action  where you would call the WDJ application.
      DATA:
            lr_compcontroller TYPE REF TO ig_componentcontroller,
            l_component TYPE REF TO if_wd_component ,
            lr_port_manager TYPE REF TO if_wd_portal_integration ,
            wa_navigation TYPE navigation.
      lr_compcontroller =   wd_this->get_componentcontroller_ctr( ).
      l_component = lr_compcontroller->wd_get_api( ).
      lr_port_manager = l_component->get_portal_manager( ) .
    * The value inserted into the navigation-target field can be found in the Portal
    * content administration tab of your portal. It is the ID or PCD Location field
      wa_navigation-target = pcd. " Please provide the PCD Location of the WDJ Application here.
      wa_navigation-mode   = '0'.  "0 = INTERNAL(same page) and 1 = EXTERNAL(new page).
      CALL METHOD lr_port_manager->navigate_absolute
        EXPORTING
          navigation_target = wa_navigation-target
          navigation_mode   = wa_navigation-mode.
    You can get the PCD from the Page properties of the WDJ application page in the Portal.
    Hope it helps!
    Warm regards,
    Upendra Agrawal

  • Call a Java Application from MicroFocus COBOL (in UNIX environment)

    Hello,
    Could you please let me know, how to call a Java application from a MicroFocus COBOL application. If anyone has any code samples, that would be of great help.
    Thanks in advance,
    Tijo.

    You generally can't cause a program to be executed on a different >server. Basic security, you know. Besides this idea of having the Java >application run on a different server wasn't mentioned in your original >post. That leads me to believe we don't have the whole story.So I think you need to step back and find out what are the requirements. For example: Does your program need to start this Java application running, or is it already running and your program needs to connect to it somehow?
    My program has to start a Java class file, meaning that the Micro Focus COBOL module will call the Java class file. Will it be running on the same machine as your program, or on some other machine?
    For both cases, I would like to know the answer.a) Running on the same machine as my program is running.
    b) Running on the different machine.
    And then there are the questions about whether your program needs to have a conversation with the Java application, or whether it just needs to start it and that's all.
    COBOL program has to call a Java class by passing some parameters and Java class in turn process it and return some value back.. Kind of Request and Response model.Plenty of questions to be asked. Go and find out what they are.
    Sorry ... if I am not clear on my questions. Anyhow, thank you very much for providing the information.

  • Calling a Java Application from MicroFocus COBOL.... (in UNIX environment)

    Hello,
    Could you please let me know, how to call a Java application from a MicroFocus COBOL application. If anyone has any code samples, that would be of great help.
    Thanks in advance,
    Tijo.

    Annoyingly crossposted.
    http://forum.java.sun.com/thread.jspa?threadID=730657

  • Call Java function from multithreaded VC++ application

    Friends, I want to call Java function from two threads of a single VC++ application. I can call it from single thread but when I call it from another thread also, JNI_CreateJavaVM() replies with an error.
    Please......help me

    Your posting is ambiguous. My impression is that you have two threads, both trying to create a java VM?

  • Can we call simple a java application from any one of this AS adapters

    Can we call a simple java application from any one of this AS adapters?
    Prakash
    Message was edited by:
    user629857

    You can achieve this using LiveCycle PDF Generator JAVA API. You can find required code here:
    Adobe LiveCycle * Quick Start (SOAP mode): Converting a Microsoft Word document to a PDF document using the Java API
    In parameters:
    //Set createPDF2 parameter values
    String adobePDFSettings = "Standard";
    String securitySettings = "No Security";
    String fileTypeSettings = "Standard OCR";
    "Standard OCR" file type setting will run OCR on input pdf. In the code, instead of doc file provide a pdf file. Resultant pdf will be searchable PDF i.e OCRed PDF.
    Feel feel to ask any further questions.

  • Calling a java application from j2ee web application

    Hi,
    I have a j2ee application in which i am making a call to a jar file which is a java application.
    Runtime a4 = Runtime.getRuntime();
    Runtime a = Runtime.getRuntime();
    String cmd[] = new String[14];
    cmd[0] = "cmd";
    cmd[1] = "/c";
    cmd[2] = "start";
    cmd[3] = "javaw";
    cmd[4] = "-jar";
    cmd[5] = CATALINA_HOME+"\\webapps\\AveksaTesting\\AveksaTestingJava\\dist\\AveksaTestingJava.jar";
    cmd[6] = SERVER_TESTS;
    cmd[7] = COLLECTOR_TESTS;
    cmd[8] = SYSTEM_TESTS;
    cmd[9] = CREATE_ORACLE;
    cmd[10] = DB_NAME;
    cmd[11] = DB_DUMP;
    cmd[12] = email;
    cmd[13] = isMIGRATE;
    try{
    java.lang.Process p = a.exec(cmd);
    Now in the called java application, i am first shutting down the tomcat server by calling shutdown.bat script and then starting it using startup.bat. But the problem i am facing is when i restart the server from java application, it says address already in use(i.e. port 8445 on which tomcat is runninng).
    Id i just call the java application and do the same operation it works fine. I guess when i am calling java from j2ee application, j2ee still has some threads holding java and not shutting down tomcat properly.
    Can anyone suggest me what can be done in this case. I have to call a java application from j2ee and restart the tomcat server many times.
    Thanks in advance
    -Vikram

    Annoyingly crossposted.
    http://forum.java.sun.com/thread.jspa?threadID=730657

  • Calling Java application(forms) from Oracle/Developer

    Hi
    How can i call java application by using Oracle/Developer 10g. Pl. name the methods that i can use.
    regards
    Touseef

    In Oracle a Java stored procedure is a program you write in Java to run in the server, exactly as a PL/SQL stored procedure. You invoke it directly with products like SQL*Plus, or indirectly with a trigger. You can access it from any Oracle Net client—OCI, precompiler, or JDBC.
    Oracle provides a fully-compliant implementation of the Java programming language and JVM. Oracle Database Java Developer's Guide explains how to write stored procedures in Java, how to access them from PL/SQL(or developer), and how to access PL/SQL functionality from Java. -> http://download-uk.oracle.com/docs/cd/B19306_01/java.102/b14187/chfive.htm#BABGCGBG

  • Running a Java application from a Swing GUI

    Hi,
    I was wondering if there is a simple way to run a Java application from a GUI built with Swing. I would presume there would be, because the Swing GUI is a Java application itself, technically.
    So, I want a user to click a button on my GUI, and then have another Java application, which is in the same package with the same classpaths and stuff, run.
    Is there a simple way to do this? Do any tutorials exist on this? If someone could give me any advice, or even a simple "yes this is possible, and it is simple" or "this is possible, but difficult" or "no this is not possible" answer, I would appreciate it. If anyone needs more information, I'll be happy to provide it.
    Thanks,
    Dan

    I don't know if it is possible to run the main method from another Java app by simply calling it...
    But you could just copy and paste the stuff from your main method into a new static method called something like runDBQuery and have all the execution run from there.
    How does that sound? Is it possible?
    What I'm suggeting is:
    Original
    public class DBQuery{
    public static void methodA(){
    public static void doQuery(){
    methodA();
    public static void main(String[] args){
    // Your method calls
    //Your initializing
    doQuery();
    }Revised:
    public class DBQuery{
    public static void methodA(){
    public static void doQuery(){
    methodA();
    public static void doMyQuery(){
    // Your method calls
    //Your initializing
    doQuery();
    // No main needed!!
    //public static void main(String[] args){
    // Your method calls
    //doQuery();
    //}

  • How to call  java program from ABAP

    Hi Experts,
         My requirement is to call java programs from ABAP. For that i have set up SAP JCO connection by using this link http://www.sdn.sap.com/irj/scn/weblogs?blog=/pub/wlg/739. [original link is broken] [original link is broken] [original link is broken] Connection gets sucessfully. After this how to call java program from ABAP as per our requirement. Please help me out.
      Also i tried this way also.. but while executing the DOS Command line appear & disappear in few seconds. So couldnt see the JAVA output. Please help me out to call java programs in ABAP..
    DATA:command TYPE string VALUE 'D:Javajdk1.6.0_20 injavac',
    parameter TYPE string VALUE 'D:java MyFirstProgram'.
    CALL METHOD cl_gui_frontend_services=>execute
    EXPORTING
    application = command
    parameter = parameter
    OPERATION = 'OPEN'
    EXCEPTIONS
    cntl_error = 1
    error_no_gui = 2
    bad_parameter = 3
    file_not_found = 4
    path_not_found = 5
    file_extension_unknown = 6
    error_execute_failed = 7
    OTHERS = 8.
    Thanks.

    This depends on the version of your Netweaver Java AS. If you are running 7.0, you will have to use the Jco framework. The Jco framework is deprecated since 7.1 though. If you want to build a RFC server in 7.1 or higher, it is adviced that you set it up through JRA.
    Implement an RFC server in 7.0:
    http://help.sap.com/saphelp_nw04/helpdata/en/6a/82343ecc7f892ee10000000a114084/frameset.htm
    Implement an RFC server in 7.1 or higher:
    http://help.sap.com/saphelp_nwce72/helpdata/en/43/fd063b1f497063e10000000a1553f6/frameset.htm

Maybe you are looking for

  • My battery life on iPhone 4 with OS 5.0.1 is down to less than 3 hours...

    Hi, I am completely frustrated over the iOS battery problem... i am getting a little bit over 3 hours on a 100% charge... My phone is extremely HOT inside and outside of the case... THIS IS NOT WORKING OUT FOR ME... This is also destroying the life o

  • Need help on fetching 500k records

    Dear programmers, I'm developing an web application that allow user to download a very large number of records. I used JDBC to query result and put it in a text file. It runs very slow and eats a lot of memory. Does anyone have suggestion? Khanh. Reg

  • How do you block explicit lyrics in iTunes store?

    My daughter can not buy explicit lyrics due to settings we have put in place but she can still listen to the short clips of the songs marked explicit.  Is there a way to block this as well?

  • Nalntsrv and winxp sp2

    Hi There I have intermittent problem with nalntsrv service. Users receive error message "Problem: Application Launcher NT Service was not found to run the application as system user." So those applications run as insecure users will not work. Under t

  • Problem when I changed fro iPhoto 9 to iPhoto 11

    I recently upgraded my computer to Mountain Lion and also upgraded from iPhoto 9 to iPhoto 11. In doing so my new iPhoto albums have problems. 1. Some photos now have no descriptions (added comments eg names dates, events) attached to them. I have sp