We help IT Professionals succeed at work.
Get Started
Troubleshooting Question

Exception Replacing while replacing characters suing String Builder in Java Map

kalyangkm
kalyangkm asked
on
59 Views
Last Modified: 2021-02-26
Hi,
I am trying to run a main program for the java class which replaces bunch of characters and adds CDATA tags. The program is working good as it is deployed in our production env. I just need to add some enhancement. But before doing that I was trying to run the program by writing a main program which takes input_test11.xml as input. It should generate the output_test.xml. I am getting "Null Pointer Exception" when I call the "replaceCharacter" method of the Java Class. All I need is to know the reason and how to run the Main program. Please note the same input_test11.xml file works fine in my production env. So, I suppose there is something wrong with my main program. Please provide some feedback. PFA  aslo is the input_test11.xml and the Required libraries:
input_test11.xml
Libraries Required (please change them to .jar when loading into eclipse):
com.sap.xi.mapping.tool.lib_api.txt
com.sap.xpi.ib.mapping.lib.txt

Java Class
package com.XXXXXXe;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

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 ConvertDocumentDTE extends AbstractTransformation {
      Date date;
      public static Map<String, String> CHARACTERSET = new HashMap<String, String>();
      private static String SPACE = " ";
      
      static {      
        //CHARACTERSET.put(NULL, SPACE); already in the control character list
              /// Control/printable characters, agreed to add this
        for(int i = 0; i <= 31; i++) {
           CHARACTERSET.put(String.valueOf((char)i), SPACE);
        }
        //CHARACTERSET.put(String.valueOf((char)127), SPACE);   
        for(int i = 127; i <= 160; i++) {
           CHARACTERSET.put(String.valueOf((char)i), SPACE);
        }
        
     }

      @Override
      /*
      * Standard TRANSFORM method, which will be called from Operation Mapping.
      */
      public void transform(TransformationInput inXml, TransformationOutput outXml) throws StreamTransformationException {
            date = new Date();
            
            

            InputStream inSream;
            String outputPayload = new String();
            String inputPayload = new String();

            try {
                  // Read input into input Stream;
                  inSream = inXml.getInputPayload().getInputStream();
                  
                  StringBuilder replacedData = this.replaceCharacter(inSream);
                  inputPayload = new String(replacedData.toString());
                  inSream.close();
                  outputPayload = xmlContentHandler(inputPayload);
                  ByteBuffer buff = encode(outputPayload, false);
                  // getTrace().addInfo("call encode END");
                  // getTrace().addInfo("buff.toString():" + buff.toString());

                  byte[] bytes = new byte[buff.remaining()];
                  buff.get(bytes, 0, bytes.length);
                  // getTrace().addInfo("length byte[]:" + bytes.length);
                  outXml.getOutputPayload().getOutputStream().write(bytes);

            } catch (Exception e) {
                  getTrace().addWarning("Error in the Map: " + e.toString());
            }
      }

      /**
      * Converts the provided String to bytes using the UTF-8 encoding. If
      * <code>replace</code> is true, then malformed input is replaced with the
      * substitution character, which is U+FFFD. Otherwise the method throws a
      * MalformedInputException.
      * 
       * @return ByteBuffer: bytes stores at ByteBuffer.array() and length is
      *         ByteBuffer.limit()
      */
      public static Charset charset = Charset.forName("UTF-8");

      public static ByteBuffer encode(String string, boolean replace) throws CharacterCodingException {
            CharsetEncoder encoder = charset.newEncoder();
            if (replace) {
                  encoder.onMalformedInput(CodingErrorAction.REPLACE);
                  encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
            }
            ByteBuffer bytes = encoder.encode(CharBuffer.wrap(string.toCharArray()));
            if (replace) {
                  encoder.onMalformedInput(CodingErrorAction.REPORT);
                  encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
            }
            return bytes;
      }
      
      public static String xmlContentHandler(String rawXmlContent) {
            if (rawXmlContent == null) return "null";
            
            // first remove all "<![CDATA[" and "]]"
            rawXmlContent = rawXmlContent.replaceAll("<!\\[CDATA\\[", "");
            rawXmlContent = rawXmlContent.replaceAll("\\]\\]>", "");
            
            //then put payload inside "<![CDATA["
            rawXmlContent = rawXmlContent.replaceAll("<DTE version=\"2.0\">", "<![CDATA[<?xml version=\"1.0\" encoding=\"UTF-8\"?><DTE version=\"2.0\">");
            rawXmlContent = rawXmlContent.replaceAll("</DTE>", "</DTE>]]>");
           
            return rawXmlContent;
      }
      
      public StringBuilder replaceCharacter(InputStream in) throws Exception {
        StringBuilder sb = new StringBuilder(25000);
        try
        {
           //InputStreamReader isr = new InputStreamReader(in);
           InputStreamReader isr = new InputStreamReader(in, "UTF-8");
           getTrace().addDebugMessage(isr.getEncoding());
           //Reader reader = new BufferedReader(isr);
           int ch;
           boolean isInXMLElement = true;
           while((ch = isr.read()) > -1) {
              char myChar = (char) ch;
              
              //to ignore the replacement in XML <element name> or </element name>
              if(myChar == '<')
                 isInXMLElement = true;
              else if(myChar == '>') {
                 isInXMLElement = false;
                 sb.append(myChar);
                 continue;
              }
              
              if(isInXMLElement == true)
                 sb.append(myChar);
              else {
                 String sValue = CHARACTERSET.get(String.valueOf(myChar));
                 //getTrace().addDebugMessage("@@myChar: " + new Integer(ch).toString());
                 if (sValue == null)
                    sb.append(myChar);
                 else {
                    getTrace().addDebugMessage("@@myChar: " + new Integer(ch).toString());
                    getTrace().addDebugMessage("@@myChar string: " + String.valueOf((char)ch));
                    getTrace().addDebugMessage("@@sValue: " + sValue.charAt(0));
                    
                    //String.valueOf((char)i
                    sb.append(sValue.charAt(0));
                 }
              }
           }
           isr.close();
        }
        catch(Exception ex) { 
           getTrace().addDebugMessage("@@Error at replacement characters: " + ex.getMessage());
           throw ex;
        }
        
        getTrace().addDebugMessage("Length" + sb.length());
        return sb;
      }

}

The Main Program

package com.XXXXXX;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;


public class TheMain {
   
   public static void main(String[] args) throws Exception{
      // TODO Auto-generated method stub
      ConvertDocumentDTE convert = new ConvertDocumentDTE();
      
     
        String outputPayload = new String();
        String inputPayload = new String();
      
      FileInputStream fin = new FileInputStream("input_test1.xml");
      FileOutputStream fout = new FileOutputStream("output_test.xml");
      
      StringBuilder replacedData = convert.replaceCharacter(fin);
      
      /// special treatment for character '&amp;', 
        inputPayload = new String(replacedData.toString());
        outputPayload = convert.xmlContentHandler(inputPayload);
        ByteBuffer buff = convert.encode(outputPayload, false);
        // getTrace().addInfo("call encode END");
        // getTrace().addInfo("buff.toString():" + buff.toString());

        byte[] bytes = new byte[buff.remaining()];
        buff.get(bytes, 0, bytes.length);
        // getTrace().addInfo("length byte[]:" + bytes.length);
        fout.write(bytes);
         
       fout.close();
      
   }

}

Comment
Watch Question
This problem has been solved!
Unlock 1 Answer and 14 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE