My First Java Mapping in PI 7.1

Hi, i'm having a problem with my first Java Mapping in PI 7.1
I was reading examples and i create a class that extends "AbstractTransformation", there's a "transform" method and it request two params with "TransformationInput" type.
I created a main method to test it, but i have a problem converting the InputStream to TransformationInput.
Anybody had this problem?
Regards,
Sebastián.

Hi Sebastian,
   Trasform method is like a main method in JAVA Mapping,the execution starts from the trasform method,TrasformationInput method reads the input from Input stream reader,and TrasformtionOut write out in in output stream.
public class FirstJavaMap extends AbstractTransformation {
     public void transform(TransformationInput in,TransformationOutput out)
      throws StreamTransformationException {
try{
your logic...
}catch(Exception e)..........
like that
refer below link ,it helps you...
http://help.sap.com/saphelp_nwpi71/helpdata/EN/43/bc2fd4da1e1bbce10000000a1553f7/content.htm
Regards,
Raj

Similar Messages

  • JAVA Mapping: Convert the InputStream in  to OutputStream out

    Hi everybody,
    I'd like to code my first JAVA Mapping. For this I would just like to convert the InputStream in  to OutputStream out.
    This does not work:
    out = new FileOutputStream(new File(in));
    How has the code look like?
    Thanks, regards
    Mario

    Hi Mario.
    Do you want to convert input into output directly without doing any transformation?
    The way I've always used is to load the input document first:
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(inputStream);
    After loading the document you can parse it's content with DOM API.
    Finally you create the transformed document and return it through outputstream:
    Document resultDoc = builder.newDocument();
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    DOMSource source = new DOMSource(resultDoc);
    StreamResult result = new StreamResult(outputStream);
    transformer.transform(source, result);
    If  you want to convert the input to output you can use:
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(inputStream);
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(outputStream);
    transformer.transform(source, result);
    At this point, I think you will have the input into the output.
    Regards,
    Gari.

  • Creation of additional attachment in Java Mapping

    Hello all,
    I want to use a Java Mapping with the functionality to create a second /attachment which I can send over email out?
    I don’t want to pick this file somewhere from the server, instead I want to fill the content of the additional attachment directly in the java mapping.
    I hope somebody knows the answer of my question.
    If its possible is there any kind of example??
    Many thanks for your help
    ilka

    hi Stefan,
    http://scn.sap.com/thread/1874962
    Regarding the comment in this thread, can you please tell me if you have faced any issue with creating output attachments. Right now, i have a message mapping in which i have written a udf to create attachments
    this message mapping is a multi mapping and the source is 0-unb. I have used a return as xml on the root message and pointed it to the udf after split by value.
    There are three root nodes in one of my cases, and when this goes through this mapping, there is 1 attachemnt each created with three main documents and submain documents. However, all the attachments contain details of the first root node itself where in actually it should be each main and submain document having a different attachment. Please find my udf below. Please let me know if you think it is wrong somewhere.
    udf :-
    GlobalContainer globalContainer = container.getGlobalContainer();
    OutputAttachments outputAttachments = globalContainer.getOutputAttachments() ;
    int flag =0;
    AbstractTrace trace = container.getTrace();
    String attachmentName = "";
    //for(int i=0;i<var1.length;i++){
    try
    var1=var1.replaceAll("><",">\n<");
    attachmentName = "attachment"+cnt;
    Attachment newopAttachment = outputAttachments.create((attachmentName), var1.getBytes("UTF-8"));
    outputAttachments.setAttachment(newopAttachment);
    trace.addInfo("newopAttachment"+newopAttachment);
    cnt=cnt+1;
    attachmentName ="";
    newopAttachment = null;
    var1="";
    catch (Exception e)
    trace.addInfo("ever reaching trace");
          e.printStackTrace(); 
    //result.addValue("1");  
    //result.addValue("1");  
    return "1";
    Input :-
    Messages
    Message1
    SBDH
    SBDH
    SBDH
    Each of the above SBDH, i have returned as xml and pointed to the udf after split by value
    Your help is highly appreciated.
    Regards,
    Ninu

  • Keystore access in Java Mapping Program - user J2EE_GUEST

    Dear Gurus,
    I have the following problem:
    I need to validate the digital signature of a XML document and I'm using some examples provided by SAP as follows:
              InitialContext ctx = ctx = new InitialContext();          
              Object o = (Object) ctx.lookup("keystore");          
              KeystoreManager manager = (KeystoreManager) o;          
              KeyStore ks = manager.getKeystore("Serasa");
    {/code}
    But I get the error below, saying that user J2EE_GUEST is not authorized. How do I change the user who executes java mapping, because I granted permissions in Visual Admin to another user.
         at com.sap.aii.ibrun.sbeans.mapping.MappingServiceObjectImpl0_0.processFunction(MappingServiceObjectImpl0_0.java:131)
         at sun.reflect.GeneratedMethodAccessor267.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:62)
         at java.lang.reflect.Method.invoke(Method.java:391)
         at com.sap.engine.services.ejb.session.stateless_sp5.ObjectStubProxyImpl.invoke(ObjectStubProxyImpl.java:187)
         at $Proxy218.processFunction(Unknown Source)
         at sun.reflect.GeneratedMethodAccessor266.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:62)
         at java.lang.reflect.Method.invoke(Method.java:391)
         at com.sap.engine.services.rfcengine.RFCDefaultRequestHandler.call(RFCDefaultRequestHandler.java:284)
         at com.sap.engine.services.rfcengine.RFCDefaultRequestHandler.handleRequest(RFCDefaultRequestHandler.java:219)
         at com.sap.engine.services.rfcengine.RFCJCOServer$J2EEApplicationRunnable.run(RFCJCOServer.java:254)
         at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
         at java.security.AccessController.doPrivileged(AccessController.java:219)
         at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:104)
         at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:176)
    Caused by: com.sap.engine.services.keystore.exceptions.BaseKeystoreException: User is not authorized to execute keystore operation[{GET_VIEW Serasa }]
         at com.sap.engine.services.keystore.impl.security.UserBasedSecurityConnector.checkUserPermission(UserBasedSecurityConnector.java:889)
         at com.sap.engine.services.keystore.impl.security.SecurityRestrictionsChecker.checkUserPermission(SecurityRestrictionsChecker.java:52)
         at com.sap.engine.services.keystore.impl.security.SecurityRestrictionsChecker.isUserAuthorized(SecurityRestrictionsChecker.java:148)
         at com.sap.engine.services.keystore.impl.security.SecurityRestrictionsChecker.checkPermission(SecurityRestrictionsChecker.java:174)
         at com.sap.engine.services.keystore.impl.ParameterChecker.checkPermission(ParameterChecker.java:35)
         at com.sap.engine.services.keystore.impl.KeystoreManagerImpl.checkPermission(KeystoreManagerImpl.java:46)
         ... 28 more
    Caused by: java.security.KeyStoreException: (thread: SAPEngine_Application_Thread[impl:3]_56,view:Serasa, entry: , user: J2EE_GUEST) - checkPermissions  'getView': com.sap.engine.services.security.exceptions.BaseSecurityException: Caller not authorized.
         at com.sap.engine.services.keystore.impl.security.UserBasedSecurityConnector.checkFailed(UserBasedSecurityConnector.java:1097)
         at com.sap.engine.services.keystore.impl.security.UserBasedSecurityConnector.checkPermissions_getView(UserBasedSecurityConnector.java:773)
         at com.sap.engine.services.keystore.impl.security.UserBasedSecurityConnector.checkUserPermission(UserBasedSecurityConnector.java:823)
         ... 33 more
    {/code}
    Thank you very much

    Hi Fabio,
    first of all have you checked if standard functions to verify digital signature for pi adpaters would work for you?
    We have used the following code to access the Keystore in a custom adapter. It accesses the keystore with the access rights of a JEE application (it has a reference to the sample adapter "sap.com/com.sap.aii.adapter.sample.ra"). Check out if it works in your mapping, too.
    import java.security.Key;
    import java.security.KeyStore;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.PublicKey;
    import java.security.UnrecoverableKeyException;
    import java.util.HashMap;
    import java.util.Map;
    import javax.resource.ResourceException;
    import com.sap.aii.af.service.resource.SAPSecurityResources;
    import com.sap.aii.security.lib.KeyStoreManager;
    import com.sap.aii.security.lib.PermissionMode;
    public class XIKeystoreAccessor {
        private static final XITrace TRACE = new XITrace(XIKeystoreAccessor.class.getName());
        static XIKeystoreAccessor instance = null;
        SAPSecurityResources securityResources;
        KeyStoreManager keystoreManager;
        Map<String, KeyStore> keystores = null;
        private XIKeystoreAccessor() throws ResourceException {
         final String SIGNATURE = "XIKeystoreAccessor()";
         TRACE.entering(SIGNATURE);
         keystores = new HashMap<String, KeyStore>();
         securityResources = SAPSecurityResources.getInstance();
         try {
             keystoreManager = securityResources.getKeyStoreManager(PermissionMode.SYSTEM_LEVEL,
                  new String[] { "sap.com/com.sap.aii.adapter.sample.ra" });
         } catch (KeyStoreException e) {
             TRACE.catching(SIGNATURE, e);
             throw new ResourceException(e);
         TRACE.exiting(SIGNATURE);
         * Get a key from AS Java keystore
         * @param view
         * @param alias
         * @param password
         * @return
         * @throws ResourceException
        public Key getPrivateKey(String view, String alias, String password) throws ResourceException {
         final String SIGNATURE = "getPrivateKey()";
         TRACE.entering(SIGNATURE);
         KeyStore keystore = getKeystore(view);
         Key privateKey = null;
         try {
             privateKey = keystore.getKey(alias, password.toCharArray());
             if (privateKey == null) {
              throw new ResourceException("Key not found. alias=" + alias);
         } catch (KeyStoreException e) {
             TRACE.catching(SIGNATURE, e);
             throw new ResourceException(e);
         } catch (NoSuchAlgorithmException e) {
             TRACE.catching(SIGNATURE, e);
             throw new ResourceException(e);
         } catch (UnrecoverableKeyException e) {
             TRACE.catching(SIGNATURE, e);
             throw new ResourceException(e);
         TRACE.exiting(SIGNATURE);
         return privateKey;
        public PublicKey getPublicKey(String view, String alias) throws ResourceException {
         final String SIGNATURE = "getPublicKey()";
         TRACE.entering(SIGNATURE);
         KeyStore keystore = getKeystore(view);
         PublicKey publicKey = null;
         try {
             publicKey = keystore.getCertificate(alias).getPublicKey();
             if (publicKey == null) {
              throw new ResourceException("Key not found. alias=" + alias);
         } catch (KeyStoreException e) {
             TRACE.catching(SIGNATURE, e);
             throw new ResourceException(e);
         TRACE.exiting(SIGNATURE);
         return publicKey;
         * Get a keystore i.e. a view from AS Java
         * @param view
         * @return
         * @throws ResourceException
        public KeyStore getKeystore(String view) throws ResourceException {
         final String SIGNATURE = "getKeystore()";
         TRACE.entering(SIGNATURE);
         KeyStore keystore;
         try {
             if (keystores.containsKey(view) == true) {
              keystore = keystores.get(view);
             } else {
              keystore = keystoreManager.getKeyStore(view);
              if (keystore == null) {
                  throw new ResourceException("Keystore not found. view=" + view);
              keystores.put(view, keystore);
             TRACE.exiting(SIGNATURE);
             return keystore;
         } catch (KeyStoreException e) {
             TRACE.catching(SIGNATURE, e);
             throw new ResourceException(e);
        static public XIKeystoreAccessor getInstance() throws ResourceException {
         if (instance == null) {
             instance = new XIKeystoreAccessor();
            return instance;

  • Problem in Java Mapping

    Hi,
          I was trying out a simple Java mapping example.
    Example of source structure is -
    <?xml version="1.0"?>
    <ns0:MT_SRC xmlns:ns0="http://www.sap-press.com/xi/training/00">
    <organization>
    <employee>
    <firstname>Jack</firstname>
    <lastname>Rose</lastname>
    </employee>
    <employee>
    <firstname>Paul</firstname>
    <lastname>McNealy</lastname>
    </employee>
    <employee>
    <firstname>Vaibhav</firstname>
    <lastname>Pandey</lastname>
    </employee>
    </organization>
    </ns0:MT_SRC>
    Example of target structure is -
    <?xml version="1.0" encoding="UTF-8"?>
    <ns0:MT_TRGT xmlns:ns0="http://www.sap-press.com/xi/training/00"><Organization><employee><name>JackRose</name></employee><employee><name>PaulMcNealy</name></employee><employee><name>VaibhavPandey</name></employee></Organization></ns0:MT_TRGT>
    and here's the code I'm using
    package com.mapping;
    import java.io.*;
    import java.util.Map;
    import java.util.HashMap;
    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.MappingTrace;
    import com.sap.aii.mapping.api.StreamTransformation;
    public class JavaMap implements StreamTransformation{
         private Map param = null;
            private MappingTrace  trace = null;
            public void setParameter (Map param) {
                this.param = param;
                if (param == null) {
                    this.param = new HashMap();
            public void execute(InputStream in, OutputStream out) {
                   OutputStreamWriter buf_writer = new OutputStreamWriter(out);        
                   InputStreamReader buf_reader = new InputStreamReader(in);
                   String mat = new String();
                   String extmat = new String();
                   try {
                        buf_writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>" ,0,56);
                        buf_writer.write("<ns0:MT_TRGT xmlns:ns0=\"http://www.sap-press.com/xi/training/00\">");
                        buf_writer.write("<Organization>",0,20);
                        buf_writer.flush();
                  } catch(IOException e){};
                  try {
                       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();          
                       factory.setValidating(false);          
                       DocumentBuilder builder = factory.newDocumentBuilder();          
                       Document doc = builder.parse(in);
                        String fname = null;
                        String lname = null;
                        doc.getDocumentElement().normalize();
                        //System.out.println("Root element " + doc.getDocumentElement().getNodeName());
                        NodeList nodeLst = doc.getElementsByTagName("employee");
                        //System.out.println("Information of all employees");
                        for (int s = 0; s < nodeLst.getLength(); s++) {
                        Node fstNode = nodeLst.item(s);
                        if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
                             buf_writer.write("<employee>");     
                        Element fstElmnt = (Element) fstNode;
                        NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("firstname");
                        Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
                        NodeList fstNm = fstNmElmnt.getChildNodes();
                        //System.out.println("First Name : " + ((Node) fstNm.item(0)).getNodeValue());
                        fname = fstNm.item(0).getNodeValue();
                        NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("lastname");
                        Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
                        NodeList lstNm = lstNmElmnt.getChildNodes();
                        //System.out.println("Last Name : " + ((Node) lstNm.item(0)).getNodeValue());
                        lname = lstNm.item(0).getNodeValue();
                        buf_writer.write("<name>"fname" "lname"</name>");
                        buf_writer.write("</employee>");
                        buf_writer.write("</Organization>");
                        buf_writer.write("</ns0:MT_TRGT>");
                        TransformerFactory tFactory = TransformerFactory.newInstance();
                     Transformer transformer = tFactory.newTransformer();
                     transformer.setOutputProperty("indent", "yes");
                     DOMSource source = new DOMSource(doc);
                     StreamResult result = new StreamResult(out);
                     transformer.transform(source, result);
                        } catch (Exception e) {
                        e.printStackTrace();
    However, when I'm testing my Interface mapping, I'm getting the following error -
    Call method execute of the application Java mapping com.mapping.JavaMap
    Error during appliction Java mapping com/mapping/JavaMap
    java.lang.StringIndexOutOfBoundsException at java.lang.String.getChars(String.java:672)
    Could anyone please help me out with this?
    Thanks and Regards,
    Shiladitya

    HI,
    It looks to be that your JavaMap class have one field whihc will be not getting the proper value as input thus its creating the array Index out of bound exception.
    Please can you verify if you have assigned the proper String size for all the fields.
    Or probably you are getting the blank value which have created the execption.
    Also can you narrow down and let me know about the line String.getChars(String.java:672)
    Here you have used the try and catch option but may be the exact line no. can give better idea about the problem.
    Thanks
    swarup

  • Issue with java mapping in a multi-mapping scenario

    Hi
        We have  a 1:n multiple mapping scenario in XI and the source is R3 proxy and target side is files. So, creating multiple file from a single message from R3 .
    R3 --> XI --> Multiple files
    Structure of the output of the multi-mapping is
    - <ns0:Messages xmlns:ns0="http://sap.com/xi/XI/SplitAndMerge">
    - <ns0:Message1>
    <Transaction>
    </Transaction>
    <Transaction>
    </Transaction></ns0:Message1>
    </ns0:Messages>
    wherein each Transaction node represents a file.
    Now, we need to introduce a constant /string like
    <!DOCTYPE Transaction PUBLIC \"-//XXXXXX//DTD BatchReceiptAuthorization//EN\" \"http://dtd.XXXXXXX.com/dtds/ReceiptAuthorization.dtd\">
    on each of the files at the very beginning - i.e within each transaction node , in the above structure, we need the above DTD string to be written.  To do this, we added a java mapping as the second mapping after the message mapping that creates this string. Is this the right approach and would it produce what we are expecting ?
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.util.Map;
    import com.sap.aii.mapping.api.StreamTransformation;
    import com.sap.aii.mapping.api.StreamTransformationException;
    import com.sap.aii.mapping.api.StreamTransformationConstants;
    import com.sap.aii.mapping.api.DynamicConfiguration;
    import com.sap.aii.mapping.api.AbstractTrace;
    public class ModifyRootAndDelay implements StreamTransformation {
         AbstractTrace myTrace;
    public void execute(InputStream input, OutputStream output) throws StreamTransformationException {
              try{
                   BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                   String NameSpacePrefix = "<!DOCTYPE Transaction PUBLIC \"-//innotrac//DTD BatchReceiptAuthorization//EN\" \"http://dtd.innotrac.com/dtds/ReceiptAuthorization.dtd\">";
                   String sLine = null;
                   StringBuffer XmlMsg= new StringBuffer();
                   String Result,PayloadBody;
                   int indexOfFirst;
                   while ((sLine = reader.readLine()) != null) {
                        XmlMsg.append(sLine);
                   String StartingTag = XmlMsg.toString();
                   indexOfFirst = StartingTag.indexOf("<MerchantID>") ;
                   PayloadBody=new String(XmlMsg.substring(indexOfFirst));
                   Result=NameSpacePrefix.concat(PayloadBody);
                   output.write(Result.getBytes());
              /*     Thread.sleep(200000); */
              }catch(Exception e){
                   myTrace.addWarning("Exception raised in the JavaMapping:modifyNamespace.java""\n The Exception Message: " e.getMessage());
                   throw new RuntimeException(e.getMessage()) ;
            }     public void setParameter(Map param) {
              myTrace = (AbstractTrace) param
                        .get(StreamTransformationConstants.MAPPING_TRACE);

    Hi XI Gurus
                       In my scenario, I sent the inputstream that is being passed to the Java execute method - to trace and I see that the whole of the xml file - as shown below  - which is the output of message mapping ( from the first mapping step ) in sent to the execute method of the java mapping a single call
    <ns0:Messages xmlns:ns0="http://sap.com/xi/XI/SplitAndMerge">
    <ns0:Message1>
    <Transaction> </Transaction>
    <Transaction> </Transaction>
    </ns0:Message1>
    <ns0:Messages>
    So, I modified Java mapping program to look for multiple occurences of <Transaction> tag and prefix them with my constant DTD Literal - which is the primary reason , why I had to use Java mappings after the message mapping.
    Now, I get an error is XI- SXMB_MONI
    - <SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="">
      <SAP:Category>XIServer</SAP:Category>
      <SAP:Code area="MAPPING" />
      <SAP:P1>unexpected symbol; expected '<', '</', entity refe</SAP:P1>
      <SAP:P2>rence, character data, CDATA section, processing i</SAP:P2>
      <SAP:P3>0</SAP:P3>
      <SAP:P4>113</SAP:P4>
      <SAP:AdditionalText />
      <SAP:ApplicationFaultMessage namespace="" />
      <SAP:Stack>The exception occurred (program: CL_XMS_MAIN===================CP, include CL_XMS_MAIN===================CM00A, line: 609)</SAP:Stack>
      <SAP:Retry>M</SAP:Retry>
      </SAP:Error>
    Should I create multiple outputs - as many as the numberof target split files ( of type outputstream ) from the execute method in the java program ?

  • Can I leverage JDom or Dom4J for java mapping in PI 7.0?

    Hi,
    since we know that PI 7.0 is based on jdk1.4 which officially allows DOM and SAX,but could I using the open source API like JDom or Dom4J via importing the related jar file to PI IR for java mapping?Anyone tried that?

    Hi ,
             I tried importing jar files into PI7.0 I was able to do so.
    First add the external jar file for JDOM into build path in eclipse (or NWDS). I did this in eclipse.
    Again I tried to import the same jar file into project within eclipse. Then the jar file will be broken into class files.
    Now compile the JDOM code you wrote and do project ->build all. This will generate the class file for your source code in addition to the class files formed earlier. Now exit from eclipe. Move to source folder of the eclipse. there you will find the .java file and the set of class files which were imported into the project earlier. Copy these files to separete folder say "myclass". Now again move to "bin" folder of your eclipse settings and obtain the .class file for the source code you have written. Copy this class file to the  "myclass" folder. Now using WINZIP zip all files into one ZIP file within "myclass" folder. Finally import this ZIP into PI 7.0 server. Run the mapping code using test tab. If you are getting any linkage error then you need to obtain correct external jar for JDOM parser else the mapping should run fine.
    Regards
    Anupam

  • Error in Java Mapping program

    Hi friends,
    I am tryin java mapping for first time.. and created one java program using link https://www.sdn.sap.com/irj/scn/wiki?path=/display/xi/wholePayloadtoaXML+field
    But when I am compiling it using JAVAC, I am getting following error message that
    package com.sap.aii.mapping.api does not exist . How can I solve this error.
    Complete error is as follows:
    C:j2sdk1.4.2_16-x64 in>javac PayloadToXMLField.java
    PayloadToXMLField.java:1: package com.sap.aii.mapping.api does not exist
    import com.sap.aii.mapping.api.StreamTransformation;
                                   ^
    PayloadToXMLField.java:2: package com.sap.aii.mapping.api does not exist
    import com.sap.aii.mapping.api.AbstractTrace;
                                   ^
    PayloadToXMLField.java:3: package com.sap.aii.mapping.api does not exist
    import com.sap.aii.mapping.api.StreamTransformationConstants;
                                   ^
    PayloadToXMLField.java:8: cannot resolve symbol
    symbol  : class StreamTransformation
    location: class PayloadToXMLField
    public class PayloadToXMLField implements StreamTransformation {
                                              ^
    PayloadToXMLField.java:16: cannot resolve symbol
    symbol  : class AbstractTrace
    location: class PayloadToXMLField
        AbstractTrace trace;
        ^
    PayloadToXMLField.java:27: cannot resolve symbol
    symbol  : class AbstractTrace
    location: class PayloadToXMLField
                (AbstractTrace) param.get(
                 ^
    PayloadToXMLField.java:28: cannot resolve symbol
    symbol  : variable StreamTransformationConstants
    location: class PayloadToXMLField
                    StreamTransformationConstants.MAPPING_TRACE);
                    ^
    PayloadToXMLField.java:43: cannot resolve symbol
    symbol  : variable outputPayload
    location: class PayloadToXMLField
            outputPayload =
            ^
    PayloadToXMLField.java:50: cannot resolve symbol
    symbol  : variable outputPayload
    location: class PayloadToXMLField
                out.write(outputPayload.getBytes());
                          ^
    9 errors
    Thanks,
    Brijesh Soni

    thanks , it is done now..
    the program is compiled properly and class file is generated.
    but m gettin error in mapping.
    in IR i created two message type  with data type as string.
    and i had imported the class file and java program using Imported archives.
    now in interface mapping mapping program i had selected type as Java Class.and name of java program.
    but when i tested it, it is giving error as Linkage error occurred when loading class zip/PayloadToXMLField
    Please suggest, M i doing some thing wrong?is any thing missing?
    Program tht i had used in java
    from link (https://www.sdn.sap.com/irj/scn/wiki?path=/display/xi/wholePayloadtoaXML+field):
    import com.sap.aii.mapping.api.StreamTransformation;
    import com.sap.aii.mapping.api.AbstractTrace;
    import com.sap.aii.mapping.api.StreamTransformationConstants;
    import java.util.Map;
    import java.io.*;
    public class PayloadToXMLField implements StreamTransformation {
        String strXML = new String();
        String outputPayload = new String();
         //Declare the XML tag for your XML message
         String StartXMLTag = "<Payload>";
         String EndXMLTag = "</Payload>";
        AbstractTrace trace;
        private Map param = null;
        public void setParameter(Map param) {
            this.param = param;
        public void execute(InputStream in, OutputStream out) {
            trace =
                (AbstractTrace) param.get(
                    StreamTransformationConstants.MAPPING_TRACE);
            trace.addInfo("Process Started");
            try {
                StringBuffer strbuffer = new StringBuffer();
                byte[] b = new byte[4096];
                for (int n;(n = in.read(b)) != -1;) {
                    strbuffer.append(new String(b, 0, n));
                strXML = strbuffer.toString();
            } catch (Exception e) {
                System.out.println("Exception Occurred");
            outputPayload =
                "<?xml version="1.0" encoding="UTF-8"?>"
                   + StartXMLTag
                   + strXML
                   + EndXMLTag;
            try {
                out.write(outputPayload.getBytes());
                   trace.addInfo("Process Completed");;
            } catch (Exception e) {
                trace.addInfo("Process Terminated: Error in writing out payload");;
    and detailed trace of error is:
    11:34:21 Start of test
    LinkageError at JavaMapping.load(): Could not load class: zip/PayloadToXMLField
    java.lang.NoClassDefFoundError: zip/PayloadToXMLField (wrong name: PayloadToXMLField) at java.lang.ClassLoader.defineClass0(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:539) at java.lang.ClassLoader.defineClass(ClassLoader.java:448) at com.sap.aii.ibrep.server.mapping.ibrun.RepMappingLoader.findClass(RepMappingLoader.java:175) at java.lang.ClassLoader.loadClass(ClassLoader.java:289) at java.lang.ClassLoader.loadClass(ClassLoader.java:235) at com.sap.aii.ibrep.server.mapping.ibrun.RepJavaMapping.load(RepJavaMapping.java:136) at com.sap.aii.ibrep.server.mapping.ibrun.RepJavaMapping.execute(RepJavaMapping.java:50) at com.sap.aii.ibrep.server.mapping.ibrun.RepMappingHandler.run(RepMappingHandler.java:80) at com.sap.aii.ibrep.server.mapping.rt.MappingHandlerAdapter.run(MappingHandlerAdapter.java:107) at com.sap.aii.ibrep.server.mapping.ServerMapService.transformInterfaceMapping(ServerMapService.java:127) at com.sap.aii.ibrep.server.mapping.ServerMapService.transform(ServerMapService.java:104) at com.sap.aii.ibrep.sbeans.mapping.MapServiceBean.transform(MapServiceBean.java:40) at com.sap.aii.ibrep.sbeans.mapping.MapServiceRemoteObjectImpl0_0.transform(MapServiceRemoteObjectImpl0_0.java:167) at com.sap.aii.ibrep.sbeans.mapping.MapServiceRemoteObjectImpl0_0p4_Skel.dispatch(MapServiceRemoteObjectImpl0_0p4_Skel.java:104) at com.sap.engine.services.rmi_p4.DispatchImpl._runInternal(DispatchImpl.java:319) at com.sap.engine.services.rmi_p4.DispatchImpl._run(DispatchImpl.java:200) at com.sap.engine.services.rmi_p4.server.P4SessionProcessor.request(P4SessionProcessor.java:136) at com.sap.engine.core.service630.context.cluster.session.ApplicationSessionMessageListener.process(ApplicationSessionMessageListener.java:33) at com.sap.engine.core.cluster.impl6.session.MessageRunner.run(MessageRunner.java:41) at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37) at java.security.AccessController.doPrivileged(Native Method) at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:102) at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:172)
    11:34:21 End of test

  • XML Validation with XSD in java mapping

    Hi experts,
    I have created an interface to send differents messages between bussines system, the bussiness system receiver is put in the message, to get this value I have a configuration file indicating the path of this field for each message type. In a java mapping I transform the message sent in this structure:
    <document>
    <message>HERE THE MESSAGE AS STRING</message>
    <parameters>
    <sender>HERE SENDER BUSSINESS SYSTEM</sender>
    <receiver>HERE RECEIVER BUSSINESS SYSTEM</receiver>
    </parameters>
    </document>
    the messaging interface works fine, but now I have to validate the XML vs XSD. I need doing in a java mapping because the messaging interface send the message and a email to sender in error case.
    To do this validation I have implemented two java mappings that works fine in my local, the first way is with class Validator of java 5, but my system PI 7.1 return an error with this class. The second way is with SAX parse:
    String schema = "XXXXXxsd";
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setNamespaceAware(true);
    docBuilderFactory.setValidating(true);
    docBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage","http://www.w3.org/2001/XMLSchema");
    InputStream is = this.getClass().getClassLoader().getResourceAsStream(schema);
    docBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource",is);
    in my local works fine but in PI always return OK never fail.
    For this moment the schema is hardcoded to do proofs, in the future will be loaded from my configuration file.
    Any idea?
    Thanks in advance
    Jose

    hi Jose,
    PI 7.1 has a built in feature available called XML vaidations ..
    your source xml can be validated against a XSD placed at a specific location on the PI server..
    validation can be performed at adapter/integration engine
    http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/d06dff94-9913-2b10-6f82-9717d9f83df1?quicklink=index&overridelayout=true

  • Java mapping for XSD Validation

    Hello,
    I have developed a Java mapping to validate an XML based on XSD.
    I works fine and generates a message with error details.
    I would like to create a report with all errors encountered during this Validation and to stop this message from being sent to the partner.
    But this Java mapping stops at first error encountered and generates an error message with first error only even though document has more errors further.
    Can anyone please let me know if there is an option to log all errors without allowing the message to go through?
    Thanks.
    Best Regards,
    Shweta

    Yes, as abhishek mentioned when you validate the instance document (XML) using standard parsers then they validate based on the spec provided in XSD and they stop at the first error. The link given using dom parser via java code will also stop at the first error.
    If you really want to validate the entire instance document then you might have to create a custom validator class which does validation for each and every fields and store it in an object like Vector or List or Map object.  Then when you throw exception you can retrieve that Map object  in the catch block and read all the individual error messages and display in log. This requires additional effort. In this case you dont rely on parser validation. Completely custom based.
    Example:
    Vector errorList = new Vector();
    if the field name is  SSN and if you see any alpha characters you add error for that field in the errorList
    If(SSN.matches("[a-zA-Z]")){
        do nothing
    }else{
        errorList.add("The fieldName SSN contains other than alpha characters");
    Like that you have to add error string mesg in the errorList object and return the errorList at the end.

  • Java mapping for EDI order document

    hi,
    My project is to convert a EDI-850 Purchase Order Document using XI into an R/3 system.I planned t use java mapping So,I had got the java code necessary for the mapping from a tool called ALTOVA XML MAPRFORCE.
    I have converted the code into a .jar file and put into the XI server.The mapping is working fine now. If i give an EDI order document as input to the mapping and test the mapping the out put is coming correctly.
    Now i dont know what I should do in the Integration directory.
    As I have to convert this document and post it in a R/3 system.I have found the function module to create a Purchase Order also "BAPI_PO_CREATE".
    What should I do next ?

    Hi Mithun,
    Follow the steps below:
    1. BAPI is a RFC function module. So you import into Integration Repository. Then map your output to the structure of RFC.
    2. In the integration Directory,
    a. Create a business service representing your source.
    b. Create a business system representing your R/3 system.
        Before creating business sytem, first you need to register it as a techincal system and business system in sld.
    c. Create a Sender Agreement to pick the message from source system. Depending upon the type of source system, you need to configure the sender adapter.
    d. Create Receiver determination to route the message to the target system
    e. Create interface determination to pick the current Interface mapping to convert source message to target message
    f. Create Receiver Agreement to send the message to R/3 System. This should encapsulate Receiver Communication channel which is using IDoc adapter.
    Reward if helpful.
    Regards,
    Suraj Kumar.

  • Java Mapping for Flat file

    hello SDNers,
    I am using JAVA mapping for converting FlatFlie IDoc to IDoc and i am using metadata for this.While downloading metadata from SAP system, the first segment in the data record is having level 2.
    1) What is the use of Level in metadata?
    2)  What is the Level for first segment in data record of metadata. Is it Level 1 or Level 2?
    3) I am facing an error while appending the node. Is it because of Level differs?
    Plese help me out and thanks in advance

    Hi,
    >>>I am using JAVA mapping for converting FlatFlie IDoc to IDoc and i am using metadata for thi
    why do you develop is from scratch is the code is already there - just copy and paste...
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/46759682-0401-0010-1791-bd1972bc0b8a
    >>>1) What is the use of Level in metadata?
    this shows how the nested segments in IDOC are to be understood
    >>>3) I am facing an error while appending the node. Is it because of Level differs?
    no, it becase your code is incorrect - the level velidation will be done at the receiver
    Regards,
    Michal Krawczyk

  • Getting Error in java mapping: Parsing empty source. Root element expected!

    Hi Experts,
       I am using java mapping for schema validation of input message. I have followed all the standard procedures and implemented the java class in the interface mapping.
    My interface mapping is like this:
    OrderData --->Java Class ---SchemaValidate
                         Mesg Map ---OrderData_to_BAP --->BAPI Msg
    So first I want to validate the schema of the input message. If the input message is invalid then XI should throw an exception. Then I use the actual message mapping to map the input order data to the BAPI input parameters.
    In the java code I am using xerces parser.
    The java code works fine when I run it as a standalone application.
    The interface mapping also works fine if I don't include the java mapping. Ofcourse schema validation does not happen.
    But when I test the interface mapping by including the java mapping then I am getting the error:
    Call method execute of the application Java mapping SchemaValidate
    Java mapping SchemaValidate completed. (execute() of SchemaValidate
    com.sap.aii.utilxi.misc.api.BaseRuntimeException: Parsing an empty source. Root element expected!
    What am I doing wrong? Why it is not getting the root element?
    My Java code is as follows:
    import com.sap.aii.mapping.api.StreamTransformation;
    import com.sap.aii.mapping.api.StreamTransformationConstants;
    import com.sap.aii.mapping.api.StreamTransformationException;
    import java.io.*;
    import java.util.Map;
    import javax.xml.parsers.*;
    import org.xml.sax.helpers.*;
    import org.xml.sax.*;
    import org.apache.xerces.jaxp.*;
    Sample mapper for SAP-XI
    @author Gopal
    public class SchemaValidate implements StreamTransformation {
        //Constants when using XML Schema for SAX parsing.
         static final String JAXP_SCHEMA_LANGUAGE =
         "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
         static final String W3C_XML_SCHEMA =
         "http://www.w3.org/2001/XMLSchema";
         static final String JAXP_SCHEMA_SOURCE =
         "http://java.sun.com/xml/jaxp/properties/schemaSource";
    Injection of mapping parameters
    from integration engine
    @param map Map with configuration data
        public void setParameter(Map map) {
    Mapping implementation
    @param inputStream Input data from integration engine
    @param outputStream Output data to integration engine
        public void execute(InputStream inputStream,
                            OutputStream outputStream)
          throws StreamTransformationException {
            try {
                  // obtain an object of class javax.xml.parsers.SAXParser,
                  SAXParserFactory spf = SAXParserFactoryImpl.newInstance();
                  spf.setNamespaceAware(true);
                  spf.setValidating(true);
                  SAXParser sp = spf.newSAXParser();
                  // setup the schema file
                  sp.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
                  sp.setProperty(JAXP_SCHEMA_SOURCE, new File("IOReqMsgSchema.xsd"));
                  //parse the input xml using the given schema
                  sp.parse(inputStream, new ParseErrorHandler());
            catch(SAXException se) {
              se.printStackTrace();
            catch ( Exception e ) {
              throw new StreamTransformationException( e.getMessage() );
    My input message is :
    <?xml version="1.0" encoding="UTF-8"?>
    <ns0:OrderCreate_request xmlns:ns0="mynamespace">
       <ORDER>HTEST1234567</ORDER>
       <ORDER_TYPE>z001</ORDER_TYPE>
       <ORDER_NAME>Test Order</ORDER_NAME>
       <CO_AREA>INTC</CO_AREA>
       <CCTR_POSTED>1234567890888888888</CCTR_POSTED>
       <CURRENCY>USD</CURRENCY>
       <PERSON_RESP>12345679</PERSON_RESP>
    </ns0:OrderCreate_request>
    Kindly help! please this is urgent!!!!!!
    Thanks
    Gopal
    Edited by: gopalkrishna baliga on Feb 28, 2008 9:34 AM

    Hi Stefan,
       I did the code changes to return output stream and the java code works perfectly in standalone mode in my PC.
       But when I use the same in the Java mapping with XI then It throws an error "Getting Error in java mapping: Parsing empty source. Root element expected!".
    My XI J2EE server has JDK1.4.3.11.
    Is there any limitation of using SAX parser in XI? If Yes, then which parser should be used for schema validation in XI?
    I have included the XSD file for schema validation along with class files in the .jar file. This jar file is then imported in XI repository. Is the XI engine not able to read the XSD file?
    Do I have to handle reading XSD file differently? Any suggession how?
    Is this parser error due to some security access?
    Kindly help me! I have been struggling with this problem since 2 weeks. I will be greatfull to you if you can help me.
    Thanks
    Gopal

  • Java Mapping XML Encoding Error.

    Hi All,
    I hav an IDoc XML coming out of R/3 whose encoding technique is UTF-8. I hav to change it to ISO-8859-1 before parsing the xml in the java mapping program. i have seen this problem repeating among many people but i cud not find any solution on the SDN. Can any one help me out in this regard?
    Thnx in Adv.
    Anil

    Hi Anil,
    put following XSLT a first place of interface mapping:
    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
         <xsl:output encoding="ISO-8859-1"/>
         <xsl:template match="/">
              <xsl:copy-of select="*"/>
         </xsl:template>
    </xsl:stylesheet>
    Regards,
    Udo

  • SOAP Adapter with JAVA Mapping.

    Hi,
    I am trying a scenario,
    file->SOAP Receiver->SOAP Sender->IDOC
    in this I have used two interface mapping(and two mapping also).
    In first mapping i used Java mapping. so the WSDL of this is of no use for me.
    and in second mapping graphical mapping is performed.
    but my scenario is not woking completely. only one messge in SXMB_MONI is displayed. but it should be two. I think there is some problem in java mapping.
    in java mapping i have generated XML output, which will be input of SOAP sender.
    plaese suggest me the format which should be generated by java mapping.

    Sandeep,
    Let me try to put your requiremen,
    You have 2 scenariom
    FILE to SOAP
    SOAP to Idoc
    When the file becomes availbale, the Scenario 1 triggers of Scenario 2. Scenario 2 provides you a WSDL and so scneario 1 's output should be of the format of this WSDL.
    Hope I am on the correct track.
    If yes, just import this WSDL into your IR, and see the format in which it expects the data by using it as a message type in some mapping ( dummy mapping ) and then in your Java Mapping create a output of the same format, with the same namespace etc.
    Regards,
    Bhavesh

Maybe you are looking for