Runtime exec problem to execute a C program

Hi,
I've spend lot of time trying to find a solution without success...
My aim is to run a C program from a java application under linux. My C code is the following:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
main(int argc, char **argv){
printf("hello world \n");
Once compiled I run my java application wich run the binary through a runtime.exec().
I followed the example given by
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
with the same input gobblers and threads.
For some reason it doesn't work: nothing comes out...
When I call "ls" instead of my binary it works perfectly!
WHY??
Any help would be greatly appreciated!

Thanks for the reply.
Yes it seems that JNI could be a solution, but it looks a bit complicated an maybe not so well adapted to my purpose.
The executables I want to execute from my java application don't need any arguments.
If JNI is really the only way I'll try to use it but is there any good reason why runtime exec doesn't work? It is supposed to execute any executable isn't it?
cheers

Similar Messages

  • Runtime.exec does not execute my program, but executes "ls"

    I am trying to run an exe from a Java program.
    The program that I want to run is an output of a gcc -o ICDDATA ICDdata.c
    Now when I use the Runtime.exec() and execute "ls", "cat" it is working fine without any errors.
    But when i try to give the file(ICDDATA) that was created with the gcc, it generates an error code of "11" or "10" and exits the process.
    Could anyone please let me know the reason why this is happenig and suggest and appropiate solution for this.

    When I give ICDDATA at the prompt, it is executing perfectly fine.
    But only when it is run inside the Java program its giving the error code 10.
    Here is the source code:
    ======================================
    public class InvokeInterface {
         This method takes two parameters and accordingly invokes one of the
         interface (ICD / Value).
         @Input : String, String
         @Return : void
         static void executeInterface(String processName, String debugOption)
         throws java.io.IOException     {
              String commandToExecute=". / ";
                   // The command that has to be passed to the Shell.
              if(processName.equals("ICD"))
                   commandToExecute="ICDDataRefresh";
              if(processName.equals("VALUE"))
                   commandToExecute="ValueDataRefersh";
              commandToExecute += " "+debugOption;
              System.out.println("..."+commandToExecute);
              Runtime runtime = Runtime.getRuntime();
              Process proc = runtime.exec(commandToExecute);
                   try {
                        if (proc.waitFor() != 0) {
                        System.err.println("exit value = " +
                        proc.exitValue());
              catch (InterruptedException e) {
                   System.err.println(e);
    ==========
    Thanks in Advance
    Ram

  • Java.lang.Runtime.exec problem in ubuntu 9.10

    Hi:
    I tried to run some command in the java code , for example "grass64 -text /home/data/location", this command works well in the terminal, however when I call it in the java code I got some excepetions.
    My code is :
    public class Grass {
         public static String grassBatJob="GRASS_BATCH_JOB";
         public void run(String cmd,String jobPath) {
              //set the environments variables
              Map<String, String> env=new HashMap<String, String>();
              env.put(grassBatJob, jobPath);
              String gisDataBase="/home/kk/grass/GrassDataBase";
              String location="spearfish60";
              String mapset="PERMANENT";
              cmd=cmd+" "+gisDataBase+"/"+location+"/"+mapset;
              CommandLine line=new CommandLine(cmd);
              //the real cmd should be >>grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT
              System.out.println("start line=="+line.toString());
              DefaultExecutor de=new DefaultExecutor();
              try {
                   int index=de.execute(line,env);
                   System.out.println(index);
              } catch (ExecuteException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              String jobPath=Grass.class.getResource("grass.sh").getFile();
              new Grass().run("grass64 -text", jobPath);
    The real cmd I want to execute is "grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT" with the envrionment variable "GRASS_BATCH_JOB=jobPath",it works well in the ternimal ,however in my application I got the exception"
    java.io.IOException: Cannot run program "grass64 -text /home/kk/grass/GrassDataBase/spearfish60/PERMANENT": java.io.IOException: error=2, No such file or directory
         at java.lang.ProcessBuilder.start(ProcessBuilder.java:459)
         at java.lang.Runtime.exec(Runtime.java:593)
         at org.apache.commons.exec.launcher.Java13CommandLauncher.exec(Java13CommandLauncher.java:58)
         at org.apache.commons.exec.DefaultExecutor.launch(DefaultExecutor.java:246)
         at org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecutor.java:302)
         at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:149)
         at org.kingxip.Grass.run(Grass.java:27)
         at org.kingxip.Grass.main(Grass.java:38)
    Caused by: java.io.IOException: java.io.IOException: error=2, No such file or directory
         at java.lang.UNIXProcess.<init>(UNIXProcess.java:148)
         at java.lang.ProcessImpl.start(ProcessImpl.java:65)
         at java.lang.ProcessBuilder.start(ProcessBuilder.java:452)
         ... 7 more
    I wonder why?

    Thanks for all of your reply, and now I can run the command, however I met some problems when I tried to get the result of the exec.
    The core codes are shown below:
    String cmd="g.version";
    String[] exe={"bash","-c",cmd};
    Process p1=Runtime.getRuntime.exec(exe,env); // the env has been set
    GrassThread outThread=new GrassThread("out", p1.getInputStream());
    outThread.start();
    GrassThread errorThread=new GrassThread("error", p1.getErrorStream());
    errorThread.start();
    int exitVal = p1.waitFor();
    String resu=outThread.sb.toString();
    System.out.println("==========the output start========");
    System.out.println(resu);
    System.out.println("==========the output end========");
    System.out.println("ExitValue: " + exitVal); //------------------> line one
    public class GrassThread extends Thread{
         public StringBuffer sb=new StringBuffer();
         public GrassThread(String type,InputStream is) {
              this.type=type;
              this.is=is;
         public void run() {
              try {
                   InputStreamReader isr = new InputStreamReader(is);
                   BufferedReader br = new BufferedReader(isr);
                   String line = null;
                   while ((line = br.readLine()) != null) {
                        System.out.println(type + ">" + line);
                        sb.append(line).append("\r");  // ----------------------------> line two
    }I define a StringBuffer in the GrassThread to save the output (see the code where I marked by "line two"), and when the process complete, I check the StringBuffer to get the output (see code where I marked by "line one"), however the output in the console of the IDE are :
    ----------- output in the console of the IDE start -------------
    ==========the output start========
    ==========the output end========
    ExitValue: 0
    out>GRASS 6.4.0RC5 (2009)
    ----------output in the console of the IDE end--------------------
    I can not understand, in the code "line one", I first get the output using "System.out.println(resu);",then I print the exitvalue,but why the order of the output in the console is not what I expected?
    Another question, the code above assume the output can be got from the Process's getInputStream, however sometimes the output maybe come from the Process's getErrorStream, so how to handle it?
    Edited by: apachemaven on 2010-3-5 ??5:38

  • Runtime.exec--problems writing to external file

    Hi. I went to http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html, and am still quite confused regarding the use of Runtime.exec, for my purposes. I want to decompile a CLASS file using javap, and then write that to a TXT file, for easier reading/input to JAVA. Now, I use the following code (a modification of what I got from http://www.mountainstorm.com/publications/javazine.html, as the "traps" article's sample code is WAY too confusing--they say the compiler had the output sent to text.txt, without even showing how in the source code they did that), but it hangs up. Modifications to the string array cause different results, such as showing the javap help menu, or saying that the class wasn't found, but I think the way I did the array here is right:
    import java.util.*;
    import java.io.*;
    public class Test {
            try {
             String ls_str;
                String[] cmd = {"C:\\j2sdk1.4.2_04\\bin\\javap", "-c", "-classpath", "H:\\Java\\metricTest", "metricTest > blah.txt", ""};
                Process ls_proc = Runtime.getRuntime().exec(cmd);
             // get its output (your input) stream
             DataInputStream ls_in = new DataInputStream(
                                              ls_proc.getInputStream());
             try {
              while ((ls_str = ls_in.readLine()) != null) {
                  System.out.println(ls_str);
             } catch (IOException e) {
              System.exit(0);
         } catch (IOException e1) {
             System.err.println(e1);
             System.exit(1);
         System.exit(0);
    }

    Also, jesie, I realize that's what I need...the only
    problem is, the name "test.txt" is nowhere to be found
    in the source code! lolLooks like I have to explain this, then.
    When you look at a Java program you'll notice that it always has a "main" method whose signature looks like this:public static void main(String[] args)When you execute that program from the command line, it takes whatever strings you put after the class name and passes them to the main program as that array of strings. For example if you run it likejava UselessProgram foo bar hippothen the "java" command takes the three strings "foo", "bar", and "hippo" and puts them into that args[] array before calling the "main" method.
    That means that inside the "main" method in this case, "args[0]" contains "foo", "args[1]" contains "bar", and "args[2]" contains "hippo".
    Now go back to the example and see how it lines up with that.

  • Runtime exec problem with command "start"

    L.S,
    I'm working on a webservice client for uploading
    and downloading files. When a file is downloaded, it
    should be opened by the appropriate application. I
    know that this is -in theory- possible by issuing a
    start command through Runtime.getRuntime.exec():
    public void doSomething(String realName, DataHandler handler) {
      File outFile = new File(realName);
      FileOutputStream out = new FileOutputStream(outFile);
      handler.writeTo(out);
      out.close();
      String fileName = outFile.getAbsolutePath();
      Process p = Runtime.getRuntime().exec("start " + fileName);
    }Running this on my Win2000 system with J2RE 1.4.2 consistently
    fails with this message:
    java.io.IOException: CreateProcess: start C:\tmp\test.pdf error=2When I issue the exact same command from a DOS shell, Adobe
    starts up with the test document loaded. I now believe that my own
    application is somehow 'holding on to' the file, preventing an
    external application like Adobe from consuming the same file.
    Does anyone know how I can get around a problem like this? How do
    I start the appropriate application and feed it the file that was
    just downloaded by the user?

    I did a search for Runtime.exec and found some good help in this forum. Someone posted something like the following and it works pretty well.
    <<begin code>
    // Determine proper shell command (extend per OS)
    String os_name = System.getProperty("os.name");
    String shellParam "";
    if (os_name.startsWith("Windows"))
    if ( (System.getProperty("os.name").endsWith("NT")) ||
    (System.getProperty("os.name").endsWith("2000")) ||
    (System.getProperty("os.name").endsWith("XP")) )
    shell = "cmd.exe";
    } else
    shell = "command.com";
    shellParam = "/C";
    // Create a string with your program executable
    String command = "myprogram.exe";
    // Create an array of each command, I found that placing "cmd.exe /c"
    // in the same string doesn't work.
    String[] cmd_array = new String[] {
    shell,
    shellParam,
    command
    Runtime.getRuntime().exec( cmd_array );
    <<end code>>
    Do a java API search for Runtime.exec (if you use Eclipse right click and hit Open Declaration) there are ways to invoke exec that support setting of the environment as well as the current directory.

  • Runtime.exec() problem with Linux

    Hi All,
    I have a java program which I am using to launch java programs on all platforms.
    I am using the Runtime.exec() method to start the process in a separate JVM.
    But, I had a problem with the -classpath switch if the directories contained spaces. So I modified the java command which I am passing to the exec() method to something like:
    java -classpath \"./my dir with spaces\" com.harshal.MainThis I had to do because of the problem in windows. But, if I use double quotes in Linux (for the classpath switch in my exec() method), it won't work.
    Can anyone correct me so that I can use the Runtime.exec() method on all platforms to launch the java application even if the classpath directories contains spaces.
    Thank you very much.

    I was reading about the command line args on java's
    tutorial and I found a shocking news. Mac OS doesn't
    support command line args, That's news to me. Could you please elaborate ?
    More important is: I got it working. I figured out I had forgotten to try something before, or, to be more correct, I made an error when trying malcommc's envp suggestion: I used "classpath" as key, not "CLASSPATH", as it should have been.
    Ran a new test, got it working.
    Sample:
    Given a rootdir. Subdirectory "cp test" with a classfile (named "test") without package declaration. Running another class in another directory, using:
    String[] cmd = new String[]{
        "java", "test"
    String[] envp = new String[]{
        "CLASSPATH=rootdir:rootdir/cp test" // <-- without quotes.
    Runtime.getRuntime().exec(cmd, envp);It's been my wrong all the time. I didn't check hard enough. It simply had to work somehow (that's the kind of things that's easy to say afterwards :-)).

  • Runtime.exec() - Need to execute unix command through pipe

    I want to execute something like this from Runtime.exec() :
    tar -czp -C /tmp/ myfile | ssh -qx -c blowfish remoteHost tar -xz -C /tmp/
    If I give the complete string as it is, then the system takes ssh command and the arguments to ssh (-qx) as arguments for tar and, thus, fails. I guess the reason is that the Runtime just takes the first string as the command and passes everything else as arguments to the command.
    How can I achieve this?

    The pipe symbol is interpreted by the shell, so you'd need the command you execute to be a shell (/bin/sh, /bin/csh /bin/bash, etc.) and the rest of it to be the args to that shell.
    Look at the man page for your shell. There should be a -c or somesuch argument that means "take the rest of this line as a command to execute in the shell I'm creating, which will then execute."
    Something like /bin/bash -c foo \| bar Not sure if you have to escape the pipe or not. Futz around with it and see.

  • Runtime.exec  problems

    Hi
    I would like to open a chm file from my "help" menu.
    I got two problem related to that:
    1.The first time the menu is clicked i start the process and the help is opened on top of my application frame.
    but - the second time It is opened - the only wat to recognize i sthe process is still active is to call exitValue (if it get an exception - process is still active) but - how can i make the frame on top of my application frame( the current active frame)
    2.when the application is closed the help application does not "die" with the rest of the application.
    I will be happy to get some ideas of how can i control it.
    this is my code:
    Runtime runtime=  Runtime.getRuntime();
            try {
                if(process==null){
                     process=runtime.exec(new String[] {"cmd.exe","/c" , helpLink});
                else{
                    try {
                        process.exitValue();
                        process = runtime.exec(new String[]{"cmd.exe", "/c", helpLink});
                        if (log.isDebugEnabled())
                            log.debug("process finish working");
                    } catch (IllegalThreadStateException e1) {
                        if (log.isDebugEnabled())
                            log.debug("process still working");
            } catch (IOException e1) {
                if (log.isErrorEnabled()){
                    log.error("could not open help file"+ helpLink);
                    log.error("exception:",e1);
                WorkingAreaManager.getWorkingAreaManagerInstance().displayErrorMessage(COULD_OPEN_HELP);
            }thanks,Liat

    1.The first time the menu is clicked i start the
    process and the help is opened on top of my
    application frame.
    but - the second time It is opened - the only wat to
    recognize i sthe process is still active is to call
    exitValue (if it get an exception - process is still
    active) but - how can i make the frame on top of my
    application frame( the current active frame)Sorry I don't know the answer to that. What happens if you invoke it a second time... does it bring up a completely new frame?
    2.when the application is closed the help application
    does not "die" with the rest of the application.
    I will be happy to get some ideas of how can i
    control it.process.destroy()?

  • Runtime.exec() ... executing a java jar from within an NT command file

    Hello,
    I spent the better part of yesterday seeking insight to this with little success. So I hope someone here can direct me in a productive direction.
    I set-up my runtime.exec in a manner similar to the article on javaworld.com which is often referred to here, with two threads to empty the output and error streams of the NT command file I am executing.
    The command file works perfectly from the command line.
    I am currently attempting to build a gui which will automate regression testing for another application. This requires third party software to be running prior to the execution of the test suite. This third party software is started using an NT command file. The command file sets up an environment (classpath, server flags, etc.) and then executes a jar file. When this command file is run from my Gui, the output is identical to the command being run from the command line. Then when the jar file is to be executed, the command file output shows a "file not found" error, but only when executed from my Gui.
    My call to runtime exec looks like this.
    cmdString = new String("commandtoexecute");
    fileLoc = new String("Fully qualified path to command file");
    String [] envp = new String[0];
    testProcess = Runtime.getRuntime().exec(cmdString, envp, fileLoc);
    // some code to process the output streams of testProcess
    Other Info:
    Gui currently executed within Eclipse IDE
    BEA WebLogic is the third party software

    First, my app has the requirement of allowing the user to start WebLogic if it is not already running.Unfortunately, I can't change the requirement.
    But I would say that in a production environment WebLogic should always be running.
    I guess it's an assumption that I'd make a priori. You're jumping through too many hoops to accomplish something that is better solved with a phone call to the server admin: "Please start the WebLogic service."
    .... Side question ... any recommendations on detecting if it is already running? grin
    Yes, call the server admin and ask why you can't have 99.999% availability of a critical resource.
    Second, development is on a hardened system (i.e. very
    long time getting approval for additional software on
    the system).Cactus and JUnit are both open source. No fees involved. If you can install a JAR, you can use these tools.
    Better yet, you can drive them automatically as part of your Ant build process. A GUI implies a person in front of it to start and monitor the tests. JUnit and Ant are all about automating these things so they're run every time you rebuild and redeploy the code. You get XML reports on test results that are displayable in a browser. You can even e-mail the test summary to all developers so they can see if a test broke the build. If a test breaks, you don't deploy. That's the way to go, IMO.
    When you have a working Ant build.xml, the next step is to automate the build completely using a tool like ThoughtWorks' CruiseControl.
    Thank you for you suggestions though. I will read up on Cactus to see if it could help me here.You're welcome. Good luck. Sorry that I'm not more help.

  • Process/runtime.exec() problem

    i m trying to compile and run java files thru runtime.exec()...i m working on linux...when i compile a singe file it works all right....however when i compile multiple files using the same command only replacing "filename.java" by "*.java" its not working.
    error: cannot read: /home/pico/example/demo/*.java
    1 error
    any help will be appreciated

    I doubt, *.java will get replaced automatically with all your java-files. It's just treated as as file called "*.java", because resolving the wildcard is usually done by a shell which is not running when using Runtime.exec().
    You have to (re)solve it yourself.
    Hope this helped.

  • Runtime.exec problem

    we have a c program which does the encryption on the input files.
    IF we ran this program in unix os, it will take 30 secs to finish.
    But if we call this program using java by calling Runtime.getRuntime().exec(command)
    it takes 20 minutest to finish.
    We wonder why does it take this much time to finish.
    We are having thought that when the program runs in unix os it can get all the resources it want.
    but when run this through java, it is limited to JRE / JVM memory size. --->Am I right?
    Could you please clarify my doubt on the memory size. If I wrong, how can we fix this problem.
    Thanx

    In the case of unix
    u will just run the executable using a.out. For processor its just the execution of the executable, so 30 secs
    In case of java
    step1: It has to interpret the java program line by line after doing required loading, linking and initialization
    of the required libraries and class files.
    step2: It has to create a separate process using Runtime.getRuntime().exec() and wait for the result
    of that process
    so the total time will be step1 + step2 = some time + 30 sec = 20 minutes.

  • Runtime exec() Problem, change working dir

    Hi!
    I have following problem:
    I want to call an executable from my home-directory under Linux this way:
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec("/home/tom/prog/exec-command");
    Unfortunately I'm getting either exception "file not found" (but it's there) or no complain but no program run...
    perhaps something's wrong with the path-name?
    If I call the program in the directory with a shell it works fine.
    Would be very happy if anybody can give a hint!
    Thanks a lot,
    Manuel

    You are interested in the programs output? Does it write to stdout or stderr or both? In any case, my advice is to go multithreading and use one thread to wait for the program to exit, one to read stdout and one to read stderr. If you just use one thread for reading, the program might block. I normally use something like this:
      final int BUFFER = 2048;
      final Process p = Runtime.getRuntime().exec(args);
      //read standard out output of the external executable
      //in seperate thread to avoid I/O deadlocks
      new Thread()
        public void run()
           try
             BufferedInputStream in =  new BufferedInputStream (p.getInputStream());
             int i;
             byte[] buf = new byte[BUFFER];
             while ( (i = in.read(buf, 0, BUFFER)) != -1 )
                System.out.write(buf, 0, i);
             in.close();
           catch (IOException e)
             e.printStackTrace();
      }.start();
      //read standard error output of the external executable
      //in seperate thread for symmetry
      new Thread()
        public void run()
           try
             BufferedInputStream in =  new BufferedInputStream (p.getErrorStream());
             int i;
             byte[] buf = new byte[BUFFER];
             while ( (i = in.read(buf, 0, BUFFER)) != -1 )
                System.err.write(buf, 0, i);
             in.close();
           catch (IOException e)
             e.printStackTrace();
      }.start();
      //Wait for the external process to finish     
      int exitCode = p.waitFor();          
      if ( exitCode != 0 )
        throw new IOException("Executable stopped with error code "+exitCode); Cheers, HJK

  • Runtime.exec() - Problem when using cvs-command

    I have a problem with the Runtime.getRuntime().exec() - Command. I try to execute a command to export files from our cvs-repository. As you hopefully know, cvs produces a lot of output.
    When I start my 'cvs export ... '- command from the console-window of windows, everything works perfect. But when I try to use the Runtime.getRuntime().exec("CVS export ...") the created cvs-subprocess stops after the export of the first three files. When I close the main-window, where the cvs-process was started from, the cvs-process continues working.
    I could see, that many others had the same problem, but I couldn't find a real solution there.
    Is there a possibility to clear/delete the output-buffer of the cvs-subprocess, because I don't really need the information, that cvs gives me. It is enough for me when cvs stores the files :-)
    My source:
    public void executableTest()
    Runtime run = Runtime.getRuntime();
    try
    Process cvsProcess = run.exec("cvs export .... ");
    cvsProcess.waitFor();
    BufferedReader in = new BufferedReader
              ( new InputStreamReader(cvsProcess.getInputStream()) );
         String line;
         while ((line = in.readLine()) != null)
              System.out.println(line);
         catch (Exception e)
         System.out.println(e.getMessage());
    Thanks for your help.

    if the buffer is overflowing, then you don't want to do the waitfor until after you've hit the end of the inputstream, me thinks.

  • Runtime.exec Problem with setting environment

    Hello
    I will run a command with a new process environment. As example I take "ls". If I use the "exec(String)" method it works fine (like it should; my PATH is ...:/usr/bin:...).
    Next when I use "exec(String cmd, String[] env)" with cmd = ls and env = {PATH=} then the programm also prints out the listing of the current directory. In my opinion this shoudn't work.
    I have the problem using jdk1.2.2 (Solaris VM (build olaris_JDK_1.2.2_10, native threads, sunwjit)) on Solaris 8.
    As I understand the exec the method should work like this:
    1. fork a new Process
    2 set environment for the new process
    3 exec the new Programm in this process
    Is this statement right?
    On Solaris 2.6 the program works fine and I get an IOException.
    Some hints way the env for the process isn't set?
    Thanks
    ========================================================
    import java.io.*;
    public class Test {
    /** Version der Klasse. */
    public static final String VERSION = "$Revision:$";
    public static void main(String[] arg) {
    try {
    call("ls", new String[]{"PATH="});
    } catch (Exception ex) {
    System.out.println(ex);
    private static void call(String cmd, String[] env)
    throws Exception
    Runtime rt = Runtime.getRuntime();
    try {
    System.out.println(cmd);
    Process p = rt.exec(cmd, env);
    StreamGobbler errorGobbler = new
    StreamGobbler(p.getErrorStream(), "ERROR", System.err);
    StreamGobbler outputGobbler = new
    StreamGobbler(p.getInputStream(), "OUTPUT", System.out);
    errorGobbler.start();
    outputGobbler.start();
    try {
    p.waitFor();
    } catch (InterruptedException e) {
    if (p.exitValue() != 0) {
    throw new Exception("Process failed");
    } catch (IOException ex) {
    System.out.println("IOException: " + ex.toString());
    class StreamGobbler extends Thread {
    private InputStream m_input;
    private OutputStream m_output;
    private String m_type;
    private StringBuffer m_message;
    StreamGobbler(InputStream is, String type, OutputStream os) {
    this.m_input = is;
    this.m_output = os;
    this.m_type = type;
    this.m_message = new StringBuffer();
    outputGobbler.start();
    try {
    p.waitFor();
    } catch (InterruptedException e) {
    if (p.exitValue() != 0) {
    throw new Exception("Process failed");
    } catch (IOException ex) {
    System.out.println("IOException: " + ex.toString());
    class StreamGobbler extends Thread {
    private InputStream m_input;
    private OutputStream m_output;
    private String m_type;
    private StringBuffer m_message;
    StreamGobbler(InputStream is, String type, OutputStream os) {
    this.m_input = is;
    this.m_output = os;
    this.m_type = type;
    this.m_message = new StringBuffer();
    public synchronized void run() {
    try {
    InputStreamReader reader = new InputStreamReader(m_input);
    BufferedReader bufferedReader = new BufferedReader(reader);
    PrintWriter writer = new PrintWriter(m_output, true);
    String line = null;
    while ( (line = bufferedReader.readLine()) != null) {
    writer.println(m_type + "> " + line);
    this.m_message.append(m_type + "> " + line + "\r\n");
    } catch (IOException ioe) {
    ioe.printStackTrace();
    public synchronized String getMessage() {
    return this.m_message.toString();

    I'm having the same problem...
    Have you been able to solve your problem yet?

  • Problem while executing simple java program

    Hi
    while trying to execute a simple java program,i am getting the following exception...
    please help me in this
    java program :import java.util.*;
    import java.util.logging.*;
    public class Jump implements Runnable{
        Hashtable activeQueues = new Hashtable();
        String dbURL, dbuser, dbpasswd, loggerDir;   
        int idleSleep;
        static Logger logger = Logger.getAnonymousLogger();      
        Thread myThread = null;
        JumpQueueManager manager = null;
        private final static String VERSION = "2.92";
          public Jump(String jdbcURL, String user, String pwd, int idleSleep, String logDir) {
            dbURL = jdbcURL;
            dbuser = user;
            dbpasswd = pwd;
            this.idleSleep = idleSleep;
            manager = new JumpQueueManager(dbURL, dbuser, dbpasswd);
            loggerDir = logDir;
            //preparing logger
            prepareLogger();
          private void prepareLogger(){      
            Handler hndl = new pl.com.sony.utils.SimpleLoggerHandler();
            try{
                String logFilePattern = loggerDir + java.io.File.separator + "jumplog%g.log";
                Handler filehndl = new java.util.logging.FileHandler(logFilePattern, JumpConstants.MAX_LOG_SIZE, JumpConstants.MAX_LOG_FILE_NUM);
                filehndl.setEncoding("UTF-8");
                filehndl.setLevel(Level.INFO);
                logger.addHandler(filehndl);
            catch(Exception e){
            logger.setLevel(Level.ALL);
            logger.setUseParentHandlers(false);
            logger.addHandler(hndl);
            logger.setLevel(Level.FINE);
            logger.info("LOGGING FACILITY IS READY !");
          private void processTask(QueueTask task){
            JumpProcessor proc = JumpProcessorGenerator.getProcessor(task);       
            if(proc==null){
                logger.severe("Unknown task type: " + task.getType());           
                return;
            proc.setJumpThread(myThread);
            proc.setLogger(logger);       
            proc.setJumpRef(this);
            task.setProcStart(new java.util.Date());
            setExecution(task, true);       
            new Thread(proc).start();       
         private void processQueue(){       
            //Endles loop for processing tasks from queue       
            QueueTask task = null;
            while(true){
                    try{
                        //null argument means: take first free, no matters which queue
                        do{
                            task = manager.getTask(activeQueues);
                            if(task!=null)
                                processTask(task);               
                        while(task!=null);
                    catch(Exception e){
                        logger.severe(e.getMessage());
                logger.fine("-------->Sleeping for " + idleSleep + " minutes...hzzzzzz (Active queues:"+ activeQueues.size()+")");
                try{
                    if(!myThread.interrupted())
                        myThread.sleep(60*1000*idleSleep);
                catch(InterruptedException e){
                    logger.fine("-------->Wakeing up !!!");
            }//while       
        public void setMyThread(Thread t){
            myThread = t;
        /** This method is only used to start Jump as a separate thread this is
         *usefull to allow jump to access its own thread to sleep wait and synchronize
         *If you just start ProcessQueue from main method it is not possible to
         *use methods like Thread.sleep becouse object is not owner of current thread.
        public void run() {
            processQueue();
        /** This is just another facade to hide database access from another classes*/
        public void updateOraTaskStatus(QueueTask task, boolean success){
            try{         
                manager.updateOraTaskStatus(task, success);
            catch(Exception e){
                logger.severe("Cannot update status of task table for task:" + task.getID() +  "\nReason: " + e.getMessage());       
        /** This is facade to JumpQueueManager method with same name to hide
         *existance of database and SQLExceptions from processor classes
         *Processor class calls this method to execute stored proc and it doesn't
         *take care about any SQL related issues including exceptions
        public void executeStoredProc(String proc) throws Exception{
            try{
                manager.executeStoredProc(proc);
            catch(Exception e){
                //logger.severe("Cannot execute stored procedure:"+ proc + "\nReason: " + e.getMessage());       
                throw e;
         *This method is only to hide QueueManager object from access from JumpProcessors
         *It handles exceptions and datbase connecting/disconnecting and is called from
         *JumpProceesor thread.
        public  void updateTaskStatus(int taskID, int status){       
            try{
                manager.updateTaskStatus(taskID, status);
            catch(Exception e){
                logger.severe("Cannot update status of task: " + taskID + " to " + status + "\nReason: " + e.getMessage());
        public java.sql.Connection getDBConnection(){
            try{
                return manager.getNewConnection();
            catch(Exception e){
                logger.severe("Cannot acquire new database connection: " + e.getMessage());
                return null;
        protected synchronized void setExecution(QueueTask task, boolean active){
            if(active){
                activeQueues.put(new Integer(task.getQueueNum()), JumpConstants.TH_STAT_BUSY);
            else{
                activeQueues.remove(new Integer(task.getQueueNum()));
        public static void main(String[] args){
                 try{
             System.out.println("The length-->"+args.length);
            System.out.println("It's " + new java.util.Date() + " now, have a good time.");
            if(args.length<5){
                System.out.println("More parameters needed:");
                System.out.println("1 - JDBC strign, 2 - DB User, 3 - DB Password, 4 - sleeping time (minutes), 5 - log file dir");
                return;
            Jump jump = new Jump(args[0], args[1], args[2], Integer.parseInt(args[3]), args[4]);
            Thread t1= new Thread(jump);
            jump.setMyThread(t1);      
            t1.start();}
                 catch(Exception e){
                      e.printStackTrace();
    } The exception i am getting is
    java.lang.NoClassDefFoundError: jdbc:oracle:thin:@localhost:1521:xe
    Exception in thread "main" ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
    JDWP exit error AGENT_ERROR_NO_JNI_ENV(183):  [../../../src/share/back/util.c:820] Please help me.....
    Thanks in advance.....sathya

    I am not willing to wade through the code, but this portion makes me conjecture your using an Oracle connect string instead of a class name.
    java.lang.NoClassDefFoundError: jdbc:oracle:thin:@localhost:1521:xe

Maybe you are looking for

  • Problem with ASA 5505 VPN config

    Hi to all, I have a problem with ASA 5505 remote access vpn. I have site-to-site VPN and I need that my VPN clients can access IP subnets that I have behind site-to-site VPN. All that I have tried I get and error to my log "Flow is a loopback". So wh

  • Upgrading systems

    If I am running v 10.6.8. on my MacBook Pro, can I upgrade to Mavericks for free?

  • What is the best strategy to purge a set of database tables.

    Hi, I have 6 tables I would require to purge data from. 1 parent table - All of the data that needs to be purged are from a partition created on this table 5 child table - Using the parent record identifier, these records needs to be purged as well.

  • How do I send string data into DIAdem via a channel?

    Using a TO.DATASHEET reference, ChnValSet doesn't work with strings. It's fine with numbers and dates, just not strings. I'm not sure if the CHT variable is useful for me or not. Thanks.

  • Curve 9320/9360 7.1 update issues - can't scroll!

    Have had the same problem on some of our Curves with the 7.1 update. They can't scroll through text message/message conversations using the trackpad. With the 9360s its fine as if we downgrade to 7.0 the problem doesn't happen, but the 9320s come wit