Gettig SOAPBody as string or as InputStream

I am receiving SOAP messages over jms Queues. After receiving messages I need to get the content of SOAP:Body as a String or as InputStream. How can this be done?

depending on the type of message u're receiving, by that i mean the class of the message, e.g. OMElement?

Similar Messages

  • It's posible inject a String in a InputStream??

    Hi all.
    I'm beginning work with XML, and in this moment i need process not very big xml FILES, this because files arrives in very short time, my problem now is with SAX/DOM, in general this process "files" and i have a string variable with the xml inside!!
    It's possible inject this String in a InputStream to don't create a temp file???
    Ideas to work and process xml directly (links to read about this) is welcome.
    thank's

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new org.xml.sax.InputSource(new java.io.StringReader("your_string")));

  • How to get InputStream from String ?

    Hi !
    I want to get InputStream object from String.
    String str = "balabalabala";
    InputStream stream = getInputStream(str);
    How to realize getInputStream(str) function ?
    Thanks!

    The preferred method nowadays is to use Readers and Writers for String data - hence StringReader(String). If you're going to operate on the InputStream directly, then I'd modify your code to use the Reader calls and go that route.
    If, however, you need to pass the InputStream to some other piece of API that requires an InputStream instead of a Reader, then the ByteArrayInputStream is probably your best bet. StringBufferInputStream is deprecated because it doesn't work reliably in the face of many character encodings.
    Speaking of encodings - never call Strng.getBytes() - always use the getBytes(character-encoding) version, so you KNOW what encoding you're getting!
    Grant

  • String to inputStream

    Hi I'm trying to "convert a string to an inputstream. I'm working with the JTidy API which needs an inputstream for doing the parseDOM(var,var) method, everything works fine when my data comes from a file and when I use FileInputStream but it wont work with the InputStream.
    It looks to me that the InputStream is empty. What I'm basically doing is:
    String myInputStream = "blahdiblah";
    try{
    System.out.println("myInputStream:" + + myInputStream.read()); // gives me 98 the value of the first char
    }catch( Exception e ) {
    System.err.println("error:" + e.toString() );
    InputStream in = null;
    StreamSource myStreamSource = new StreamSource(myInputStream);
    in = myStreamSource.getInputStream();
    try{
    System.out.println("1 test" + + in.read()); // gives me nothing back, while it should give 98
    }catch( Exception e ) {
    System.err.println("error:" + e.toString() );
    Why does the first read-method returns the Decimal ASCII of the letter "b" and the second does not?
    Can anyone tell me what I'm doing wrong? I'm not really familiar with these streaming stuff, any help would be great !

    String data = "sfgafgagafg";
    ByteArrayInputStream bais = new ByteArrayInputStream(data.getBytes())

  • Strange exception when deploying BC4J as EJB in 8i CORBA.BAD_PARAM: null Strings are

    I am trying to deploy BC4J as Ejb to 8i (8.1.6). I use the following deployment method with j: my Jdev root.
    setjboenv j: ejb8i
    loadjava - u user/passwd@host:port:sid - thin -v - r grant "SYS,PUBLIC" j:lib\xmlparserv2.jar
    loadjava - u user/passwd@host:port:sid - thin -v - r grant "SYS,PUBLIC" j:lib\jbomt.zip
    loadjava - u user/passwd@host:port:sid - thin -v - r grant "SYS,PUBLIC" j:lib\jboejb.jarI then create a deployment profile for ejb 8i with the ide. (Without deploying)
    I then use loadjava outside the IDE to deploy the 2 jar files created
    MyProject1CommonEJB.jar
    and
    Myproject1.jar
    I then use the ide again to deploy the bean profile
    Package1ModuleServerEJB.prf
    The last step fails with the error :
    Publishing EJBHome...org.omg.CORBA.BAD_PARAM: null Strings are illegal in IIOP. Please correct your application or run the ORB in backward compatibility mode. minor code: 0 completed: No
    void oracle.aurora.ejb.deployment.GenerateEjb.invoke()
    void oracle.aurora.server.tools.sess_iiop.ToolImpl.invoke(java.lang.String[], java.io.InputStream, java.io.PrintStream, java.io.PrintStream)
    void oracle.aurora.ejb.deployment.GenerateEjb.main(java.lang.String[])
    Exception in thread main
    Strangely, when I test this EJB with the tester (middle tier = remote ejb) it works, but from JSP's I get an application error : "Unknown Exception"
    I am using Jdev 3.1
    Also using the deploy option when creating the deployment profile fails apparantly due to the missing grant "SYS,PUBLIC" when loading classes to the database before deploying the bean.
    What can be done ?
    null

    Hi Blaise
    Thanks for the reply. I have tried to do the complete deployment from within Jdev, but now I get the following error right at the end of the deployment.
    /BC4J1AppModuleEjb/EjbObject_RemoteBC4J1AppModuleEjb:ORA-29535: source requires recompilationjava.lang.NullPointerException at sun.tools.java.Environment.error(Environment.java) at sun.tools.java.Environment.error(Environment.java) at sun.tools.java.Environment.error(Environment.java) ..... etc.
    I have tried to deploy to a clean schema with the java privilages granted as described in the Jdev release notes.
    I included the following libraries in my project :
    JBO JDBC816 PATCH
    JBO OSQL Domains
    JDeveloper Runtime
    Oracle 8.1.6 JDBC
    Connection Manager
    JBO Runtime
    JBO VB Runtime
    JBO 8i Runtime
    SQLJ Runtime
    JBO 8i Client
    JBO Vanilla Domains
    JBO EJB Runtime
    JServer
    Oracle XML SQL Utility
    ORACLE XML Parser 2.0
    Then I just used the deployment wizzard
    null

  • XML document - request string

    Hi Experts,
    Could you please tell me, how to pass XML document as a request string to the webservice scenario. Inside the service, I have to do the schema validation for the request . Please guide me, how to proceed further?
    Regards
    Sara

    Hi SARA,
    use following Code written in SAX parsing .this will fulfil your requirment.This handle Special character also.
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.Attributes;
    import org.xml.sax.helpers.DefaultHandler;
    import org.xml.sax.SAXException;
    import com.sap.aii.mapping.api.StreamTransformation;
    import com.sap.aii.mapping.api.StreamTransformationException;
    public class SimpleForwardMappingString extends DefaultHandler implements StreamTransformation
         private List m_arlCurrent = new ArrayList();
         private List m_arlBOList = new ArrayList();
         private List m_arlObjectList = new ArrayList();
        public static int counter = 0;
         String listName = "newList";
         public  StringBuffer m_totalElementsBuffer = new StringBuffer();
         String startData = "<inCanonStream>";
         String endData = "</inCanonStream>";
         private Map param = null;
         /** Constant Strings used in Forward Mapping */
         public static void main(String args[])
              try {
                      InputStream in = new FileInputStream(new File("C:
    Documents and Settings
    281152
    Desktop
    Cannonical12321.xml"));
                   OutputStream out = new FileOutputStream(new File("C:
    Documents and Settings
    281152
    Desktop
    Cannonical21.xmlOut.xml"));               
                   SimpleForwardMappingString myMapping = new SimpleForwardMappingString();
              catch (Exception e)
                   e.printStackTrace();
         public void execute(InputStream arg0, OutputStream arg1)
         throws StreamTransformationException
              Writer out;
              try
                   out = new OutputStreamWriter(arg1, "UTF16");
                   /** Building the SAX parser */
                   getXMLDoc(arg0, arg1);
                   arg1.write(m_totalElementsBuffer.toString().getBytes("UTF16"));
              catch (IOException e)
                   System.out.println("Error : io" + e.getMessage());
              catch (Exception e)
                   System.out.println("Error :" + e.getMessage());
         /* (non-Javadoc)
    @see com.sap.aii.mapping.api.StreamTransformation#setParameter(java.util.Map)
         public void setParameter(Map arg0)
         public void getXMLDoc(InputStream inputStream, OutputStream outputStream)
    Defines a factory API that enables applications to configure and
    obtain a SAX based parser to parse XML documents. Once an application
    has obtained a reference to a SAXParserFactory it can use the
    factory to configure and obtain parser instances.
              SAXParserFactory factory = SAXParserFactory.newInstance();
              try
                   factory.setNamespaceAware(true);
                   factory.setValidating(true);
                   SAXParser saxParser = factory.newSAXParser();
    Parse the content of the given {@link java.io.InputStream}
    instance as XML using the specified
    {@link org.xml.sax.helpers.DefaultHandler}.
    @param inputstream InputStream containing the content to be parsed.
    @param cobject The SAX DefaultHandler to use.
    @exception IOException If any IO errors occur.
    @exception IllegalArgumentException If the given InputStream is null.
    @exception SAXException If the underlying parser throws a
    SAXException while parsing.               
                   saxParser.parse(inputStream, this);
              catch (FactoryConfigurationError e)
                   System.out.println("Error");
              catch (ParserConfigurationException e)
                   e.printStackTrace();
              catch (SAXException e)
                   e.printStackTrace();
              catch (IOException e)
                   e.printStackTrace();
         /** ===========================================================
                             Methods Overriding in SAX Default Handler
              ===========================================================
    Receive notification of the beginning of the document.
    By overriding this method in a subclass to take specific actions
    at the beginning of a document (such as allocating the root node
    of a tree or creating an output file)     
         public void startDocument()throws SAXException
              if(m_totalElementsBuffer.length()>0)
                                m_totalElementsBuffer = new StringBuffer();
                                counter = 0;
              m_totalElementsBuffer.append(m_prologue);
              m_totalElementsBuffer.append(m_nameSpace);
              m_totalElementsBuffer.append(startData);     }
    Receive notification of the end of the document.
    By overriding this method in a subclass to take specific
    actions at the end of a document (such as finalising a tree
    or closing an output file)     
         public void endDocument()throws SAXException
              m_totalElementsBuffer.append(endData);
              m_totalElementsBuffer.append(m_rootElementEnd);
    Receive notification of the start of an element.
    By overriding this method in a subclass to take specific
    actions at the start of each element (such as allocating
    a new tree node or writing output to a file)
         public void startElement(String namespaceURI, String name, String qName, Attributes attrs)
              throws SAXException
              /** If current List is not empty then append node to StringBuffer */
                   m_totalElementsBuffer.append("&lt;" + name + "&gt;");
    Receive notification of the end of an element.
    By overriding this method in a subclass to take specific
    actions at the end of each element (such as finalising
    a tree node or writing output to a file)
         public void endElement(String uri, String name, String qName) throws SAXException
                   m_totalElementsBuffer.append("&lt;/" + name + "&gt;");
    Receive notification of character data inside an element.
    By overriding this method to take specific actions for each
    chunk of character data (such as adding the data to a node
    or buffer, or printing it to a file)     
         public void characters(char buf[], int offset, int len)
              throws SAXException
              String s = new String(buf, offset, len);
              if (null != s && s.length() >0)
                   if(s.equalsIgnoreCase("&"))
                         //System.out.println("FOUND AND SYMBOL");
                         String s1 = s.replaceAll("&","_-#_");
                         //System.out.println("s= " +s1);
                         s = s1;
                   if(s.equalsIgnoreCase("<"))
                         //System.out.println("FOUND AND SYMBOL");
                         String s1 = s.replaceAll("<","_#-_");
                         //System.out.println("s= " +s1);
                         s = s1;
                   m_totalElementsBuffer.append(s);
    Thanks
    Sunil Singh

  • String to Stream

    Hi!
    How do you convert a String to an InputStream?
    I'm sending more than one XML file in a String through a Socket. I receive an Input Stream and convert it to a String. but i now need this String to be an Input Stream!
    Andr�

    Hi!
    How do you convert a String to an InputStream?
    I'm sending more than one XML file in a String through
    a Socket. I receive an Input Stream and convert it to
    a String. but i now need this String to be an Input
    Stream!
    Andr�Why ? Can't you use the original input stream (the socket's one)?

  • InputStream hung from Runtime.getRuntime().exec

    Dear all,
    I am trying to use the following code to run a Runtime.getRuntime().exec("my_selection.exe") method and redirect all the output from the process to my JTextArea.
    My program is an executable called "my_selection.exe", which runs under DOS something like:
    My Selection Utilities:
    type the command -
    o : open an item
    l : list subitems
    q : exit
    Please select your options:But when I run my Test program, the above selection menu does not show in my JTextArea. Only after I type q (which is exit command in my_selection), will all the output shown in TextArea.
    I tested the inputstream.available(), but it always == 0.
    Anyone can help point me out what is wrong here?
    BTW, when I use the same program to run "copy a.txt a" by exec("cmd.exe"), it works ok, no matter whether it prompts for owerwrite the existing file or not.
    Many thanks!
    I tried the code,
    /* part of the code */
    public static void main(String[] args) {
         Test t = new Test();
         t.setTitle("Basic GUI");
         t.init(); // init GUI
         t.connect();
         t.show();
    private static void log(Object text) {
         getTextArea().setCaretPosition(getTextArea().getText().length());
         getTextArea().setText(getTextArea().getText() + text.toString() + "\n");
    private Thread getInputStreamListener() {
         if(listener == null) {
              Runnable runnable = new Runnable() {
                   public void run() {
                        try {
                             String text = "";
                             while (true) {
                                  while (inputStream.available()==0) {
                                       Thread.currentThread().sleep(100);
                                  byte[] bytes = new byte[inputStream.available()];
                                  inputStream.read(bytes);
                                  text = new String(bytes);
                                  log("> " + text);
                        catch(Exception e) {
                             handleException(e);
              listener = new Thread(runnable);
              listener.setName("out listener");
              listener.setPriority(2);
              listener.start();
         return listener;
    private Thread getErrorStreamListener() {
         if(listener == null) {
              Runnable runnable = new Runnable() {
                   public void run() {
                        try {
                             String text = "";
                             while (true) {
                                  while (errorStream.available()==0) {
                                       Thread.currentThread().sleep(100);
                                  byte[] bytes = new byte[errorStream.available()];
                                  errorStream.read(bytes);
                                  text = new String(bytes);
                                  log("> " + text);
                        catch(Exception e) {
                             handleException(e);
              listener = new Thread(runnable);
              listener.setName("out error listener");
              listener.setPriority(2);
              listener.start();
         return listener;
    private static void handleException(Throwable t) {
         log(t);
    private void connect() {
         try{
              process = Runtime.getRuntime().exec(new String[] {"my_selection.exe"});
              inputStream = new BufferedInputStream(process.getInputStream());
              outputStream = new BufferedOutputStream(process.getOutputStream());
              errorStream = new BufferedInputStream(process.getErrorStream());
              getInputStreamListener();
              getErrorStreamListener();
         catch(Exception e) {
              log(e);

    Note in the above code all "listener" variable in:
    private Thread getErrorStreamListener() method
    show be "listener1".
    Even I changed it, it does not work either.
    Please help.
    Thanks!

  • InputStream only gets to 8192 bytes

    I'm guessing this must be something simple I don't understand about InputStreams, but the following code only reads "README.txt" to 8192 bytes, despite the fact that fis.available() returns somewhere around 13000:
    void loadDoc(){
        String str;
        try{
            InputStream is = getClass().getResourceAsStream("README.txt");
            int size = is.available();
            byte[] bytes = new byte [size];
            int read = is.read(bytes);
            System.err.println("Available:" + size + "\nRead: " + read);
            is.close();
            str = new String(bytes);
        } catch (Exception e){
            System.err.println(e);
            str = "The file README.txt could not be found; it may have been deleted or moved.\n";
        displayArea.setText(str);
        displayArea.setCaretPosition(0);
    }I'm suspicious, since 8192 is a power of 2, which makes me think that it's not stopping at some arbitrary point or due to something in the file. What's going on here?

    From what the docs for available() say, I'd have thought it would read the full 13000 or whatever. It seems like it's blocking sooner than it's supposed to.
    I'd guess one of three things, in order of decreasing likelihood:
    * "Blocking" has a specific meaning that doesn't extend to what's happening here, which I'd guess is simply that some underlying buffer has a size of 8k, so that's all that can be deliverd at once.
    * You're not running the code you think you are, or have otherwise misinterpreted what you observed.
    * There's a bug in the stream implementation.
    Presumably if you loop here, you'll get the remaining bytes on the next read (if it is in fact the first point above that's causing this). Decorating the InputStream with a BufferedInputStream might do this for you, but I wouldn't count on it--you'd still have to put the reading in a loop.
    On other alternative would be to turn the URL into a URI, the URI into a File, and then build a RandomAccessFile from the File, and use ReadFully. That feels like overkil to me, though.

  • Error while executing a process - it hangs!

    Hi there, please help me with this problem:
    I'm executing a CMD file with the next code and it hangs
    File file = new file("E:\\NDM_TEST\\UPLOAD_ENC\\CA210105.001.zip")
    Vector response = null;
    Log.debugLog("File to transport as a response " + getFileAbsolutePath());
    if (NDM.executeCMD(file.getFileAbsolutePath(), file.getFileName()) == 0) {
    public static int executeCMD(String fileAbsolutePath, String fileName) {
      int exitValue = 1;
      String chainn = "";
      try {
        Log.debugLog("starting CMD execution");
        String arguments[] = new String[1];
        arguments[0] = "\"" + getNDM_BATCH() + "\" " + fileAbsolutePath + " " + fileName;
        exitValue = WindowsExec.execute(arguments);
      } catch (Exception e) {
        Log.log("[ERROR] NDM.ejecutaBatch ==> " + e);
      } finally {
        return exitValue;
    public class WindowsExec {
      public static int execute(String args[]) {
        int exitVal = 1;
        if(args.length < 1) {
          Log.log("USAGE; java WindowsExec <cmd>");
          System.exit(1);
        try {
          String osName = System.getProperty("os.name");
          String[] cmd = new String[3];
          Runtime rt = Runtime.getRuntime();
          String toExecute = cmd[0] + " " + cmd[1] + " " + cmd[2];
          Log.debugLog(toExecute);
          Process proc = rt.exec(toExecute);
          Streammer errorStreammer = new Streammer(proc.getErrorStream(), "ERROR");
          Streammer outPutStreammer = new Streammer(proc.getInputStream(), "OUTPUT");
          errorStreammer.start();
          outPutStreammer.start();
          exitVal = proc.waitFor();
        } catch(Throwable t) {
          t.printStackTrace();
        } finally {
          return exitVal;
    public class Streammer extends Thread {
      InputStream is;
      String type;
      Streammer(InputStream is, String type) {
        this.is = is;
        this.type = type;
      public void run() {
        try {
          InputStreamReader isr = new InputStreamReader(is);
          BufferedReader br = new BufferedReader(isr);
          String line = null;
          while ((line = br.readLine()) != null) {
            Log.log(type + " > " + line);
        } catch (Exception ioe) {
          ioe.printStackTrace();
    }The output of the line Log.debugLog(toExecute); is:
    cmd.exe /C "E:\NDM_TEST\PROCESS\TX_TEST.CMD" E:\NDM_TEST\UPLOAD_ENC\CA210105.001.zip CA210105.001.zip
    If i run this output from a command prompt it runs ok, but when invoked from my java program it hangs and never ends

    You are right, at the moment I paste my code, I delete three important lines, here is the right code:
    File file = new file("E:\\NDM_TEST\\UPLOAD_ENC\\CA210105.001.zip")
    Vector response = null;
    Log.debugLog("File to transport as a response " + getFileAbsolutePath());
    if (NDM.executeCMD(file.getFileAbsolutePath(), file.getFileName()) == 0) {
    public static int executeCMD(String fileAbsolutePath, String fileName) {
      int exitValue = 1;
      String chainn = "";
      try {
        Log.debugLog("starting CMD execution");
        String arguments[] = new String[1];
        arguments[0] = "\"" + getNDM_BATCH() + "\" " + fileAbsolutePath + " " + fileName;
        exitValue = WindowsExec.execute(arguments);
      } catch (Exception e) {
        Log.log("[ERROR] NDM.ejecutaBatch ==> " + e);
      } finally {
        return exitValue;
    public class WindowsExec {
      public static int execute(String args[]) {
        int exitVal = 1;
        if(args.length < 1) {
          Log.log("USAGE; java WindowsExec <cmd>");
          System.exit(1);
        try {
          Runtime rt = Runtime.getRuntime();
          String[] cmd = new String[3];
          cmd[0] = "cmd.exe";
          cmd[1] = "/C";
          cmd[2] = args[0];
          String toExecute = cmd[0] + " " + cmd[1] + " " + cmd[2];
          Log.debugLog(toExecute);
          Process proc = rt.exec(toExecute);
          Streammer errorStreammer = new Streammer(proc.getErrorStream(), "ERROR");
          Streammer outPutStreammer = new Streammer(proc.getInputStream(), "OUTPUT");
          errorStreammer.start();
          outPutStreammer.start();
          exitVal = proc.waitFor();
        } catch(Throwable t) {
          t.printStackTrace();
        } finally {
          return exitVal;
    public class Streammer extends Thread {
      InputStream is;
      String type;
      Streammer(InputStream is, String type) {
        this.is = is;
        this.type = type;
      public void run() {
        try {
          InputStreamReader isr = new InputStreamReader(is);
          BufferedReader br = new BufferedReader(isr);
          String line = null;
          while ((line = br.readLine()) != null) {
            Log.log(type + " > " + line);
        } catch (Exception ioe) {
          ioe.printStackTrace();
    }I hope you can help me know... thanks!.

  • Shell commands from JSP after Forms migration

    During application migration from forms 9i to JSP & BC4J, I have to code the following Forms code into my JSP application.This is for a button pressed trigger.
    DECLARE
    RENAME_STRING VARCHAR2(120):= 'RENAME C:\BRC\PDATA' ||:DRAWING_ACCOUNTS.ACCOUNT_ID|| '.TXT P' || :DRAWING_ACCOUNTS.ACCOUNT_ID || TO_CHAR(SYSDATE,'DDMMYY')|| '.txt';
    BEGIN
    HOST( RENAME_STRING, no_screen );
    web.show_document( 'http://hostname/selectfile.html', '_new');
         IF NOT Form_Success THEN
              Message('Error -- File not Renamed.');
         END IF;
    END;
    How can I do this simple sending of OS commands in JSP, any ideas?

    Hi,
    Not only rename commands but I have to pass several other os commands like 'sqlldr' for data upload as well. Therefore, I need a reusable piece of code for that. I have acheived some way for that using the following code.
    put the following file in that package.
    package BankrecBC4J;
    import java.util.*;
    import java.io.*;
    import java.net.*;
    import java.text.*;
    import java.util.zip.*;
    class StreamGobbler extends Thread
    InputStream is;
    String type;
    StreamGobbler(InputStream is, String type)
    this.is = is;
    this.type = type;
    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);
    } catch (IOException ioe)
    ioe.printStackTrace();
    public class GoodWindowsExec
    private static final boolean NATIVE_COMMANDS = true;
    //Allow browsing and file manipulation only in certain directories
         private static final boolean RESTRICT_BROWSING = false;
    //If true, the user is allowed to browse only in RESTRICT_PATH,
    //if false, the user is allowed to browse all directories besides RESTRICT_PATH
    private static final boolean RESTRICT_WHITELIST = false;
    //Paths, sperated by semicolon
    //private static final String RESTRICT_PATH = "C:\\CODE;E:\\"; //Win32: Case important!!
         private static final String RESTRICT_PATH = "/etc;/var";
         * Command of the shell interpreter and the parameter to run a programm
         private static final String[] COMMAND_INTERPRETER = {"cmd", "/C"}; // Dos,Windows
         //private static final String[] COMMAND_INTERPRETER = {"/bin/sh","-c"};      // Unix
         * Max time in ms a process is allowed to run, before it will be terminated
    private static final long MAX_PROCESS_RUNNING_TIME = 30 * 1000; //30 seconds
         //Normally you should not change anything after this line
         //Change this to locate the tempfile directory for upload (not longer needed)
         private static String tempdir = ".";
         private static String VERSION_NR = "1.1a";
         private static DateFormat dateFormat = DateFormat.getDateTimeInstance();
    public GoodWindowsExec(String g)
    System.out.println(" hello " + g);
    /*if (g.length < 1)
    System.out.println("USAGE: java GoodWindowsExec <cmd>");
    System.exit(1);
    try
    String osName = System.getProperty("os.name" );
    String[] cmd = new String[3];
    System.out.println("here ");
    if( osName.equals( "Windows NT" ) )
    cmd[0] = "cmd.exe" ;
    cmd[1] = "/C" ;
    cmd[2] = g;
    else if( osName.equals( "Windows 2000" ) )
    System.out.println("Windows 2000");
    cmd[0] = "command.com" ;
    cmd[1] = "/C" ;
    cmd[2] = g;
    else if( osName.equals( "Windows XP" ) )
    System.out.println("Windows XP");
    cmd[0] = "command.com" ;
    cmd[1] = "/C" ;
    cmd[2] = g;
    else if( osName.equals( "Windows 95" ) )
    cmd[0] = "command.com" ;
    cmd[1] = "/C" ;
    cmd[2] = g;
    Runtime rt = Runtime.getRuntime();
    System.out.println("Execing " + cmd[0] + " " + cmd[1]
    + " " + cmd[2]);
    Process proc = rt.exec(cmd);
         * Starts a native process on the server
         *      @param command the command to start the process
         *     @param dir the dir in which the process starts
    // any error message?
    StreamGobbler errorGobbler = new
    StreamGobbler(proc.getErrorStream(), "ERROR");
    // any output?
    StreamGobbler outputGobbler = new
    StreamGobbler(proc.getInputStream(), "OUTPUT");
    // kick them off
    errorGobbler.start();
    outputGobbler.start();
    // any error???
    int exitVal = proc.waitFor();
    System.out.println("ExitValue: " + exitVal);
    } catch (Throwable t)
    t.printStackTrace();
         * Converts some important chars (int) to the corresponding html string
         static String conv2Html(int i) {
              if (i == '&') return "&amp;";
              else if (i == '<') return "&lt;";
              else if (i == '>') return "&gt;";
              else if (i == '"') return "&quot;";
              else return "" + (char) i;
    static String startProcess(String command, String dir) throws IOException {
              StringBuffer ret = new StringBuffer();
              String[] comm = new String[3];
              comm[0] = COMMAND_INTERPRETER[0];
              comm[1] = COMMAND_INTERPRETER[1];
              comm[2] = command;
              long start = System.currentTimeMillis();
              try {
                   //Start process
                   Process ls_proc = Runtime.getRuntime().exec(comm, null, new File(dir));
                   //Get input and error streams
                   BufferedInputStream ls_in = new BufferedInputStream(ls_proc.getInputStream());
                   BufferedInputStream ls_err = new BufferedInputStream(ls_proc.getErrorStream());
                   boolean end = false;
                   while (!end) {
                        int c = 0;
                        while ((ls_err.available() > 0) && (++c <= 1000)) {
                             ret.append(conv2Html(ls_err.read()));
                        c = 0;
                        while ((ls_in.available() > 0) && (++c <= 1000)) {
                             ret.append(conv2Html(ls_in.read()));
                        try {
                             ls_proc.exitValue();
                             //if the process has not finished, an exception is thrown
                             //else
                             while (ls_err.available() > 0)
                                  ret.append(conv2Html(ls_err.read()));
                             while (ls_in.available() > 0)
                                  ret.append(conv2Html(ls_in.read()));
                             end = true;
                        catch (IllegalThreadStateException ex) {
                             //Process is running
                        //The process is not allowed to run longer than given time.
                        if (System.currentTimeMillis() - start > MAX_PROCESS_RUNNING_TIME) {
                             ls_proc.destroy();
                             end = true;
                             ret.append("!!!! Process has timed out, destroyed !!!!!");
                        try {
                             Thread.sleep(50);
                        catch (InterruptedException ie) {}
              catch (IOException e) {
                   ret.append("Error: " + e);
              return ret.toString();
    In the first line of the JSP file include the package
    <%@page import="BankrecBC4J.*" %>
    and call
    it this way:from the jsp page
    new GoodWindowsExec ("calc"); //
    which should open up the calciulator, and should do for other os commands as well.
    Thanks

  • Portal application can't read request info

    hi all,
    i use  portal application for change portal user's infos.but when i sent request info,
    request.getServletRequest().getInputStream() method is cutting my sending line after 90. character.
    in R3 side i use HTTP_POST function and fill request info (table paramater).
    i tried to send 2 line(less than 90 character) in request info, but i can't read second line in java code.
    Is IPortalComponentRequest accept only 90 character ?
    how can i solve this problem , any idea ?
    my code is below, variable "str" is filling only first 90 character;
         protected void doOnNodeReady(
                   IPortalComponentRequest request,
                   IEvent event) {
         String str = "";
         try {
              InputStream is = request.getServletRequest().getInputStream();
              InputStreamReader isr = new InputStreamReader(is);
              int c;
              while ((c = isr.read()) > -1) {
              str = str + (char) c;
                } catch (java.io.IOException ex) {
                 str = "Error accessing input stream";
    thanks

    New discovery...If I shut down all instances of IE on my machine, then reopen my test form, it works. Once. The second time I try it I get the same peculiar behavior again, until I again shut down all instances of IE.

  • AT Commands , Hyper Terminal and java

    Hi,
    I have following problem, i have PCMCIA Type -11 Wireless modem.its installed on my system COM4 port.
    Now first problem is that when i try to connect with hyper terminal to COM4 there is no response from it .It become Idle.but when i connect with COM3 which is my Dialup modem port it works fine with all AT commands.
    Now 2nd things is that same with below code i tried to send sms using AT command on COM4 its has same behaviour as it was in Hyper terminal mean no response. no Data Available event occour
    Please help me in this regard and suggest me a solution.
    package serialio;
    import javax.comm.*;
    import java.io.*;
    import java.util.*;
    public class SimpleWrite
        implements Runnable, SerialPortEventListener
      public void run()
      static Enumeration portList;
      static CommPortIdentifier portId;
      static String dest = "0517111930";
      static String messageString = "Hello";
      InputStream inputStream;
      static SerialPort serialPort;
      static OutputStream outputStream;
      public void serialEvent(SerialPortEvent event)
        switch (event.getEventType())
          case SerialPortEvent.BI:
          case SerialPortEvent.OE:
          case SerialPortEvent.FE:
          case SerialPortEvent.PE:
          case SerialPortEvent.CD:
          case SerialPortEvent.CTS:
          case SerialPortEvent.DSR:
          case SerialPortEvent.RI:
          case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
            break;
          case SerialPortEvent.DATA_AVAILABLE:
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            try
              while ( (line = reader.readLine()) != null)
                System.out.println(line);
            catch (IOException e)
              System.err.println("Error while reading Port " + e);
            break;
        } //switch
      public SimpleWrite(SerialPort serial)
        try
          inputStream = serial.getInputStream();
          try
            serial.addEventListener(this);
          catch (TooManyListenersException e)
            System.out.println("Exception in Adding Listener" + e);
          serial.notifyOnDataAvailable(true);
        catch (Exception ex)
          System.out.println("Exception in getting InputStream" + ex);
      public static void main(String[] args)
    //    String line1="AT+CMGF=1\r\n";
    //    String line2="AT+CMGS=\""+ dest+"\"\r\n";
    //    String line3=messageString+"\r\n";
    //    String line4="\u001A";
        String line1 = "AT+CMGF=1\r\n";
        String line2 = "AT+CMGS=" + dest + "\r\n";
        String line3 = messageString + "^Z\r\n";
    //    String line4 = "\u001A";
        portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements())
          portId = (CommPortIdentifier) portList.nextElement();
          if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
            System.out.println("SMS Sending........");
            if ( portId.getName().equals("COM4"))
              System.out.println("SMS Sending....Port Found");
              try
                serialPort = (SerialPort) portId.open("SimpleWriteApp", 2000);
                SimpleWrite wr = new SimpleWrite(serialPort);
              catch (PortInUseException e)
                System.out.println("Port In Use " + e);
              try
                outputStream = serialPort.getOutputStream();
              catch (IOException e)
                System.out.println("Error writing to output stream " + e);
              try
                serialPort.setSerialPortParams(
                    2400,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);
              catch (UnsupportedCommOperationException e)
              try
                outputStream.write(line1.getBytes());
                outputStream.write(line2.getBytes());
                outputStream.write(line3.getBytes());
                outputStream.flush();
              catch (IOException e)
                System.out.println("Error writing message " + e);
      /** show text in the text window
       * @param Text text string to show on the display
      public static void showText(String Text)
        System.out.println(Text);
    }

    * SerialWrite.java
    * Created on September 10, 2008, 2:51 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package com.sms;
    import javax.comm.*;
    import java.io.*;
    import java.util.*;
    public class SerialWrite implements Runnable, SerialPortEventListener
    static String output="";
    public void run()
    static Enumeration portList;
    static CommPortIdentifier portId;
    static String dest = "+91999999999";
    static String messageString = "Hello Testing11";
    InputStream inputStream;
    static SerialPort serialPort;
    static OutputStream outputStream;
    public void serialEvent(SerialPortEvent event)
    switch (event.getEventType())
    case SerialPortEvent.BI:
    case SerialPortEvent.OE:
    case SerialPortEvent.FE:
    case SerialPortEvent.PE:
    case SerialPortEvent.CD:
    case SerialPortEvent.CTS:
    case SerialPortEvent.DSR:
    case SerialPortEvent.RI:
    case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
              System.out.println("Error");
    break;
    case SerialPortEvent.DATA_AVAILABLE:
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    String line = "";
    try
    while ( (line = reader.readLine()) != null)
    if(line.equalsIgnoreCase("OK") || (line.indexOf("+CMGS") != -1))
         output=line;
              Thread.sleep(10);
    catch (Exception e)
    System.err.println("Error while reading Port " + e);
    break;
    } //switch
    public SerialWrite(SerialPort serial)
    try
    inputStream = serial.getInputStream();
    try
    serial.addEventListener(this);
    catch (TooManyListenersException e)
    System.out.println("Exception in Adding Listener" + e);
    serial.notifyOnDataAvailable(true);
    catch (Exception ex)
    System.out.println("Exception in getting InputStream" + ex);
    public static void main(String[] args) throws Exception
         int i=0;
    String line0 = "ATZ\r\n";
    String line1 = "AT+CMGF=1\r\n";
    String line2 = "AT+CSCA=\"+919888888\"\r\n";
    //String line3 = "AT+CMGS="+"\""+ dest + "\""+"\r\n";
    String line3 = "AT+CMGS="+"\""+ args[0] + "\""+"\r\n";
    //String line4 = messageString;
    String line4 = args[1];
         portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements())
    portId = (CommPortIdentifier) portList.nextElement();
    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
    System.out.println("SMS Sending........");
    if ( portId.getName().equals("/dev/ttyACM0"))
    System.out.println("SMS Sending....Port Found");
    try
    serialPort = (SerialPort) portId.open("SerialTestApp", 2000);
    SerialWrite wr = new SerialWrite(serialPort);
    catch (PortInUseException e)
    System.out.println("Port In Use " + e);
    try
    outputStream = serialPort.getOutputStream();
    catch (IOException e)
    System.out.println("Error writing to output stream " + e);
    try
    serialPort.setSerialPortParams(
    115200,
    SerialPort.DATABITS_8,
    SerialPort.STOPBITS_1,
    SerialPort.PARITY_NONE);
    catch (UnsupportedCommOperationException e)
    try
    outputStream.write(line0.getBytes());
              Thread.sleep(10);
    while(!output.equalsIgnoreCase("ok"))
              Thread.sleep(10);
              output="";
    outputStream.write(line1.getBytes());
    while(!output.equalsIgnoreCase("ok"))
                   Thread.sleep(10);
              output="";
    outputStream.write(line2.getBytes());
    while(!output.equalsIgnoreCase("ok"))
                   Thread.sleep(10);
              output="";
         for(i=0;i<3;i++)
    outputStream.write(line3.getBytes());
    Thread.sleep(10);
    outputStream.write(line4.getBytes());
    Thread.sleep(10);
    outputStream.write(26);
    outputStream.write("\r\n".getBytes());
    outputStream.flush();
    while(!output.equalsIgnoreCase("ok"))
                   Thread.sleep(10);
              output="";
              System.out.println("Message Sent !!!!!!!!!1");
    catch (IOException e)
    System.out.println("Error writing message " + e);
    /** show text in the text window
    * @param Text text string to show on the display
    public static void showText(String Text)
    System.out.println("TEXT "+Text);
    }

  • Runtime.exec("Perl Script writing and reading on I/O"), handling Streams

    Hi all !!
    In a first place : sorry for my english if it's not really understandable but I try to do as good as possible !
    I'm writing a GUI with Swing that will allow (in one of my multiple tables) the user to run a Perl Script.
    This Perl Script ask the user to choose a Folder ... then read all the files in this folder and for each file (xml File), extract the datas and put them in a database. But when a file that has to be inserted in the database contains this line : <Template_Used name="ST1.mtt"> and if the Template table in my database doesn't have the "ST1.mtt" stored ... the Perl Script ask to the user to give him the path of the file "ST1.mtt" so that the script can put the "ST1.mtt template" datas in the database.
    This script runs well when it is from a windows console.
    But I need a graphic interface !!!
    So I created a JButton "Process a folder".
    When the button is pressed, a JFileChooser appears and ask the user which Folder has to be processed.
    Then a Process is created with the command : ("cmd.exe /C \"C:\\Program Files\\Fluke\\Ansur\\ProcessFolder.bat\").
    The BatFile :
    {code}cd C:\Documents and Settings\tsd\Desktop\Gael-Project\Project_Files
    perl Process.pl
    exit{code}
    At this moment everything is working well.
    But my Process.pl (which is 300 lines long ... and that you don't even want to hear about), ask in a first time the Path of the folder to process and sometimes ask the path to a file (a template file).
    So I need to read and wirte on the STDIN/STDOUT during the exec of the Process.
    In order to handle this I created two different threads : one reading the Process.getInputStream with a BufferedReader and one other writing on the Process.getOutputStream with a PrintWrinter.
    What I need to do is :
    When I read a line from the InputStream saying "I need the path of the ST1.mtt file", I should run a JFileChooser ... the user find the file in the computer ... and I write in the OutputStream the path of the file, so that my Perl Script doesn't have un Unitialised value on <STDIN> and can continue to process !!
    I'm pretty sure it's possible ... because at the moment I just used a trick :
    When the user push the "process a folder" button, I write the paths in the OutputStream before than the script needs it and it works !
    But I need to write in the OutputStream only when it is time !!!
    Any idea ??
    Here are some parts of my code :
    {code}
    String filename = File.separator+"tmp";
              JFileChooser fc = new JFileChooser(new File(filename));
              fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY );
              // Show open dialog; this method does not return until the dialog is closed
         fc.showOpenDialog(null);
         Folder = fc.getSelectedFile();
              new GoodExec(cmd);
    {code}
    {code}
    public class GoodExec {
         public static Process proc;
         public static StreamGobbler errorGobbler;
         public static StreamGobbler inputGobbler;
         public static StreamGobbler outputGobbler;
         public GoodExec(String cmd)
         try
                   Runtime rt = Runtime.getRuntime();
              proc = rt.exec(cmd);
         // any error message?
         errorGobbler = new
         StreamGobbler(proc.getErrorStream(), "ERROR");
         // any input?
         inputGobbler = new
         StreamGobbler(proc.getInputStream(), "INPUT");
         // any output?
              outputGobbler = new
              StreamGobbler(proc.getOutputStream(), "OUTPUT");
         // kick them off
         errorGobbler.start();
         inputGobbler.start();
         outputGobbler.start();
         // any error???
         int exitVal = proc.waitFor();
         System.out.println("ExitValue: " + exitVal);
         } catch (Throwable t)
         t.printStackTrace();
    {code}
    {code}
    public class StreamGobbler implements Runnable
    InputStream is;
    OutputStream os;
    String type;
    Thread thread;
    public static String chaine;
    StreamGobbler(InputStream is, String type)
    this.is = is;
    this.os=null;
    this.type = type;
    StreamGobbler(OutputStream os, String type)
    this.os = os;
    this.is=null;
    this.type = type;
    public void start () {
         thread = new Thread(this);
         thread.start ();
    public void run()
    try
    if (is == null){
         PrintWriter toProgram = new PrintWriter(os);
         File FolderToProcess = ProcessFolder.Folder;
    String Folder = FolderToProcess.getPath();
    toProgram.write(Folder);
    toProgram.close();
    else {
         if (os == null){
         InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line=null;
    String comp = "Please enter the exact path of the directory that contains the files you want to process.";
    while ( (line = br.readLine()) != null){
         if (type.equals("INPUT")){
              chaine+=line+"\n";
         if (line.equals(comp)) {
              System.out.println("give directory");RUN A JFILECHOOSER AND GIVE THE DIRECTORY TO THE OUTPUTSTREAM
    System.out.println(type + ">" + line);
    is.close ();
    catch (IOException ioe){
         ioe.printStackTrace();
    {code}
    And here is an example of a simple perl script that could be used (it s a simple one !!) :
    {code}
    #!/usr/bin/perl -w
    use strict;
    print "Please enter the exact path of the directory that contains the files you want to process.\n";
    my $dir= <STDIN>;
    chomp ($dir);
    print "titallala $dir";
    if (the template of the file is not in the database){
    print "Please give me the template so that I can put it in the database";
    $dir= <STDIN>;
    chomp ($dir);
    {code}
    Thank you for your help ... if it's possible to help me !!
    Gael

    BalusC -- The line that gives me my NullPointerException is when I call the "DisplayProduct()" method. Its a dumb question, but with NetBeans how do I find out which reference could be null? I'm not very familiar with how NetBeans works with finding out how to debug. Any help you can give me would be greatly appreciated.The IDE is com-plete-ly irrelevant. It's all about the source code.
    Do you understand anyway when and why a NullPointerException is been thrown? It is a subclass of RuntimeException and those kind of exceptions are very trival and generally indicate an design/logic/thinking fault in your code.
    SomeObject someObject = null; // The someObject reference is null.
    someObject.doSomething(); // Invoking a reference which is null would throw NPE.

  • Runtime exec freezes: exec target is a executable .jar that requires stdin

    I am having a problem with the Runtime.getRuntime().exec methodology in the following scenerio:
    -- Exec.class is a program that uses a StreamGobbler to display stdout to the screen
    -- ReadInput.class is a program that requires the user enter information via the console, using stdin
    When I try to do this, the ReadInput.class locks up and freezes, presumably because its trying to use stdin which already has been gobbled up by the Exec.class ???
    Here is my code, for example, that I run with the following command (on Windows XP) :
    start.bat
    @echo off
    echo.
    javac *.java
    echo First, test the Exec.class to see if it works
    echo.
    java Exec "dir *.java"
    echo.
    echo Then, try to run a program that wants the stdin (click a key to continue)
    echo.
    pause>nul
    java Exec "java -cp . ReadInput"
    echo.
    echo (click a key to end)
    pause>nul
    Exec.java
    import java.util.*;
    import java.io.*;
    class StreamGobbler extends Thread
        InputStream is;
        String type;
        StreamGobbler(InputStream is, String type)
            this.is = is;
            this.type = type;
        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);   
                } catch (IOException ioe)
                    ioe.printStackTrace(); 
    public class Exec
        public static void main(String args[])
            if (args.length < 1)
                System.out.println("USAGE: java Exec <cmd>");
                System.exit(1);
            try
                String osName = System.getProperty("os.name" );
                   System.out.println(osName);
                String[] cmd = new String[3];
                if( osName.equals( "Windows XP" ) )
                    cmd[0] = "cmd.exe" ;
                    cmd[1] = "/C" ;
                    cmd[2] = args[0];
                else if( osName.equals( "Linux" ) )
                    cmd[0] = "command.com" ;
                    cmd[1] = "/C" ;
                    cmd[2] = args[0];
                Runtime rt = Runtime.getRuntime();
                System.out.println("Execing " + cmd[0] + " " + cmd[1] + " " + cmd[2]);
                Process proc = rt.exec(cmd);
                // any error message?
                StreamGobbler errorGobbler = new
                    StreamGobbler(proc.getErrorStream(), "ERR");           
                // any output?
                StreamGobbler outputGobbler = new
                    StreamGobbler(proc.getInputStream(), "OUT");
                // kick them off
                errorGobbler.start();
                outputGobbler.start();
                // any error???
                int exitVal = proc.waitFor();
                System.out.println("ExitValue: " + exitVal);       
            } catch (Throwable t)
                t.printStackTrace();
    public class ReadInput {
       public static void main (String[] args) {
          //  prompt the user to enter their name
          System.out.print("Enter your name: ");
          //  open up standard input
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
          String userName = null;
          //  read the username from the command-line; need to use try/catch with the
          //  readLine() method
          try {
             userName = br.readLine();
          } catch (IOException ioe) {
             System.out.println("IO error trying to read your name!");
             System.exit(1);
          System.out.println("Thanks for the name, " + userName);
    }  // end of ReadInput classEdited by: sabre150 on 21-Jul-2011 11:26
    Added [ code] tags to make the code readable.

    When you call proc.getInputStream(), you are opening an InputStream in your app to read from the process's stdout.
    If that process "needs stdin", that is, if it normally runs by a user typing stuff at a terminal after it launches, then you have to call proc.getOutputStream() to get an OutputStream that your app can use to feed the process's stdin. So if you're trying to have your app read from the terminal (your app's stdin/System.in) and push that to the process you're launching, then after reading a line from System.in, your app would need to write that line to the OutputStream that you get from proc.getOutputStream().

Maybe you are looking for

  • I cant update my flash player!!! ...stop at 33%

    1st I try to clear the cache but still retriving something then "try to reconnect" and it will always stop to 33% after that lost connection. 2nd i uninstall the program and clear the remaining files in the system 32 and install "again" the flash but

  • How can i retrieve the answers to my security questions?

    Can someone help me i cant remember my security answers how can i retrieve them?

  • Dynamic Fields Or other tech.

    Hello , I'm a developer currently trying to figure out if Acrobat Forms will work for us, for an employment form.  Adobe forms looks to just about fill the gap here. What we're trying to accomplish here is an employment form for several positions for

  • Pre-comps loose Quality when putting them in parent Comps

    Hi there! I got quite a problem with my AE project and I really don't know what to do. I already Looked up the forum but didn´t find any useful help till now. The Problem I got is that I am working on quite a big project and need to fit precomps into

  • Can't sync w/ VersaMail

    hi.  I have a Treo 650 and I just got a new computer which is running Vista and Office 2007 with Outlook.  My old computer had WinXP and Office 2003 w/ Outlook. My problem is that after installing Palm 6.2 and the conduits for 2007 I am having a prob