Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / July 2006

Tip: Looking for answers? Try searching our database.

Running C and Java programs through Servlet

Thread view: 
abdel.olakara@gmail.com - 31 Jul 2006 18:55 GMT
Hello everybody..
I have a tipical problem.. I need to run a c , java or a command from a
servlet.. I tried using Runtime class as shown below :
.
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("<command / c program>");
. . .

But this code works fine on a stand alone java program.. when i put the
same code inside the servlet.. i don't get even the data from the error
stream..
pls help!
Larry - 31 Jul 2006 20:17 GMT
> Hello everybody..
> I have a tipical problem.. I need to run a c , java or a command from a
[quoted text clipped - 8 lines]
> stream..
> pls help!

Are you very familiar with servlets?  The standard output for servlets
goes to the application server (weblogic, jboss, etc.) console.  So
maybe there is output, but you're not looking in the right place   ;-)
Roland de Ruiter - 31 Jul 2006 22:15 GMT
> Hello everybody..
> I have a tipical problem.. I need to run a c , java or a command from a
[quoted text clipped - 8 lines]
> stream..
> pls help!

You'll need to drain the standard error and output streams of the Process p.
The following class does this for you: it copies the output of the
process to Java's System.out and System.err. If you need the output for
further processing in your servlet, you'll have to modify method
flush(boolean).

// Begin of OutputAbsorber.java
import java.io.*;

public class OutputAbsorber implements Runnable {
    public static void main(String[] args) {
        // Example usage
        final String command = "cmd.exe /c dir";
        try {
            Process p = Runtime.getRuntime().exec(command);
            OutputAbsorber.absorb(p);
            p.waitFor();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void absorb(Process p) {
        if (p != null) {
            Thread outAbsorb = new Thread(new OutputAbsorber(
                    p.getInputStream(), false));
            Thread errAbsorb = new Thread(new OutputAbsorber(
                    p.getErrorStream(), true));
            // outAbsorb.setPriority(Thread.MIN_PRIORITY);
            // errAbsorb.setPriority(Thread.MIN_PRIORITY);
            outAbsorb.start();
            errAbsorb.start();
        }
    }

    private final static int MAX_BUF = 512;
    private final boolean dropCR;
    private final boolean dropNL;
    private int limit;
    private final byte[] outbuf;
    private final InputStream stream;
    private final boolean toStdErr;

    private OutputAbsorber(InputStream stream, boolean isStdErr) {
        this.stream = stream instanceof BufferedInputStream ? stream
                : new BufferedInputStream(stream);
        this.toStdErr = isStdErr;
        this.outbuf = new byte[MAX_BUF];
        this.limit = 0;
        String lineSeparator = System.getProperty("line.separator");
        if ("\n".equals(lineSeparator)) {
            this.dropNL = false;
            this.dropCR = true;
        } else if ("\r".equals(lineSeparator)) {
            this.dropNL = true;
            this.dropCR = false;
        } else {
            this.dropNL = false;
            this.dropCR = true;
        }
    }
    private int absorb(final int b) {
        if (b >= 0) {
            switch (b) {
            case '\n':
                if (!dropNL) {
                    flush(true);
                }
                break;
            case '\r':
                if (!dropCR) {
                    flush(true);
                }
                break;
            default:
                append((byte) b);
                break;
            }
        }
        return b;
    }
    private void append(final byte b) {
        if (limit >= MAX_BUF) {
            flush(false);
        }
        outbuf[limit++] = b;
    }
    private void flush(final boolean addNewline) {
        try {
            String s = new String(outbuf, 0, limit);
            if (toStdErr) {
                if (addNewline) {
                    System.err.println(s);
                } else {
                    System.err.print(s);
                }
            } else {
                if (addNewline) {
                    System.out.println(s);
                } else {
                    System.out.print(s);
                }
            }
        } finally {
            limit = 0;
        }
    }
    private void maybeFlush() {
        if (limit > 0) {
            flush(true);
        }
    }
    public void run() {
        try {
            while (absorb(stream.read()) != -1) {
                Thread.yield();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                stream.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            try {
                maybeFlush();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}
// End of OutputAbsorber.java
Signature

Regards,

Roland



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.