cancel
Showing results for 
Search instead for 
Did you mean: 

Serializing SAX streams

Former Member
0 Kudos

Hey guys,

does anyone have a hint and/or a sample piece of java code on how to serialize a SAX-parsed stream without intermediary DOM documents?

I used a lot of DOM parsing in my java mappings but now I'm trying to get rid of DOM for performance purposes.

Thanks in advance,

Henrique.

Accepted Solutions (1)

Accepted Solutions (1)

Former Member
0 Kudos

Hi Pinto,

Are you lookinf for the follwoing kind of stuff?

/people/prasad.ulagappan2/blog/2005/06/29/java-mapping-part-ii

Cheers,

venu

henrique_pinto
Active Contributor
0 Kudos

Actually I was hoping for a method for which I didn't have to extend the whole DefaultHandler class...

But thanks for that, Sirangi.

Regards,

Henrique.

Former Member
0 Kudos

Hi Pinto,

try to find the following code.i have done it for one of the interfaces.. and find the useful..u expected..

/*

  • Created on 15-Jun-2006

*

  • To change the template for this generated file go to

  • Window>Preferences>Java>Code Generation>Code and Comments

*/

//package mvpDevelopment;

//package bin;

package mvpDevelopment;

import org.xml.sax.helpers.DefaultHandler;

import org.xml.sax.SAXException;

import org.xml.sax.Attributes;

import org.xml.sax.*;

import org.xml.sax.helpers.*;

import com.sap.aii.mapping.value.api.*;

import java.io.PrintWriter;

import java.util.*;

import java.io.*;

import java.util.Map;

import java.util.HashMap;

import javax.xml.parsers.SAXParserFactory;

import javax.xml.parsers.SAXParser;

import javax.xml.parsers.*;

import com.sap.aii.mapping.api.*; //StreamTransformation;

import com.sap.aii.mapping.value.api.*;

import com.sap.aii.mappingtool.tf3.rt.Container;

import com.sun.rsasign.b;

public class myMVPMapping extends DefaultHandler implements StreamTransformation

{

private String currentTag = "";

private String prevTag = "";

private PrintWriter printWriter = null;

private Map headerMap = null;

private OutputStream out;

private Map map;

//Anindita

private StringBuffer sbBuf = null;

// Constructor of the class

public myMVPMapping()

{

headerMap = new HashMap();

try

{

printWriter = new PrintWriter(new FileWriter("C:
Pratik
TargetOutput.xml",false),true);

}

catch(Exception e)

{

System.out.println(e.getMessage());

}

}

// set parameter method ...required but we don't do with it.

public void setParameter(Map param)

{

map = param;

}

// Execute method to be called by the XI

public void execute(InputStream in, OutputStream out) throws com.sap.aii.mapping.api.StreamTransformationException

{

DefaultHandler handler = this;

SAXParserFactory factory = SAXParserFactory.newInstance();

try

{

// Added by Onsite

// addtrace = container.getTrace();

// addtrace.addWarning("End of Java Mapping");

// End add

SAXParser saxParser = factory.newSAXParser();

this.out = out;

saxParser.parse(in,handler);

}

catch(Throwable t)

{

t.printStackTrace();

}

}

// method called at the start of document parsing

public void startDocument() throws SAXException

{

try

{

// write("<?xml version='1.0' encoding='UTF-8'?>");

emitTag("<?xml version='1.0' encoding='UTF-8'?>");

emitTag("<ns0:MT_MeterReading_IntermediateForm xmlns:ns0=\"urn://MVP_SR3_01/MVP/MeterReading\">");

// write("<Recordset>");

//System.out.println("<xml version='1.0' encoding='UTF-8'?>");

}

catch(Exception e)

{

System.out.println(e.getMessage());

}

}

//method called at the end of document parsing

public void endDocument() throws SAXException

{

if (prevTag.equals("H1") || prevTag.equals("D1") || prevTag.equals("D2") || prevTag.equals("U2")

|| prevTag.equals("UC"))

{

//Added by Onsite

emitTag("</Item>");

//End add

emitTag("</Recordset>");

headerMap.clear();

}

emitTag("</ns0:MT_MeterReading_IntermediateForm>");

}

//method called at the start of each tag parsing

public void startElement(String uri, String lName, String qName, Attributes attr) throws SAXException

{

String startTagName = lName;

if("".equals(startTagName))

{

startTagName = qName;

}

if(startTagName.equals("H1"))

{

//if (prevTag.equals("H1") || prevTag.equals("D1") || prevTag.equals("D2") || prevTag.equals("U2")

// || prevTag.equals("UC"))

//{

//emitTag("</Recordset>");

//headerMap.clear();

//}

/addded by suneel/

if (prevTag.equals("D1") || prevTag.equals("D2") || prevTag.equals("U2")

|| prevTag.equals("UC"))

{

emitTag("</Item>");

emitTag("</Recordset>");

headerMap.clear();

}

if (prevTag.equals("H1"))

{

emitTag("</Recordset>");

headerMap.clear();

}

currentTag = "H1";

prevTag = "H1";

}

//END

//Added by Onsite

else if (startTagName.equals("KEY"))

{

// write("<KEY>");

currentTag = "KEY";

}

//End

else if (startTagName.equals("CyclicNum"))

{

currentTag = "CyclicNum";

}

else if (startTagName.equals("RouteNum"))

{

currentTag = "RouteNum";

}

else if (startTagName.equals("MetReaderId"))

{

currentTag = "MetReaderId";

}

else if (startTagName.equals("TotRead"))

{

currentTag = "TotRead";

}

else if (startTagName.equals("TotDevUploaded"))

{

currentTag = "TotDevUploaded";

}

else if (startTagName.equals("D1"))

{

if (prevTag.equals("D1") || prevTag.equals("D2") || prevTag.equals("U2") || prevTag.equals("UC"))

{

emitTag("</Item>");

}

currentTag = "D1";

prevTag = "D1";

}

else if (startTagName.equals("AccountNumber"))

{

currentTag = "AccountNumber";

}

else if (startTagName.equals("MeterReadCode"))

{

currentTag = "MeterReadCode";

}

else if (startTagName.equals("ReadDate"))

{

currentTag = "ReadDate";

}

else if (startTagName.equals("TroubleCode"))

{

currentTag = "TroubleCode ";

}

else if (startTagName.equals("D2"))

{

currentTag = "D2";

prevTag = "D2";

}

else if (startTagName.equals("ChgdSplInstr"))

{

currentTag = "ChgdSplInstr";

}

else if (startTagName.equals("U2"))

{

currentTag = "U2";

prevTag = "U2";

}

else if (startTagName.equals("Data"))

{

currentTag = "Data";

}

else if (startTagName.equals("UC"))

{

currentTag = "UC";

prevTag = "UC";

}

else if (startTagName.equals("Data"))

{

currentTag = "Data";

}

else

{

currentTag = null;

}

}

//changed by Anindita

//method called at the end of each tag parsing

public void endElement(String uri, String sName, String qName) throws SAXException

{

String endTagName = sName;

if ("".equals(endTagName))

{

endTagName = qName;

}

if (sbBuf != null)

{

String strData = sbBuf.toString();

charManipulate(strData);

}

if (endTagName.equals("H1"))

{

emitTag("<Recordset>");

emitTag("<H1>");

String strRecordid="";

String strRouteNumber="";

String strMetReaderId="";

String strTotRead="";

String strTotDevUploaded="";

if (headerMap.get("KEY")!=null)

{

strRecordid = headerMap.get("KEY").toString();

}

if (headerMap.get("RouteNumber")!=null)

{

strRouteNumber = headerMap.get("RouteNumber").toString();

}

if (headerMap.get("MetReaderId")!=null)

{

strMetReaderId = headerMap.get("MetReaderId").toString();

}

if (headerMap.get("TotRead")!=null)

{

strTotRead = headerMap.get("TotRead").toString();

}

if (headerMap.get("TotDevUploaded")!=null)

{

strTotDevUploaded = headerMap.get("TotDevUploaded").toString();

}

emitTag("<Recordid>");emitContent(strRecordid);emitTag("</Recordid>");

emitTag("<RouteNumber>");emitContent(strRouteNumber);emitTag("</RouteNumber>");

emitTag("<MetReaderId>");emitContent(strMetReaderId);emitTag("</MetReaderId>");

emitTag("<TotRead>");emitContent(strTotRead);emitTag("</TotRead>");

emitTag("<TotDevUploaded>");emitContent(strTotDevUploaded);emitTag("</TotDevUploaded>");

emitTag("</H1>");

// write("</H1"prevTag">");

}

else if (endTagName.equals("D1"))

{

emitTag("<Item>");

emitTag("<D1>");

String strMetReaderId="";

String strTotDevUploaded="";

String strAccountNumber="";

String strMeterReadCode="";

String strReadDate="";

String strTroubleCode = "";

if (headerMap.get("MetReaderId")!=null)

{

strMetReaderId = headerMap.get("MetReaderId").toString();

}

if (headerMap.get("TotDevUploaded")!=null)

{

strTotDevUploaded = headerMap.get("TotDevUploaded").toString();

}

if (headerMap.get("AccountNumber")!=null)

{

strAccountNumber = headerMap.get("AccountNumber").toString();

}

if (headerMap.get("MeterReadCode")!=null)

{

strMeterReadCode = headerMap.get("MeterReadCode").toString();

}

if (headerMap.get("ReadDate")!=null)

{

strReadDate = headerMap.get("ReadDate").toString();

}

if (headerMap.get("TroubleCode")!=null)

{

strTroubleCode = headerMap.get("TroubleCode").toString();

}

emitTag("<HMetReaderId>");emitContent(strMetReaderId);emitTag("</HMetReaderId>");

emitTag("<HTotDevicesUploaded>");emitContent(strTotDevUploaded);emitTag("</HTotDevicesUploaded>");

emitTag("<AccountNumber>");emitContent(strAccountNumber);emitTag("</AccountNumber>");

emitTag("<MeterReadCode>");emitContent(strMeterReadCode);emitTag("</MeterReadCode>");

emitTag("<ReadDate>");emitContent(strReadDate);emitTag("</ReadDate>");

emitTag("<TroubleCode>");emitContent(strTroubleCode);emitTag("</TroubleCode>");

emitTag("</D1>");

}

else if (endTagName.equals("D2"))

{

emitTag("<D2>");

String strChgdSplInstruction = "";

if (headerMap.get("ChgdSplInstr")!=null)

{

strChgdSplInstruction = headerMap.get("ChgdSplInstr").toString();

}

emitTag("<ChgdSplInstr>");emitContent(strChgdSplInstruction);emitTag("</ChgdSplInstr>");

emitTag("</D2>");

}

else if (endTagName.equals("U2"))

{

emitTag("<U2>");

String strData = "";

if (headerMap.get("Data")!=null)

{

strData = headerMap.get("Data").toString();

}

emitTag("<Data>");emitContent(strData);emitTag("</Data>");

emitTag("</U2>");

}

else if (endTagName.equals("UC"))

{

emitTag("<UC>");

String strData = "";

if (headerMap.get("Data")!=null)

{

strData = headerMap.get("Data").toString();

}

emitTag("<Data>");

emitContent(strData);emitTag("</Data>");

emitTag("</UC>");

}

currentTag = "";

sbBuf = null;

}

//changed by Anindita

public void characters (char ch[], int offset, int length) throws SAXException

{

if (currentTag==null || "".equals(currentTag)) return;

String tagValue = new String(ch,offset,length);

if (sbBuf == null)

{

sbBuf = new StringBuffer(tagValue);

}

else

{

sbBuf.append(tagValue);

}

}

//Added by Anindita

private void charManipulate(String tagValue) throws SAXException

{

if (currentTag.equals("KEY"))

{

headerMap.put("KEY",tagValue);

}

else if (currentTag.equals("CyclicNum"))

{

headerMap.put("CyclicNumber",tagValue);

}

else if (currentTag.equals("RouteNum"))

{

headerMap.put("RouteNumber",tagValue);

}

else if (currentTag.equals("MetReaderId"))

{

headerMap.put("MetReaderId",tagValue);

}

else if (currentTag.equals("TotRead"))

{

headerMap.put("TotRead",tagValue);

}

else if (currentTag.equals("TotDevUploaded"))

{

headerMap.put("TotDevUploaded",tagValue);

}

else if (currentTag.equals("AccountNumber"))

{

headerMap.put("AccountNumber",tagValue);

}

else if (currentTag.equals("MeterReadCode"))

{

headerMap.put("MeterReadCode",tagValue);

}

else if (currentTag.equals("ReadDate"))

{

headerMap.put("ReadDate",tagValue);

}

else if (currentTag.equals("TroubleCode"))

{

headerMap.put("TroubleCode",tagValue);

}

else if (currentTag.equals("ChgdSplInstr"))

{

headerMap.put("ChgdSplInstr",tagValue);

}

else if (currentTag.equals("Data"))

{

headerMap.put("Data",tagValue);

}

}

//method for writing into the output stream

public void emitContent(String str) throws SAXException

{

//new code

try

{

String outputString = sanitizeText(str);

out.write(outputString.getBytes());

out.flush();

}

catch(Exception e)

{

throw new SAXException ("I/O Error",e);

}

}

char[] specialCharacters = { '&', '<', '>', '\'' };

String[] replacementStrings = { "&amp;", "&lt;", "&gt;", "&apos;" };

public String sanitizeText( String text ) throws SAXException

{

StringBuffer buffer = new StringBuffer( text );

String sample;

for( int i = 0; i < buffer.length(); i++ )

{

for( int k = 0; k < specialCharacters.length; k++ )

{

if( buffer.charAt(i) == specialCharacters[k] )

{

buffer.replace( i, i + 1, replacementStrings[k] );

i += replacementStrings[k].length();

}

/*else if( (int)buffer.charAt(i) > 128 )

{

String replacement = "&#" + (int)buffer.charAt(i) + ";";

buffer.replace( i, i + 1, replacement );

i += replacement.length();

}*/

}

}

return buffer.toString();

}

private void emitTag(String s)

throws SAXException

{

try {

out.write(s.getBytes());

out.flush();

} catch (IOException e)

{

throw new SAXException("I/O error", e);

}

}

}

Answers (3)

Answers (3)

henrique_pinto
Active Contributor
0 Kudos

Thank you for your inputs.

Regards,

Henrique.

Former Member
0 Kudos

Hi Henrique,

Yes, you can create XML document using SAX serialization technique.

Please have a look at the following sample code..


/*
 * Created on Mar 20, 2007
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package com.saxTest;

import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.helpers.AttributesImpl;

/**
 * @author Ananth
 */
public class SAX_Test_Plain {

	static TransformerHandler txHandler = null;

	public static void main(String[] args) {

		try {
			String val;
			SAX_Test_Plain obj = new SAX_Test_Plain();

			SAXTransformerFactory factory =
				(SAXTransformerFactory) SAXTransformerFactory.newInstance();
			txHandler = factory.newTransformerHandler();

			txHandler.setResult(new StreamResult(System.out));

			txHandler.startDocument();
			txHandler.startElement(
				"http://abc.corp/xyz/r3/SO_1234",
				"",
				"ns0:SO_Create",
				new AttributesImpl());

			txHandler.startElement("", "", "Header", new AttributesImpl());

			txHandler.startElement("", "", "SalesOrg", new AttributesImpl());
			val = "VK01";
			txHandler.characters(val.toCharArray(), 0, val.length());
			txHandler.endElement("", "", "SalesOrg");

			txHandler.startElement("", "", "DisChannel", new AttributesImpl());
			val = "Ch001";
			txHandler.characters(val.toCharArray(), 0, val.length());
			txHandler.endElement("", "", "DisChannel");

			txHandler.endElement("", "", "Header");
			txHandler.endDocument();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Hope this helps.

Regards,

Ananth

henrique_pinto
Active Contributor
0 Kudos

Hey Ananth,

the point is that I'm not creating an xml document from scratch. I have it in an input stream (java mapping). And since I'm not creating it, the only way to have that kind of access level during the parsing, using SAX parser, is if I extend the default handler class to automatically write the current element into the output stream (which I didn't want to do).

Thanks for the sample code, though.

Regards,

Henrique.

prateek
Active Contributor
0 Kudos
henrique_pinto
Active Contributor
0 Kudos

Hey Prateek,

thanks for that documentation, it's way more complete than the help.

I'll try one of those transformation methods (Sax -> stream) and let you know the result.

Regards,

Henrique.