How can I execute a java program from a Servlet?

Thank You
[email protected]

You could call it via Runtime.exec(), just as you would from any Java program. Or better, you could redesign it as a proper Java class. Then your servlet could create an instance of the class and call its methods as necessary.

Similar Messages

  • How can I execute an external program from within a button's event handler?

    I am using Tomcat ApacheTomcat 6.0.16 with Netbeans 6.1 (with the latest JDK/J2EE)
    I need to execute external programs from an event handler for a button on a JSF page (the program is compiled, and extremely fast compared both to plain java and especially stored procedures written in SQL).
    I tried what I'd do in a standalone program (as shown in the appended code), but it didn't work. Instead I received text saying the program couldn't be found. This error message comes even if I try the Windows command "dir". I thought with 'dir' I'd at least get the contents of the current working directory. :-(
    I can probably get by with cgi on Apache's httpd server (or, I understand tomcat supports cgi, but I have yet to get that to work either), but whatever I do I need to be able to do it from within the button's event handler. And if I resort to cgi, I must be able to maintain session jumping from one server to the other and back.
    So, then, how can I do this?
    Thanks
    Ted
    NB: The programs that I need to run do NOT take input from the user. Rather, my code in the web application processes user selections from selection controls, and a couple field controls, sanitizes the inoputs and places clean, safe data in a MySQL database, and then the external program I need to run gets safe data from the database, does some heavy duty number crunching, and puts the output data into the database. They are well insulated from mischeif.
    NB: In the following array_function_test.pl was placed in the same folder as the web application's jsp pages, (and I'd tried WEB-INF - with the same result), and I DID see the file in the application's war file.
            try {
                java.lang.ProcessBuilder pn = new java.lang.ProcessBuilder("array_function_test.pl");
                //pn.directory(new java.io.File("K:\\work"));
                java.lang.Process pr = pn.start();
                java.io.BufferedInputStream bis = (java.io.BufferedInputStream)pr.getInputStream();
                String tmp = new String("");
                byte b[] = new byte[1000];
                int i = 0;
                while (i != -1) {
                    bis.read(b);
                    tmp += new String(b);
                getSelectionsDisplayTextArea().setText(getSelectionsDisplayTextArea().getText() + "\n\n" + tmp);
            } catch (java.io.IOException ex) {
                getSelectionsDisplayTextArea().setText(getSelectionsDisplayTextArea().getText() + "\n\n" + ex.getMessage());
            }

    Hi Fonsi!
    One way to execute an external program is to use the System Exec.vi. You find it in the functions pallet under Communication.
    /Thomas

  • How Can I execute a java program using java code?

    {color:#000000}Hello,
    i am in great trouble someone please help me. i want to execute java program through java code i have compiled the java class using Compiler API now i want to execute this Class file through java code please help me, thanks in advance
    {color}

    Thanks Manko.
    i think my question was not clear enough.. actually i want to run this class using some java code . like any IDE would do i am making a text editor for java, as my term project i have been able to complie the code usign compiler api and it genertaes the class file but now i want to run this class file "THROUGH JAVA CODE" instead of using Java command. I want to achive it programatically. do you have any idea about it.. thanks in advance

  • How Can I execute an external program from my vi?

    Hi guys,
    I want to execute a external program to use it when i called with a bottom. I want push a bottom and execute the program, like acess direct icon or so.
    Any help?.

    Hi Fonsi!
    One way to execute an external program is to use the System Exec.vi. You find it in the functions pallet under Communication.
    /Thomas

  • How to execute a Java program from ODI

    Hi All,
    I am new to ODI. I would like to know whether its possible to execute a java program from ODI.
    Reason for this is, I would like to write information in error tables into a file. And after that another program will mail that error log to concerned person.
    Could anyone please help me with this?
    Thank you in advance
    Regards,
    Srini

    if you have the java code then u can create a procedure with Java BeanShell as the Technology and write your java code in the procedure

  • How can i  apply this  java program for  a jsp page?

    import java.io.*;
    import java.util.*;
    public class FileProcessing
      //create a vector container  for the input variables
         Vector variables = new Vector();
      //create a vector container for the constants
         Vector constants = new Vector();
      /*create a string expression container for the equation
         as read from the file */
         String expression = " ";
      //create double result container for the final result
         double result = 0;
         public boolean processFile(String filename,String delim)
          //index for values vector
              int num_values = 0;
          //index for constants vector
              int num_constants = 0;
          //current line being read from the external file.
              String curline = " ";
          //start reading from the external file
              try
                   FileReader fr = new FileReader(filename);
                   BufferedReader br = new BufferedReader(fr);
                   while(true)
                        curline = br.readLine();
                        if(curline == null)
                             break;
                    //determine the type of current interaction
                        boolean variable = curline.startsWith("input");
                        boolean constant = curline.startsWith("constant");
                        boolean equation = curline.startsWith("equation");
                        boolean output = curline.startsWith("result");
                   //on input variables
                        if(variable)
                          StringTokenizer st = new StringTokenizer(curline,delim);
                          int num = st.countTokens();
                          int count=0;
                          while(st.hasMoreTokens())
                               String temp = st.nextToken();
                               if(count==1)
                                    byte b[]= new byte[100];
                                    System.out.println(temp);
                                    System.in.read(b);
                                    String inputval = (new String(b)).trim();
                                    variables.add(num_values,inputval);
                                    num_values++;
                               count++;
                        // on constant values
                        if(constant)
                             StringTokenizer st = new StringTokenizer(curline,delim);
                             int num = st.countTokens();
                             int count = 0;
                             while(st.hasMoreTokens())
                                  String temp = st.nextToken();
                                  if(count==1)
                                       byte b[]= new byte[100];
                                       System.out.println(temp);
                                       System.in.read(b);
                                       String cons = (new String(b)).trim();
                                       constants.add(num_constants,cons);
                                       num_constants++;
                                  count++;
                        // on equation
                        if(equation)
                             StringTokenizer st = new StringTokenizer(curline,delim);
                             int num = st.countTokens();
                             int count = 0;
                             while(st.hasMoreTokens())
                                  String temp = st.nextToken();
                                  if(count==2)
                                       this.expression = temp;
                                  count++;
              // now we are ready to evaluate the expression
                       if(output)
                          org.nfunk.jep.JEP  myparser= new org.nfunk.jep.JEP();
                          myparser.setAllowAssignment(true);
                          for(int i=1;i<variables.size()+1;i++)
                             String name = "arg"+Integer.toString(i);
                             myparser.addVariable(name,new Double(variables.get(i-1)
                                                .toString()).doubleValue());
                          for(int i=1;i<constants.size()+1;i++)
                               String name = "arg" +Integer.
                                         toString(i+variables.size());
                               myparser.addConstant(name,new Double(constants.get(i-1).toString()));
                   //output is obtained as follows
                          myparser.parseExpression(expression);
                          result = myparser.getValue();
                          System.out.println("Assay value: "+result);
              catch(Exception e)
                   System.out.println(e.toString());
              return true;
         public static void main(String[] args)
              FileProcessing fp = new FileProcessing();
              fp.processFile("input.eqn",":");
    }//my text file name is: "input.eqn" (given below)
    input:Enter Value1:arg1
    input:Enter Value2:arg2
    input:Enter Value3:arg3
    constant:arg4
    constant:arg5
    Equation:arg1+arg2+arg3
    result:

    how can i apply this java program for a jsp pagewhy do you want to do this ?
    Your program reads from a file on the disk and formats based on a patterm.
    Jsp is not intended for such stuff.
    ram.

  • How can i run my java program with out java language

    Hai to every one ..Iam new to java language ...am using windows xp operating system , i did not installed java language in my system .. how can i run a java program with out installing java language... Which files is requied to run java program..?
    any one can help me??

    Hai to every one ..Iam new to java language ...am
    using windows xp operating system , i did not
    installed java language in my system .. how can i run
    a java program with out installing java language...
    you ... can ... not ... do ... this
    Which files is requied to run java program..?
    any one can help me??a JVM. Download it from sun's website.
    [url http://java.sun.com/javase/downloads/index.jsp]Download JavaSE here

  • How can we disable the 'Improvement Program' from all the apps in TCS5?

    How can we disable the 'Improvement Program' from all the apps in TCS5, so that the end users are not able to see the option in the help menu?
    We have tried changing the value of bUsageMeasurement (HKLM\SOFTWARE\Policies\Adobe\(product name)\(version)\FeatureLockdown) to zero, but it did not help.

    You’re probably going to have to contact Support on that one.

  • How can I drop the java objects from a schema

    hi..good afternoon all...
    How can I drop the java objects from a database schema???
    suppose the credentials are scott/tiger@db1
    Another thing is that...I have to do this from cmd(command prompt) as there is no plsql developer or sqldeveloper installed in the machine.
    plss help...thanks in advance...

    hi...i have already tried all the options..but it is showing the error..
    ora:01435 - user does not exist
    but when i have given the command...
    select object type, object_name, status from user_objects where object_type like'%JAVA%';
    then it is showing that the java_object is present....
    Connected to:
    Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
    With the Partitioning, OLAP, Data Mining and Real Application Testing options
    SQL>
    SQL>
    SQL>
    SQL> set linesize 200
    SQL>
    SQL>
    SQL>
    SQL> select object_type, object_name, status from user_objects where object_type
    like '%JAVA%';
    OBJECT_TYPE OBJECT_NAME
    STATUS
    JAVA CLASS javaclass1
    VALID
    JAVA SOURCE javaclass1
    VALID
    SQL> drop java source javaclass1.java;
    drop java source javaclass1.java
    ERROR at line 1:
    ORA-01435: user does not exist
    SQL>

  • How can I execute a batch file from my java program

    Hi,
    Can someone help me or direct me to a link,
    How can I execute a DOS batch file from my java program?
    Thanks

    You will need to grab a handle to the process's
    outputstream so u can see its output.The OP didn't mention any output from any batch file;
    nor any input for that
    matter,so lets not complicate matters here for now
    ok?Actually I think this is essential to see whether it works or not. It's either that or do some manual check to see whether it ran, which is not exactly elegant, and in some cases this may not be easier than simply writing the output stream code, or in fact it may be impossible to check manually.
    I'm sure it wasn't intentional that your post appeared to be bristling with attitude.

  • How can I call a java class from within my program?

    I was wondering if there's a platform independent way to call a java class from my program.

    Here's my scenario. I'm working on a platform independent, feature rich, object-oriented command prompt program. The way I'm designing it is that users can drop classes they write into my bin directory and gain access to the class through my program. For example, they drop a class named Network.class in the bin directory. They would type Network network at my command prompt and gain access to all the methods available in that class. They can then type system.echo network.ipaddress() at my prompt and get the system's ip address. I have it designed that there's a server running in the background and the clients connect to my port. Once connected the end-user can enter their user name and password and gain access to the system. When they type a command they actually call another java program which connects to my server using a seperate thread. They can then communicate back and forth. I have it set that everything has a process id and it's used to keep track of who called what program. Once the program is done it disconnects and closes. Rather than getting into the nitty gritty (I didn't want to get into heavy detail, I know how everything will work) I'm really interested in finding out how I can call a java program from my program. I don't want it to be part of the app in any way.

  • Execute a java program from an another program

    Like we can compile a code from wihin a java file by using the following :
    Tool javac = ToolProvider.getSystemJavaCompiler();
    Similarly,can we execute i.e. run a java program from within a java file i.e. running d java command from within the java file ??If yes then please tell me how??

    suppose on the Unix box or from a Unix script ( korn, perl, bourne, bash) you can run the following java program
    java ${JAVA_OPTS} -jar ${GMR_APPS_DIR}/risk.jar -I -c ${COB} -r ${BATCH} -o ${XML_DIR}
    in java you can do the following :
    Runtime rt = Runtime.getRuntime();
              try {
                   Process process = rt.exec("java ${JAVA_OPTS} -jar ${GMR_APPS_DIR}/risk.jar -I -c ${COB} -r ${BATCH} -o ${XML_DIR}
    // OR
                   Process process = rt.exec("/export/apps/Tools/apache-tomcat-5.5.17/bin/startup.sh");
                   // process.destroy(); if you want to kill the process
                   process.waitFor();
                   int RC = process.exitValue();      
                   System.out.println(returnOutput(process.getErrorStream()));
                   System.out.println(returnOutput(process.getInputStream()));
              } catch (Exception ex) {
                   ex.printStackTrace();
    empty the output stream from the script
    private String returnOutput(InputStream is) throws Exception {
                   String s;
                   StringBuffer strBuff = new StringBuffer();
                   BufferedReader br = new BufferedReader(new InputStreamReader(is));
                   while ((s = br.readLine()) != null) {
                        strBuff.append(s);
                   return strBuff.toString();
              }You need to relace the ${} by the appropriate values.
    Regards,
    Alan Mehio
    London, UK
    Edited by: alan_mehio on Jan 16, 2008 4:21 PM

  • Executing a Java Program from within a Java Program

    I need to execute the following Java Program from withing another Java Program. The office toolbar command line is
    D:\WINDOWS\system32\java.exe -cp E:\Development\Eclipse\UpdateServer\Classes -server -showversion UpdateServer
    I can find no combination of ProcessBuilder commands, including those that include "Cmd.exe /c" that will make this program run from within another Java Program. All the examples I can find only show how to run Windows *.exe programs. I keep getting error 123 from ProcessBuilder.start(), but I can find no documentation for error 123.

    Assuming your code didn't get mangled by the forum
    (it's missing one "), it may be that your "-cp
    E:\\Develop.." argument is getting quoted as it has a
    space in it; try passing "-cp" and "E:\\Develop..."
    as two arguments.That worked; specifically the following tested OK:
    ProcessBuilder pb = new ProcessBuilder("D:\\WINDOWS\\System32\\Java.exe", "-cp", "E:\\Development\\Eclipse\\UpdateServer\\Classes\\", "-server", "-showversion", "UpdateServer" );
    pb.directory(new File("E:\\Development\\Eclipse\\UpdateServer\\Classes\\"));
    try{
         Process p = pb.start();
         InputStream is = p.getErrorStream();
         InputStreamReader isr = new InputStreamReader(is);
         BufferedReader br = new BufferedReader(isr);
         String line;
         while ((line = br.readLine()) != null)
              System.out.println(line);
         p.waitFor();
    }catch(IOException ioe){
    I was sure I tried that exact same code before, and it did not work, but now it does, at least at the top level (when it is in main of a test program). I will have to wait to try it until later when it is buried deep in a subroutine.

  • How can you get a java program working on a cell phone?

    I was thinking of making some stuff for cell phones so i was wondering how you get a normal java program to work on cells.

    its all j2me - midlet package....Huh? The jsr-118 MID profile alone has 11 packages, one of which is javax.microedition.midlet. Notj2me - midlet.
    works best on nokia phones.Sez who? You seem to be confusing Java ME with Symbian C.
    you can use net beans midlet packge add-on.Only it's called the NetBeans Mobiliity Pack.
    Its easy to use and has lots of tutorials.Ditto for the Wireless toolkit for CLDC.
    just search on google.Yes, but with which keywords?
    @OP:
    NetBeans mobility pack comes with a short tutorial and several samples, you also need to download the latest WTK as the ver. 2.2 which comes bundled with NetBeans is just too buggy to work with. Then there are the manufacturer-specific SDKs from Nokia, Motorola, Sony Ericsson and (maybe) others.
    If and when you get started in Java ME aka j2me, it will be appropriate to post any questions you might have on the mobility forums, not here.
    Google "j2me tutorial" for many good hits.
    luck, db

  • Not able to execute one Java program from another one via. exec()

    Hi,
    I am new to this forum, so I might be asking a very trivial quetion.
    My program Ap1 is :
    class Ap1
    public static void main(String a[]) throws Exception
    Runtime rt=Runtime.getRuntime();
    Process p=null;
    p=rt.exec("javac,Pr.java");
    Runtime.getRuntime().exec("javac,Pr.java");
    When I run the above program, I get below error at the line 7(bold one):
    D:\batchwe>javac Ap1.java
    D:\batchwe>java Ap1
    Exception in thread "main" java.io.IOException: CreateProcess: javac,Pr.java err
    or=2
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(ProcessImpl.java:81)
    at java.lang.ProcessImpl.start(ProcessImpl.java:30)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:451)
    at java.lang.Runtime.exec(Runtime.java:591)
    at java.lang.Runtime.exec(Runtime.java:429)
    at java.lang.Runtime.exec(Runtime.java:326)
    at Ap1.main(Ap1.java:7)
    Path is set as below(which seems correct):
    D:\batchwe>path
    PATH=C:\Program Files\Java\jdk1.5.0_05\bin
    I am just wondering how to call one Java program from another one?!
    Please help.
    thanks
    Rashmi

    Hi diptaPB,
    Thanks for your suggestion.
    Here is how I tried it again, but not getting the desired output:
    Class Pr looks like below -->
    class Pr
    public static void main(String a[])
    System.out.println("hi from process");
    When I run 'Pr' from command prompt, i get the desired output:
    D:\batchwe>java Pr
    hi from process
    However, when I call 'Pr' from another program Ap2.java, it seems that it does not call 'Pr':
    class Ap2
    public static void main(String a[]) throws Exception
    Runtime rt=Runtime.getRuntime();
    Process p=null;
    String[] cmd=new String[2];
    cmd[0]="javac";
    cmd[1]="Pr.java";
    p=rt.exec("cmd");
    D:\batchwe>javac Ap2.java
    D:\batchwe>java Ap2
    ************* no output appears here***********************
    Looking forward for your help.
    regards
    Rashmi

Maybe you are looking for

  • How to convert a .jsp to a .java/.class file for use in peoplesoft

    Hi java/jsp experts, I want to convert a .jsp to a .java/.class file. is there a tool available, please let me know if you have any pointers.... or can i do it manually: these are a few lines that the .jsp contains, and i would like to translate this

  • Linking one Numbers file to another???

    I want to link the formulas from one Numbers file to another seperate and distinct Numbers file - can I????

  • How to create Customer data TAB in PO -ME23N

    Can anyone tell me how to add 'Customer data' TAB in the PO heade TABSTRIP. I have to add it in the header besides 'Status' TAB. I know an enhancement 'MM06E005' which is used for this purpose. Thanks SMS

  • At New will made some fields *********

    Hi, by using At New in internal table some fields are showing ********* can any one please hep to solve Regards Nausal

  • Quick Time 7.6.6 in Mac OSX 10.6.3

    Hello I am looking for some advice. I have a Mac Book Pro with OS X 10.6.3 and I am trying to install QuickTime from your web, but it says that it is a QT for Mac OS X v10.5 through v 10.5.8...so what I should I do. I have already downloaded it and t