Inputstream -- Parse -- Outputstream

Hi guyz,
Just need a little help.
What I want is:
1) Receive data via InputStream
2) Parse the data contained in InputStream
3) If parsing was succesful, I wan't to write content of InputStream to OutputStream.
The above procedure is a requirement.
Now, all the parsing stuff I got covered. I'm just not sure of how to write the content of my InputStream in to the OutputStream since the InputStream seems unavailable after parsing - I get a 'java.io.IOException: Bad file descriptor' whenever I try to read the InputStream again after parsing.
Hope someone can throw a few hints my way:-)
Thanks in advance.
Daniel

If you know the InputStream is associated with a file, I suppose you can reset it to the beginning of the file somehow; if only by closing and re-opening the file.
If the stream may be associated with a socket or something else, the above approach won't work (I think). If it's acceptable to write the data to the output stream along the way as you read it for parsing, do that. Otherwise, keep it in a variable (like a byte array, for instance) and write it out in the end.
Does this help?

Similar Messages

  • Are inputstream and outputstream independent of eachother ?

    <b><u>Code snippet 1) </u></b><br>
    ByteArrayInputStream inputPDFStream = (ByteArrayInputStream) <SOME INPUT STREAM OBJECT>;<br>
    byte [] bArray = new byte [inputPDFStream.available()];<br>
    //Reading into byte array.<br>
    inputPDFStream.read( bArray );<br>
    //Dumping byte array contents onto file system.<br>
    File file = new File("//exchange//EPP//template//test_PDF_OnPortal.pdf");<br>
    FileOutputStream os = new FileOutputStream(file);<br>
    os.write(bArray);<br>
    os.flush();<br>
    os.close();<br>
    //Closing input stream, after all operations have been performed.<br>
    <b>inputPDFStream.close();</b><br>
    <br>
    <b><u>Code snippet 2)</u></b><br>
    ByteArrayInputStream inputPDFStream = (ByteArrayInputStream)pdfObject.createPDF();<br>
    byte [] bArray = new byte [inputPDFStream.available()];<br>
    int iBytesRead = inputPDFStream.read( bArray );<br>
    /*************** change starts here ************/<br>
    //Closing input stream immediately after it has been read from.<br>
    <b>inputPDFStream.close();</b><br>
    /*************** change ends here ************/<br>
    File file = new File("//exchange//EPP//template//test_PDF_OnPortal.pdf");<br>
    FileOutputStream os = new FileOutputStream(file);<br>
    os.write(bArray);<br>
    os.flush();<br>
    os.close();<br>
    /*************** change starts here ************/<br>
    // commented this line of code and shifted it above.<br>
    <b>//inputPDFStream.close(); </b><br>
    /*************** change ends here ************/<br>
    <br><br>               
    <b><u>Questions -</u></b> <br>
    <br>
    1) Are inputstream and outputstream objects totally independent of eachother ?<br>
    2) Will the change in the position of the "inputstream.close()" method as shown above, affect the writing of the file to the file system ?
    In other words, will the outcome of an "FileOutputStream.write(), flush() or close()" depend on when the inputstream object is closed as seen in code snippet (2) ?<br>
    3) Assuming that the output buffer is flushed, will any data that you try to write using the OutputStream.write() method, be written to the outputstream target (whether a file, or response object), irrespective of whether the inputstream is active at that point of time ??<br>
    <br>
    Thanks,<br>
    Navneet.<br>
    Changes made by -

    Hey kaj...Do you have any idea about the "not normal"
    situations in which case the input and output streams
    might influence eachother ? ;)Those cases are when both streams comes from a resource which closes both streams when one of them is closed. It's very rare to see, but I've seen some socket implementations which does that.
    Kaj

  • Converting string into inputstream and outputstream Jsch (ssh connection)

    hi,
    I'm not really sure if this is the place where i should ask this, but if it is so then tell me!
    So my problem is that everything works just fine with input output streams like in this code, but i need to change this input stream into string messadge(Which would work!!)
    The main problem is not that i can't change string to inputstream, but that when i use inputstream every commands works, and when i try to do the same with sting>inputstream this doesn't work...
    unfortunatelly newgrp server; or newgrp doesn't rerally work just frezzes :/
    anyway i solved the initial problem, because Jsch have two (probably more methods of sending info to unix server, but because there is no documentation htere no way to know :D)
    methods of sending info to server : exec and shell , the exec sends one command and only works with commands like date;ls... now the shell can easily send any type of command including newgrp server1, and everything works :)
    so we connect to the server(passw,user,host) then excecute commands, this code works perfectle but the commented code// doesn't work :
    JSch jsch=new JSch();
    String host=null;
    String user="me1234";
    host="super.server.co.uk";
    String passw="12345";
    Session session=jsch.getSession(user, host, 22);
    session.setPassword(passw);
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect();
    Channel channel=session.openChannel("shell"); //the power of shell, if i use exec doesn't excecute newgrp...
    //String command = "newgrp xxxx;"; //this doesn't work ...
    //InputStream is = new ByteArrayInputStream(command.getBytes("UTF-8"));
    //channel.setInputStream(is);
    //then somehow printout the response from server...
    channel.setInputStream(System.in); // well instead of this I'd prefer channel.send(command);
    channel.setOutputStream(System.out);
    channel.connect();
    Edited by: 842778 on 14-Mar-2011 01:42

    You seem to be leaving out the newlines.

  • [RS232] how to use InputStream and OutputStream

    hi
    i am using javax.comm
    i get input and outputstream
                  try {
                   out  = serialPort.getOutputStream();
                            in    =serialPort.getInputStream();
                  } catch (IOException e) {
                        }but i can use only write(bytes[]) and read(bytes[])
    i would use println and readln .. how can i do that?
    thanks in advance, nik

    @OP: Maybe this thread is of use to you:
    http://forum.java.sun.com/thread.jspa?forumID=31&threadID=698876

  • How can I subclassing from InputStream or OutputStream...

    I need a user define class(stream..) that extends from java.io.InputStream
    So I wanna my class is just override close() method that don't close the stream
    just flush().
    public class MyInputStream extends InputStream
    But java.io.InputStream class is a abstract so I implements read() method
    I just modify close() method ..
    how can i do...
    please help me~~
    bye and thanks for read my poor English

    MyInputStream will have a constructor that takes another input stream. Just save this stream in your class as a private member variable. Anytime any method you don't care about (such as read) occurs on your stream, just call the same method on the private member variable.
    class MyInputStream extends InputStream
    private InputStream baseStream;
    public MyInputStream( InputStream base )
        baseStream = base;
    public int read( byte[] b )
        return baseStream.read(b);
    //etc
    }

  • InputStream and OutputStream - Already opened for input

    URL url = new URL("website.com");
            URLConnection urlc = url.openConnection();
            urlc.setDoOutput(true);
            urlc.setDoInput(true);
            urlc.setUseCaches(false);
    // read something from a file
            BufferedReader reader = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
            while (reader.read() > 0) {
                // do something
            reader.close();
    // write something to the same file
            DataOutputStream dos = new DataOutputStream(urlc.getOutputStream());
            dos.writeBytes("write something");
            dos.close();"java.io.IOException: Already opened for input:"
    what is that supposed to mean? Doesn't "reader.close();" take care of that?
    I can read the file and I can write to a file. But I can't do both one after another...
    Why is that?

    I just swapped the code
    URL url = new URL("website.com");
            URLConnection urlc = url.openConnection();
            urlc.setDoOutput(true);
            urlc.setDoInput(true);
            urlc.setUseCaches(false);
    // write something to the same file
            DataOutputStream dos = new DataOutputStream(urlc.getOutputStream());
            dos.writeBytes("write something");
            dos.close();
    // read something from a file
            BufferedReader reader = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
            while (reader.read() > 0) {
                // do something
            reader.close();

  • Does parsing modify inputStream in anyhow?

    Guys,
    does parsing (SAX and DOM) modify InputStream in anyhow? Specially regarding to indentation?
    My exact issue: If I have a digitally signed XML InputStream into my java mapping, parse it (for schema validation, for example) and just put InputStream into OutputStream, will the output's signature be still valid, for sure, or is there any possibility that it will be invalidated?
    Please answer for both SAX and DOM parsers.
    Thanks in advance,
    Henrique.

    Hi,
    As explained above by Bhavesh.
    See below links also.
    /people/sap.user72/blog/2005/06/16/using-digital-signatures-in-xi
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/55ba9790-0201-0010-aa98-ce8f51ea93cd
    Loading Invoice XML IDoc with digital signature via XI into R/3
    Security Issues: SSL on SOAP Adapter and Digital Signature in BPM
    http://help.sap.com/saphelp_nw04s/helpdata/en/6b/8c784226d1d242e10000000a1550b0/frameset.htm
    Encryption of Data in XI3.0
    Regards
    Chilla

  • InputStream / OutputStream Help

    I have in a series 10 commands to be executed on a server. so i am using Buffered OutputStream and DataOutputStream to write those commands to server.
    these commands have a set of protocol rule to be followed.
    for example i am creating a byte array and i am appending those protocol rules to the byte array and then finally to the stream and then writing to the socket of the server.
    everything works fine here.
    After that i must read the messages from the server.
    this is also fine but t�he problem is everytime i read different input for each command.
    i dont know why!!!!
    so my read function is as follows,
    import java.net.*;
    public class xxxxx
    InputStream instream;
    OutputStream outstream;
    public void OpenConnection() throws ConnectException,UnknownHostException
    try
         tcpipSocket = new Socket(tcpipparameters.getIpAddress(),tcpipparameters.getPortNumber());
    catch(IOException exception)
         System.out.println(exception.toString());
    try
         outstream = tcpipSocket.getOutputStream();
         instream = tcpipSocket.getInputStream();
         dos = new DataOutputStream(outstream);
         BufferedOutputStream bos= new BufferedOutputStream(dos);
         dis = new DataInputStream(instream);
         BufferedInputStream bis = new BufferedInputStream(dis);
    ////////// now i start the command execution on the server
    ///// The 1st Command --------------(The INIT Command)
         byte[] init = {0,6,0,2};
         init = createMessage.calculateCheckSum(init);
         int len = init.length;
         //dos.write(init,0,len);
         bos.write(init);
         bos.flush();
         int available;
         while((available = bis.available()) > 0)
              byte[] data = new byte[available];
              bis.read(data);
              for(int i = 0 ; i < data.length; i++)
                   System.out.print(data);
    ////////////////// The 2nd Command -------------------(IDENTIFY)
    byte[] identify = {0,16,0,20};
    // The protocol version number is inserted in to the IDENTIFY byte[]array
    int protocol_version_number = 512;
    byte[] protocol = {(byte)(protocol_version_number/256) ,(byte)(protocol_version_number%256) };
    byte[] temp = new byte[ identify.length +  protocol.length] ;
    System.arraycopy( identify, 0, temp, 0, identify.length ) ;
    System.arraycopy(protocol, 0, temp, identify.length, protocol.length ) ;
    identify = temp ;
    String PR_SName = "PRS2.0";
    identify = createString.stringData(identify,PR_SName);
    identify = createMessage.calculateCheckSum(identify);
    len = identify.length;
    bos.write(identify);
    bos.flush();
    int length1 = bis.available();
    System.out.println("length of the BufferedInputStream = " + length1);
    StringBuffer sb = new StringBuffer();
    for (int i=1; i<=length1; i++)
         char reply = (char)bis.read();
         sb.append(reply);
    System.out.println(sb.toString());
    ////////////////// The 3rd Command and So on................................
    catch(IOException exception)
         System.err.println("message = " + exception.getMessage());
    catch(InterruptedException e)
         System.err.println("Error =" + e);
    finally
         try
              //flush and close both "Instream" and "Outstream"
              dos.close();
              dis.close();
              instream.close();
              outstream.close();
         catch (IOException ex)
              ex.printStackTrace();
    every time the reading from the server is different.
    but i want to have the exact number of bytes to read everytime.
    so please correct me where i am wrong.
    With regards,
    Ashok
              public void CloseConnection()throws IOException
                        tcpipSocket.close();

    I would say the answer is in my previous replies to your question. I suggest you have another read of them.

  • InputStream & OutputStream Lockup

    Hi,
    I am using applet-servlet communication to get servlet to get the BLOB field from database and passing
    it through applet using InputStream and OutputStream. I am not getting any errors but it crashes when its
    reading the InputStream from Servlet and reading it to byte[] (s). Any help is always appreciated.
    Thanks in advance.
    Here is the code.
    /--------- SERVLET CODE-----------/
    public class getImage extends HttpServlet{
    Connection myCon;
    Statement myStmt;
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
    try{
    System.out.println("Inside the doGet");
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    System.out.println("after class.forname");
    Connection myCon = DriverManager.getConnection("jdbc:odbc:SCANODBC","SYSDBA","masterkey");
    System.out.println("after Connection myCon");
    Statement myStmt = myCon.createStatement();
    System.out.println("after Statement myStmt");
    myStmt.executeQuery("SELECT IMAGE FROM UNMATCH WHERE UINDEX=1");
    System.out.println("after myStmt.executeQuery");
    ResultSet rset = null;
    rset = myStmt.getResultSet();
    System.out.println("after rset= myStmt.getResultSet()");
    rset.next();
    int samir=0;
    InputStream stream = rset.getBinaryStream(1);
    res.setContentType("image/tiff");
    byte[] s = new byte[1];
    int lengthRead = 0;
    while((lengthRead = stream.read(s)) != -1){
    ++samir;
    System.out.println(samir);
    byte[] b = new byte[samir];
    while((lengthRead = stream.read(b)) != -1){
    res.getOutputStream().write(b);
    res.getOutputStream().flush();
    res.getOutputStream().close();
    catch(FileNotFoundException fnfe){
    System.out.println(fnfe);
    catch(IOException ioe){
    System.out.println(ioe);
    catch(ClassNotFoundException cnfe){
    System.out.println(cnfe);
    catch(SQLException se){
    System.out.println(se);
    /-----------AppletCode---------------/
    public class ImageApplet extends JApplet {
    private boolean isStandalone = false;
    private JPanel jPanel1 = new JPanel();
    private BorderLayout borderLayout1 = new BorderLayout();
    private String hostName = "localhost";
    private int port = 8080;
    private String servletPath = "/examples/servlet/imageappletservlet.getImage";
    private String webServerStr = null;
    private JButton jButton1 = new JButton();
    //Get a parameter value
    public String getParameter(String key, String def) {
    return isStandalone ? System.getProperty(key, def) :
    (getParameter(key) != null ? getParameter(key) : def);
    //Construct the applet
    public ImageApplet() {
    //Initialize the applet
    public void init() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    //Component initialization
    private void jbInit() throws Exception {
    this.setSize(new Dimension(500,500));
    jPanel1.setLayout(borderLayout1);
    jButton1.setText("jButton1");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jButton1_actionPerformed(e);
    this.getContentPane().add(jPanel1, BorderLayout.CENTER);
    jPanel1.add(jButton1, BorderLayout.CENTER);
    //Get Applet information
    public String getAppletInfo() {
    return "Applet Information";
    //Get parameter info
    public String[][] getParameterInfo() {
    return null;
    //static initializer for setting look & feel
    static {
    try {
    //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    //UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    catch(Exception e) {
    protected void log(String msg)
    System.out.println(msg + "\n");
    void jButton1_actionPerformed(ActionEvent e) {
    try {
    URL hostURL = getCodeBase();
    hostName = hostURL.getHost();
    port = hostURL.getPort();
    webServerStr ="http://localhost:8080/examples/servlet/imageappletservlet.getImage";
    log("Web String full = " + webServerStr);
    String servletGET = webServerStr;
    log(servletGET);
    log("Connecting...");
    URL imageDBServlet = new URL(servletGET);
    URLConnection servletConnection = imageDBServlet.openConnection();
    log("Getting InputStream");
    InputStream is = null;
    is = servletConnection.getInputStream();
    int samir=0;
    byte[] s = new byte[1];
    int lengthRead = 0;
    while(is.read(s) != -1){                // this is where it lockes up
    System.out.println(samir); //
    ++samir;
    System.out.println(samir);
    catch (IOException ex){
    System.out.println(ex);

    Cross-posting is frowned upon! You posted this to 4 different forums!

  • InputStream - OutputStream: Reader - Writer

    What was not possible by InputStream & OutputStream that JAVA had to provide Reader and Writer. I have found out that if I use InputStream to read a Chinese HTML page, it reads it. I can create a copy of the same HTML page by using OutputStream, the data remaining un-affected. Then, why do I go for Reader and Writer?
    What happens if InputStream encounters some unicode charchters to be read? How does InputStream and OutputStream function internally?

    Well, you can go look at the source of InputStream/OutputStream.
    The reason we have Reader/Writer as well is because the streams don't deal with character encoding (or at least, they tried to and did it very badly). So you would normally use streams for dealing with binary data and reader/writer for dealing with character data. If you're using streams to copy a file and this file happens be be HTML with Chinese characters, this will work fine because you're just duplicating bytes. But if you try and use a stream to read this file into memory, you will have problems because it won't understand the Unicode characters in the file. In this case, you need to use a Reader and tell it what the character encoding of the file is.

  • InputStream/OutputStream ...

    Hello
    For my socket communications, I am thinking of using InputStream/OutputStream to read/write data. Just realized that InputStream and OutputStream are abstract classes. In particular, the read() and write () are abstract methods
    with no actual implementation.
    =================================
    public abstract int read() throws IOException
    Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.
    A subclass must provide an implementation of this method.
    Returns:
    the next byte of data, or -1 if the end of the stream is reached.
    Throws:
    IOException - if an I/O error occurs.
    ============================================
    However, when I call these methodes, they actually work!
    What is going on here?
    What is your recommendation for socket I/O? should i stick with my InputStream/OutputStream, or I should use DataInputStream/DataOutputStream?
    Thanks for your help,
    Alex

    Hello
    For my socket communications, I am thinking of using
    InputStream/OutputStream to read/write data. Just
    realized that InputStream and OutputStream are
    abstract classes. In particular, the read() and write
    () are abstract methods
    with no actual implementation.
    =================================
    public abstract int read() throws IOException
    Reads the next byte of data from the input stream. The
    value byte is returned as an int in the range 0 to
    255. If no byte is available because the end of the
    stream has been reached, the value -1 is returned.
    This method blocks until input data is available, the
    end of the stream is detected, or an exception is
    thrown.
    A subclass must provide an implementation of this
    method.
    Returns:
    the next byte of data, or -1 if the end of the stream
    is reached.
    Throws:
    IOException - if an I/O error occurs.
    ============================================
    However, when I call these methodes, they actually
    work!
    What is going on here?There is nothing strange about that. The type of the object that Socket.getInputStream() returns is a subclass of class InputStream. Read a book about Java interfaces and abstract classes (or look it up in the tutorial: http://java.sun.com/docs/books/tutorial/java/index.html).
    What is your recommendation for socket I/O? should i
    stick with my InputStream/OutputStream, or I should
    use DataInputStream/DataOutputStream?That depends on what data you want to communicate over the socket. DataInputStream and DataOutputStream make it easy for you to send and receive Java primitive types over the socket. You can create a DataInputStream that wraps the input stream of your socket as follows:
    Socket s = ...;   // create the socket etc.
    InputStream sis = s.getInputStream();
    DataInputStream dis = new DataInputStream(sis);
    // ... now use dis to read dataJesper

  • JavaMapping in PI 7.1 Error:Unable to display tree view; Error when parsing

    hi,
    i get by testing in PI 7.1 (operation mapping) this ERROR:
    "Unable to display tree view; Error when parsing an XML document (Content is not allowed in prolog.)"
    this is my java-programm-code:
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import com.sap.aii.mapping.api.StreamTransformation;
    import java.io.*;
    import java.util.Map;
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    /*IMPORT statement imports the specified classes and its methods into the program */
    /Every Java mapping program must implement the interface StreamTransformation and its methods execute() and setParameter() and extend the class DefaultHandler./
    public class Mapping extends DefaultHandler implements StreamTransformation {
    Below is the declaration for all the variables we are going to use in the
    subsequent methods.
         private Map map;
         private OutputStream out;
         private boolean input1 = false;
         private boolean input2 = false;
         private int number1;
         private int number2;
         private int addvalue;
         private int mulvalue;
         private int subvalue;
         String lineEnd = System.getProperty("line.separator");
    setParamater() method is used to store the mapping object in the variable
    "map"
         public void setParameter(Map param) {
              map = param;
         public void execute(InputStream in, OutputStream out)
                   throws com.sap.aii.mapping.api.StreamTransformationException {
              DefaultHandler handler = this;
              SAXParserFactory factory = SAXParserFactory.newInstance();
              try {
                   SAXParser saxParser = factory.newSAXParser();
                   this.out = out;
                   saxParser.parse(in, handler);
              } catch (Throwable t) {
                   t.printStackTrace();
    As seen above execute() method has two parameters "in" of type
    InputStream and "out" of type OutputStream. First we get a new instance
    of SAXParserFactory and from this one we create a new Instance of
    SAXParser. To the Parse Method of SaxParser, we pass two parameters,
    inputstream "in" and the class variable "handler".
    Method "write" is a user defined method, which is used to write the
    string "s" to the outpurstream "out".
         private void write(String s) throws SAXException {
              try {
                   out.write(s.getBytes());
                   out.flush();
              } catch (IOException e) {
                   throw new SAXException("I/O error", e);
         public void startDocument() throws SAXException {
              write("");
              write(lineEnd);
              write("");
              write(lineEnd);
         public void endDocument() throws SAXException {
              write("");
              try {
                   out.flush();
              } catch (IOException e) {
                   throw new SAXException("I/O error", e);
         public void startElement(String namespaceURI, String sName, String qName,
                   Attributes attrs) throws SAXException {
              String eName = sName;
              if ("".equals(eName))
                   eName = qName;
              if (eName.equals("NUMBER1"))
                   input1 = true;
              if (eName.equals("NUMBER2"))
                   input2 = true;
         public void endElement(String namespaceURI, String sName, String qName)
                   throws SAXException {
              String eName = sName;
              if ("".equals(eName))
                   eName = qName;
              if (eName.equals("NUMBER1"))
                   input1 = false;
              if (eName.equals("NUMBER2"))
                   input2 = false;
         public void characters(char[] chars, int startIndex, int endIndex)
                   throws SAXException {
              String dataString = new String(chars, startIndex, endIndex).trim();
              if (input1) {
                   try {
                        number1 = Integer.parseInt(dataString);
                   } catch (NumberFormatException nfe) {
              if (input2) {
                   number2 = Integer.parseInt(dataString);
              if (input2 == true) {
                   addvalue = number1 + number2;
                   mulvalue = number1 * number2;
                   subvalue = number1 - number2;
                   write("" + addvalue + "");
                   write(lineEnd);
                   write("" + mulvalue + "");
                   write(lineEnd);
                   write("" + subvalue + "");
                   write(lineEnd);
    in developer studio 7.1 i dont get error.
    this happens by testing the mapping-programm in ESR.
    can somebody help me please?

    Make sure that the xml created out after the java mapping is a valid xml with only one root node.
    Regards,
    Prateek

  • Context change by DOM parsing Java Mapping in XI

    Hi Team,
    I would like to know that how can I handle Context Change by DOM Parser Java Mapping in XI.?
    Suppose  the source XML structure I have like below:
    <?xml version="1.0" encoding="UTF-8"?>
    <ns0:Header xmlns:ns0="urn:bp:xi:hr:edm:test:100">
       <FileName>
          <filesub>
             <subname>a</subname>
             <subname>b</subname>
             <subname>c</subname>
          </filesub>
       </FileName>
       <FileName>
          <filesub>
             <subname>d</subname>
             <subname>e</subname>
             <subname>f</subname>
          </filesub>
       </FileName>
    </ns0:Header>
    Where the field FileName can occur maximum thrice(0...3) but the subname field is (0....unbounded) but in the target source I would like to have as given below:
    <?xml version="1.0" encoding="UTF-8" ?>
    - <MT_Test4 xmlns="urn:bp:xi:hr:edm:test:100">
    - <Header>
      <FileName>a</FileName>
      <FileName1>d</FileName1>
        </Header>
    - <Header>
      <FileName>b</FileName>
      <FileName1>e</FileName1>
       </Header>
    Header>
      <FileName>c</FileName>
      <FileName1>f</FileName1>
       </Header>
    </MT_Test4>
    That means the first value from every context of the source field is forming my first and second value in my target first context.Thensecond value from every context is forming my 1st and 2nd value of my target 2nd context and finally 3rd value of every context is forming my 1st and 2nd value of my target 3rd context.Is this possible to done through DOM parsing or we have to do it by UDF only?

    Hi Atanu,
        In my last post I gave an alogorithm to solve the mapping problem. Here is the complete program for the mapping.
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Map;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import com.sap.aii.mapping.api.StreamTransformation;
    import com.sap.aii.mapping.api.StreamTransformationException;
    public class DOMParser1  implements StreamTransformation{
         public void execute(InputStream in, OutputStream out)
                   throws StreamTransformationException {
              try
                   DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
                   DocumentBuilder builderel=factory.newDocumentBuilder();
                   /input document in form of XML/
                   Document docIn=builderel.parse(in);
                   /document after parsing/
                   Document docOut=builderel.newDocument();
                   TransformerFactory tf=TransformerFactory.newInstance();
                   Transformer transform=tf.newTransformer();
                   Element root,child,child1=null;
                   Node textChild;
                   NodeList l;
                   int i,n1,j,div,k;
                   String s[];
                   root=docOut.createElement("MT_Test4");
                   root.setAttribute("xmlns","urn:bp:xi:hr:edm:test:100");
                   l=docIn.getElementsByTagName("subname");
                   n1=l.getLength();
                   s=new String[n1];
                   for(i=0;i<n1;++i)
                             s<i>=l.item(i).getFirstChild().getNodeValue();
                   l=docIn.getElementsByTagName("filesub");
                   div=l.getLength();
                   j=n1/div;
                   for(i=0,k=0;i<j;++i)
                        child1=docOut.createElement("Header");
                        root.appendChild(child1);
                        child=docOut.createElement("FileName");
                        textChild=docOut.createTextNode(s[k]);
                        child.appendChild(textChild);
                        child1.appendChild(child);
                        child=docOut.createElement("FileName1");
                        textChild=docOut.createTextNode(s [ k + j ]);
                        child.appendChild(textChild);
                        child1.appendChild(child);
                        ++k;
                   docOut.appendChild(root);
                   transform.transform(new DOMSource(docOut), new StreamResult(out));     
              catch(Exception e)
                   e.printStackTrace();
         public void setParameter(Map arg0) {
         public static void main(String[] args) {
              try{
                   DOMParser1 genFormat=new DOMParser1();
                   FileInputStream in=new FileInputStream("C:/Apps/my dw/sdnq/apps.xml");
                   FileOutputStream out=new FileOutputStream("C:/Apps/my dw/sdnq/tgt1.xml");
                   genFormat.execute(in,out);
              catch(Exception e)
                   e.printStackTrace();
    source ->  apps.xml
    <?xml version="1.0" encoding="UTF-8" ?>
    - <ns0:Header xmlns:ns0="urn:bp:xi:hr:edm:test:100">
    - <FileName>
    - <filesub>
      <subname>a</subname>
      <subname>b</subname>
      <subname>c</subname>
      </filesub>
      </FileName>
    - <FileName>
    - <filesub>
      <subname>d</subname>
      <subname>e</subname>
      <subname>f</subname>
      </filesub>
      </FileName>
      </ns0:Header>
    target structure ->  tgt1.xml
    <?xml version="1.0" encoding="UTF-8" ?>
    - <MT_Test4 xmlns="urn:bp:xi:hr:edm:test:100">
    - <Header>
      <FileName>a</FileName>
      <FileName1>d</FileName1>
      </Header>
    - <Header>
      <FileName>b</FileName>
      <FileName1>e</FileName1>
      </Header>
    - <Header>
      <FileName>c</FileName>
      <FileName1>f</FileName1>
      </Header>
      </MT_Test4>
    Hope this helps
    one more thing  in this line "textChild=docOut.createTextNode(s k + j );"   somehow the the third braces one opening  before k and one closing after j is missing for unknown reasons. Please correct it when you actually run this code.
    regards
    Anupam
    Edited by: anupamsap on Mar 7, 2011 12:47 PM

  • Java Mapping Using DOM Parser.

    Hi Experts,
    I am new to Java mapping and i have followed the link
    http://scn.sap.com/thread/3173071 and it is working fine. It is for only one item. I have tried to modify the code and i placed a for loop to go create the Output Node based on the No of Input Nodes and it is giving the error as below. But my requirement is
    Input.xml : -
    <?xml version="1.0" encoding="UTF-8" ?>  
    <ns0:DT_Source xmlns:ns0="urn:java_mapping2"> 
    <Person1> 
          <Name>Alex</Name>  
          <Surname>Stewart</Surname>  
    </Person1>
    <Person1> 
          <Name>Sam</Name>  
          <Surname>Abdreson</Surname>  
    </Person1>  
    </ns0:DT_Source>
    Output.xml:-
    <?xml version="1.0" encoding="UTF-8" standalone="no"?> 
    <ns0:DT_Target xmlns:ns0="urn:java_mapping2"> 
    <Person2> 
         <EmpName> 
              <Emp>Alex Stewart</Emp> 
    </EmpName> 
    </Person2>
    <Person2> 
         <EmpName> 
              <Emp>Sam Abdreson</Emp> 
    </EmpName> 
    </Person2>  
    </ns0:DT_Target> 
    I am unable to get the output. I am getting the following error.
    org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.
    at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.insertBefore()
    at com.sun.org.apache.xerces.internal.dom.NodeImpl.appendChild()
    Please suggest me how i can resolvoe this error.
    Regards,
    GIRIDHAR

    Complete code
    package test;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    import com.sap.aii.mapping.api.AbstractTransformation;
    import com.sap.aii.mapping.api.StreamTransformationException;
    import com.sap.aii.mapping.api.TransformationInput;
    import com.sap.aii.mapping.api.TransformationOutput;
    import java.io.IOException;
    import org.xml.sax.SAXException;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.Node;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    public class RemoveTag extends AbstractTransformation {
        public void execute(InputStream in,OutputStream out) throws StreamTransformationException, SAXException, IOException {  
            try
                 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
                 DocumentBuilder builderel=factory.newDocumentBuilder();
                 /*input document in form of XML*/
                 Document docIn=builderel.parse(in);
                 /*document after parsing*/
                 Document docOut=builderel.newDocument();
                 TransformerFactory tf=TransformerFactory.newInstance();
                 Transformer transform=tf.newTransformer();
                 Element root,child,child1,child2;
                 Node textChild;
                 Node name,surname;
                 String fullname="";
                 root=docOut.createElement("ns0:DT_Target");
                 root.setAttribute("xmlns:ns0","urn:java_mapping2");
                 NodeList nList = docIn.getElementsByTagName("Person1");
                 for (int temp = 0; temp < nList.getLength(); temp++)
                child1=docOut.createElement("Person2");
                 child=docOut.createElement("EmpName");
                 child2=docOut.createElement("Emp");
                 child.appendChild(child2);
                 child1.appendChild(child);
                 root.appendChild(child1);
                 name=docIn.getElementsByTagName("Name").item(temp);
                 surname=docIn.getElementsByTagName("Surname").item(temp);
                 fullname=name.getFirstChild().getNodeValue()+" ";
                 fullname+=surname.getFirstChild().getNodeValue();
                 textChild=docOut.createTextNode(fullname);
                 child2.appendChild(textChild);
                 docOut.appendChild(root);  
                 transform.transform(new DOMSource(docOut), new StreamResult(out));
            catch(Exception e)
                 e.printStackTrace();
        public static void main(String[] args) {
            try{
                RemoveTag genFormat=new RemoveTag();
                 FileInputStream in=new FileInputStream("C:\\Users\\Desktop\\aa.xml");
                 FileOutputStream out=new FileOutputStream("C:\\Users\\Desktop\\output1.xml");
                 genFormat.execute(in,out);
            catch(Exception e)
                 e.printStackTrace();
    @Override
    public void transform(TransformationInput arg0, TransformationOutput arg1)
    throws StreamTransformationException {
    // TODO Auto-generated method stub
    try {
        this.execute(arg0.getInputPayload().getInputStream(), arg1.getOutputPayload().getOutputStream());
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

  • XI Soap Adapter: problems in parsing XML

    Hallo,
    I call a Web Service using XMLSpy and this is the response (note tag <File>):
              <SOAPSDK4:ExpBaselineResponse xmlns:SOAPSDK4="http://tempuri.org/PRWBS_PRIMAVERA/message/">
                   <RESULT>OK</RESULT>
                   <File>&lt;?xml version=&apos;1.0&apos; encoding=&apos;UTF-8&apos;?&gt;
    &lt;Dati:Parametri xmlns:Dati=&quot;Schema&quot;&gt;
         &lt;ELSAG xmlns=&quot;Schema&quot;&gt;
              &lt;proj_id&gt;4623&lt;/proj_id&gt;
              &lt;BS_short_name&gt;FS0084AAAA01 - B1&lt;/BS_short_name&gt;
              &lt;BS_proj_id&gt;1302&lt;/BS_proj_id&gt;
              &lt;TARGET_START&gt;2004-04-01&lt;/TARGET_START&gt;
    ....etc...
    If I call the same Web Service from XI, this is the response:
    <SOAPSDK4:ExpBaselineResponse xmlns:SOAPSDK4="http://tempuri.org/PRWBS_PRIMAVERA/message/" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAPSDK3="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAPSDK2="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAPSDK1="http://www.w3.org/2001/XMLSchema">
         <RESULT>OK</RESULT>
         <File>&#60;?xml version="1.0" standalone="yes"?&#62;
    &#60;Dati:Parametri xmlns:Dati="Schema"&#62;
         &#60;ELSAG xmlns="Schema"&#62;
              &#60;proj_id&#62;4623&#60;/proj_id&#62;
              &#60;BS_short_name&#62;FS0084AAAA01 - B1&#60;/BS_short_name&#62;
              &#60;BS_proj_id&#62;1302&#60;/BS_proj_id&#62;
              &#60;TARGET_START&#62;2004-04-01&#60;/TARGET_START&#62;
    ....etc....
    In my flow, I use a java mapping to parse the content of tag <File> into a message.
    My mapping works correctly only with the first option.
    Is it possible to change XI Soap Adapter encoding for HTML?
    My java mapping uses this parser:
         public void execute(InputStream MyInputStream, OutputStream MyOutputStream)
                   throws StreamTransformationException {
              SAXReader reader = new SAXReader();
              Document document;
              try {
                   document = reader.read(MyInputStream);
    this instruction generates an Exception only with XI message.
    Can anybody help me??
    Thanks;-)

    Hi,
    I would suggest you go through this Pdf for the SOAP Adapter configuration:
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/40728f7b-0401-0010-d9bc-8c73884a3789
    And also have a glance on the info for webservices given below,
    Just go through these links and they will surely help you learn more about Webservices:
    <a href="/people/siva.maranani/blog/2005/09/03/invoke-webservices-using-sapxi Webservices using SAPXI</a>
    <a href="/people/siva.maranani/blog/2005/05/23/communication-between-sap-system-webservice-using-proxies between SAP System & Webservice Using Proxies</a>
    You can Go through these links to get some info about accessing Webservices:
    http://help.sap.com/saphelp_nw04/helpdata/en/d6/f9bc3d52f39d33e10000000a11405a/content.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/b7/d7baaf1481a349ab723e3acd7334b3/content.htm
    Go through these links which will surely help you find an answer to your problem.....
    Regards,
    Abhy

Maybe you are looking for

  • To restrict Sales Order if account balane is less than SO balance

    hi Srujal Patel, I want to restrict some customers sales order which are less account balance. example: ABC customer account balance is 100. now they ordered 150. now this SO document will not be posted until approval from superior. how can i do rest

  • App Store. Could not sign in. An unknown error has occurred.

    I keep getting this message on my iPhone 4, iOS 6. Every time I try to update my apps after I put my password. Have not changed anything on the phone itself, it just started doing it a few days ago. My iPad, Macbook and iMac with the same account do

  • Problem with job sceduling

    Hi experts, i have schedule a job, but it could not executed because the system was down. like i schedule my job at 1:00 PM, but system is shutdown at that time, so the job could not executed, so i want to execute the same job again on some event lik

  • Fileds issues in XL reporter

    Hi all, I want to pick the ObjType & DocNumber fileds in the open opportunity report in XL reporter  i tried  but not able to pick these fields in xl reporter Please Provide me the solution asap. Thanks & Regards Pankaj Sharma

  • Asking for password for keychain access, but won't accept my password... What's up with this?

    Restarted my MacBook just now and it's got a continuous stream of pop ups asking for password for keychain access, won't accept my password, won't go away (cancel), any suggestions.