cancel
Showing results for 
Search instead for 
Did you mean: 

XML to String Java Mapping

ernesto_cruz
Participant
0 Kudos

Hi Guys, I'm working on an RFC to SOAP scenario in PI 7.1 and I want to transform an input XML to a output string.

I want to use Java Mapping, but could not find any code.

The source XML and target String are:

INPUT XML:

<?xml version="1.0" encoding="UTF-8"?>

<ns0:ZDM_RFC_REPLICA_CONVENIOS_PI xmlns:ns0="urn:sap-com:document:sap:rfc:functions">

   <I_CONVENIO>

      <CANAL_ID/>

      <CANAL_CODIGO/>

      <CANAL_SISTEMA/>

      <ORIGEN_PETICION/>

   </I_CONVENIO>

</ns0:ZDM_RFC_REPLICA_CONVENIOS_PI>

OUTPUT String:

<CABECERA><CANAL_ID></CANAL_ID><CANAL_CODIGO></CANAL_CODIGO><CANAL_SISTEMA></CANAL_SISTEMA><ORIGEN_PETICION></ORIGEN_PETICION></CABECERA>

Regards!

Accepted Solutions (1)

Accepted Solutions (1)

Former Member
0 Kudos
ernesto_cruz
Participant
0 Kudos

Hi Satish, The code in this example has helped me and I'm using this.

https://wiki.sdn.sap.com/wiki/display/Snippets/Java+Mapping+-+Convert+the+Input+xml+to+String

Do you know what the line of code that replaces the name of a field? in our case <CABECERA> , instead of <I_CONVENIO>

Thank in advance.

nabendu_sen
Active Contributor
0 Kudos

Hi,

Please find the below code for "exceute" step.   

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,child2,child3,child4;

               Node CANAL_ID,CANAL_CODIGO,CANAL_SISTEMA,ORIGEN_PETICION;

               Node  CANAL_ID_Target,CANAL_CODIGO_Target,CANAL_SISTEMA_Target,ORIGEN_PETICION_Target;

               root=docOut.createElement("<ns0:ZDM_RFC_REPLICA_CONVENIOS_PI");

               root.setAttribute("xmlns:ns0","urn:sap-com:document:sap:rfc:functions");

               

               child=docOut.createElement("CABECERA");

               

               child1=docOut.createElement("CANAL_ID");

              

               child2=docOut.createElement("CANAL_CODIGO");

               child3=docOut.createElement("CANAL_SISTEMA");

               child4=docOut.createElement("ORIGEN_PETICION");

               child.appendChild(child1);

               child.appendChild(child2);

               child.appendChild(child3);

                child.appendChild(child4);

               CANAL_ID=docIn.getElementsByTagName("CANAL_CODIGO").item(0);

                    CANAL_CODIGO=docIn.getElementsByTagName("CANAL_CODIGO").item(0);

               ......

                .......

               ........

               CANAL_ID_Target=docOut.createTextNode(CANAL_ID.getFirstChild().getNodeValue());

  CANAL_CODIGO_Target=docOut.createTextNode(CANAL_CODIGO.getFirstChild().getNodeValue());

                ..........

                ..........

             

               child1.appendChild(CANAL_ID_Target);

                child2.appendChild(CANAL_CODIGO_Target);

               ..........

               ............

               docOut.appendChild(root);

               root.appendChild(child);

               transform.transform(new DOMSource(docOut), new StreamResult(out));

          }

          catch(Exception e)

          {

               e.printStackTrace();

          }

          

     }

ernesto_cruz
Participant
0 Kudos

Excellent! But I have another problem with the response message. The request channel throws the following error:

Error in processing caused by: com.sap.aii.adapter.rfc.core.server.RfcServerException: got unexpected document type:DOC_TYPE_UNKNOWN.

And I have the following code in Java Mapping Response:

import java.io.IOException;

import java.io.StringReader;

import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerException;

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.NodeList;

import org.xml.sax.InputSource;

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;

public class string_to_xml extends AbstractTransformation {

@Override

public void transform(TransformationInput in, TransformationOutput out)

throws StreamTransformationException {

String inData = "";

try {

getTrace().addInfo("JAVA Mapping Iniciado");

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

DocumentBuilder db = dbf.newDocumentBuilder();

Document docIn = db.parse(in.getInputPayload().getInputStream());

NodeList nodos = docIn.getChildNodes();

if (nodos.item(0) != null) {

String xmlEmbebido = nodos.item(0).getTextContent();

InputSource source = new InputSource(new StringReader(

xmlEmbebido));

Document docOut = db.parse(source);

inData = getStringFromDocument(docOut);

inData=inData.replaceAll("XML_OUTPUT", "E_RESULTADO");

inData=inData.replaceAll("COD_RECHAZO", "CODIGO_RECHAZO");

}

} catch (Exception e) {

getTrace().addInfo("Excepcion: " + e.getMessage());

}

try {

out.getOutputPayload().getOutputStream().write(

inData.getBytes("UTF-8"));

getTrace().addInfo("JAVA Mapping Finalizado");

} catch (IOException e1) {

getTrace().addInfo("IOException e1: " + e1.getMessage());

}

}

public String getStringFromDocument(Document doc) {

try {

DOMSource domSource = new DOMSource(doc);

StringWriter writer = new StringWriter();

StreamResult result = new StreamResult(writer);

TransformerFactory tf = TransformerFactory.newInstance();

Transformer transformer = tf.newTransformer();

transformer.transform(domSource, result);

return writer.toString();

} catch (TransformerException ex) {

getTrace().addInfo("TransformerException e1: " + ex.getMessage());

return null;

}

}

}

The message that WS responds to the RFC is:

<?xml version="1.0" encoding="UTF-8"?><XML_OUTPUT><ERRORES><ERROR><COD_RECHAZO>1001</COD_RECHAZO><DESCRIPCION>The 'http://626_XIB.ProcesamientoMasivo/Esquema_AltaConvenios_SIBA_Entrada.xsd:FEAL_Q40' element is invalid - The value '0000-00-00' is invalid according to its datatype 'String' - The Pattern constraint failed.

The 'http://626_XIB.ProcesamientoMasivo/Esquema_AltaConvenios_SIBA_Entrada.xsd:TICU_Q40' element is invalid - The value '00000' is invalid according to its datatype 'String' - The actual length is greater than the MaxLength value.

</DESCRIPCION></ERROR></ERRORES></XML_OUTPUT>

Any suggestions?

anupam_ghosh2
Active Contributor
0 Kudos

Hi Ernesto,

                  From your first post I can make out the source XML. Could you please provide the complete intended target XML after mapping. The output suggested in your first post is not the complete XML , I beleive the output is content of a field within the target XML. Java mapping needs complete target XML structure.

Regards

Anupam 

ernesto_cruz
Participant
0 Kudos

Hi, Anupam, thanks for your interest.

Following with thread, the mapping request, actually is used a message mapping, the goal is use a Java Mapping,  (I'm display using 😞

The xmls are:

XML Source

<?xml version="1.0" encoding="UTF-8"?>

<ns0:ZDM_RFC_REPLICA_CONVENIOS_PI xmlns:ns0="urn:sap-com:document:sap:rfc:functions">

   <I_CONVENIO>

      <CANAL_ID/>

      <CANAL_CODIGO/>

      <CANAL_SISTEMA/>

      <ORIGEN_PETICION/>     

   </I_CONVENIO>

</ns0:ZDM_RFC_REPLICA_CONVENIOS_PI>

XML Target

<?xml version="1.0" encoding="UTF-8"?>

<ns1:AltaConvenios_SIBA xmlns:ns1="626_XIB.ProcesamientoMasivo">

   <ns1:strXmlEntrada><![CDATA[<CABECERA>

      <CANAL_ID/>

      <CANAL_CODIGO/>

      <CANAL_SISTEMA/>

      <ORIGEN_PETICION/>

   </CABECERA>]]></ns1:strXmlEntrada>

</ns1:AltaConvenios_SIBA>

Regards.

anupam_ghosh2
Active Contributor
0 Kudos

Hi Ernesto,

                Could you please try this java mapping code? I assume you are working in PI 7.1 or higher versions.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
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.AbstractTransformation;
import com.sap.aii.mapping.api.TransformationInput;
import com.sap.aii.mapping.api.TransformationOutput;
import com.sap.aii.mapping.api.StreamTransformationException;


public class DOMParser1  extends AbstractTransformation {

     
     

     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,child2;
               Node textChild,cdata;
               Node src;
               NodeList srcList;
               int i,l;
               String text="<CABECERA>";
               root=docOut.createElement("ns1:AltaConvenios_SIBA");
               root.setAttribute("xmlns:ns1","626_XIB.ProcesamientoMasivo");
               
               child1=docOut.createElement("ns1:strXmlEntrada");
               
              
               srcList=docIn.getElementsByTagName("I_CONVENIO").item(0).getChildNodes();
               l=srcList.getLength();
               String temp="";
               for(i=0;i<l;++i)
               {
               
                Node t;
              
                if(srcList.item(i).getNodeType()==Node.ELEMENT_NODE)
                {
                 temp+=("<" + srcList.item(i).getNodeName());
                 t=srcList.item(i).getFirstChild();
                 if(t!=null && t.getNodeType()==Node.TEXT_NODE)
                 {
                  temp+=">"+t.getTextContent();
                  temp+=("</" + srcList.item(i).getNodeName() + ">");
                 }
                 else
                 {
                  temp+="/>";
                 }
                }
              
               }
               temp="<CABECERA>"+temp+"</CABECERA>";
               cdata=docOut.createCDATASection(temp);
               child1.appendChild(cdata);
               docOut.appendChild(root);
               root.appendChild(child1);
               transform.transform(new DOMSource(docOut), new StreamResult(out));
          }
          catch(Exception e)
          {
               e.printStackTrace();
          }
          
     }

   

    

@Override
public void transform(TransformationInput arg0, TransformationOutput arg1)
   throws StreamTransformationException {
  // TODO Auto-generated method stub
  this.execute(arg0.getInputPayload().getInputStream(), arg1.getOutputPayload().getOutputStream());

   }

}

Hope this resolves the issue.

Regards

Anupam

ernesto_cruz
Participant
0 Kudos

Thanks a lot Anupam, the code is running ok.

Now, our situation is:

*RFC to WS(mapping provided by Anupam), from Runtime Workbench, I captured a message with data test, status message, succesful

*WS to RFC, from Runtime Workbench, I captured a message with data test, status message succesful

*The code used for WS to RFC was posted at previous thread.

*The message response was posted at previous thread.

But in the channel Sender, I have the following Snapshot

Some ideas about this issue?

Ernesto

nabendu_sen
Active Contributor
0 Kudos

Hi Ernesto,

The Response which is going back to RFC from Web Service is not matching with RFC Response structure. I hope you are using RFC Request and Response Structure in your mapping uploaded from SAP system in ESR. Also you have included a mapping program for Request Mapping and also for Response Mapping in the Interface/ Operation Mapping and included the same in Interface Determination.

ernesto_cruz
Participant
0 Kudos

Hi Nabendu, with respect your tips, the objects was revisited ok.

I need response Java mapping, from WS to RFC:

XML string (WS)

file1ws  xml attached

XML  (RFC)

file2rfc xml attached

Thanks in advance.

anupam_ghosh2
Active Contributor
0 Kudos

Hi Ernesto,

                    XML you have uploaded are not complete ones. I would also request you to open a new thread,if possible, with this new requirement as your original requirement has been already answered in this thread.

Regards

Anupam

ernesto_cruz
Participant
0 Kudos

Thanks for your cooperation, the thread main was resolved. I will open a new thread for follow with response mapping.

Regards!

Answers (3)

Answers (3)

nabendu_sen
Active Contributor
0 Kudos
baskar_gopalakrishnan2
Active Contributor
0 Kudos
Former Member
0 Kudos

Hi Cruz,

you try with this code, it will help you.

import java.io.*;

import javax.xml.parsers.*;

import org.w3c.dom.*;

import org.xml.sax.*;

import javax.xml.transform.*;

import javax.xml.transform.dom.DOMSource;

import javax.xml.transform.stream.StreamResult;

public class XMLtoString{

  static public void main(String[] args){

    try{

      BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        DocumentBuilder builder = factory.newDocumentBuilder();

        Document doc = builder.parse("1.xml");

        StringWriter stringWriter = new StringWriter();

        Transformer transformer = TransformerFactory.newInstance().newTransformer();

        transformer.transform(new DOMSource(doc), new StreamResult(stringWriter));

        String strFileContent = stringWriter.toString(); //This is string data of xml file

        System.out.println(strFileContent);

    }

    catch (Exception e){

      e.getMessage();

    }

  }

}

or

import java.io.IOException;

import org.apache.xerces.parsers.DOMParser;

import org.w3c.dom.Document;

import org.xml.sax.InputSource;

import org.xml.sax.SAXException;

public class String2XML {

    public static void main(String[] args) throws SAXException, IOException {

        String xml="

<CABECERA><CANAL_ID></CANAL_ID><CANAL_CODIGO></CANAL_CODIGO><CANAL_SISTEMA></CANAL_SISTEMA><ORIGEN_PETICION></ORIGEN_PETICION></CABECERA>

";

        DOMParser parser = new DOMParser();

        parser.parse(new InputSource(new java.io.StringReader(xml)));

        Document doc = parser.getDocument();

        System.out.println("String2XML.main()-"+doc.toString());

    }

}

Regards,

Bhaskar