Documente Academic
Documente Profesional
Documente Cultură
Training Courseware
Java Mapping
Bibinu
SAP-XI Consultant,
Capgemini Consulting India Pvt Ltd,
Vikhroli, Mumbai.
________________________
Phone +91 (0) 022-66496332
Fax +91 (0)22 5555 7000
_________________________
Page 1 of 40
Training Courseware
Java Mapping
TABLE OF CONTENTS
1.0 Scope.......................................................................................
2.0 What is Java Mapping..............................................................
3.0 Pre-requisite for Java Mapping.................................................
3.1 Mapping API............................................................................
3.2 SAX Parser..............................................................................
3.3 DOM Parser.............................................................................
4.0 When to use Java mapping in XI?...........................................
4.1 How is Java mapping different from Graphical, XSLT and ABAP
mapping?........................................................................................
4.2 Advantages of using Java mapping.............................................
4.3 Disadvantages of using Java mapping.........................................
5.0 SAP NetWeaver Developer Studio and Tools.................................
6.0 Steps for implementing Java mapping in XI..............................
7.0 Examples...............................................................................
7.1 Example 1 XML to XML (Using SAX Parser)..............................
7.2 Example 2 XML to XML (Using SAX Parser)..............................
7.3 Example 3 XML to XML (Using DOM Parser).............................
7.4 Example 4 XML to Text (Using DOM Parser).............................
7.5 Example 5 XML to HTML (Using SAX Parser)............................
7.6 Example 6 Text to XML ........................................................
8.0 When to use SAX and DOM parsers?........................................
9.0 References.............................................................................
i)
Links....................................................................................
ii)
SDN Weblogs/SAP help............................................................
Page 2 of 40
Training Courseware
1.0
Java Mapping
Scope
This document provides details you'll need to know about getting started
with the Java mapping. It also gives an overview regarding how to process XML
documents using Java API for XML Processing (JAXP). The JAXP supports the
Document Object Model (DOM) and the Simple API for XML (SAX). This gives
you great flexibility for mapping definitions with Java.
Examples outlining different transformations are also provided.
Details about XI Design and Configuration are not under the scope of this
document.
Target Audience
The document is intended for XI consultants trying to learn Java mapping.
Prior Knowledge of XI development environment is essential.
Page 3 of 40
Training Courseware
2.0
Java Mapping
3.0
Mapping API
The runtime environment for Java mappings has a mapping API. To use
Java mapping, you must define a Java class that implements the Java interface
com.sap.aii.mapping.api.StreamTransformation. This interface is available in
aii_map_api.jar. It has two methods:
...
Page 4 of 40
Training Courseware
Java Mapping
Meaning
Classification of message. Possible values
ApplicationMessage:
Asynchronous or synchronous request
message
ApplicationResponse:
Response to a request message
VERSION_MAJOR
Relevant
for PCK
Yes
Acknowledgment Messages
VERSION_MINOR
No.
The PCK only
supports
message
protocol XI 3.0.
No
PROCESSING_MODE
Yes
MESSAGE_ID
Yes
REF_TO_MESSAGE_ID
Yes
CONVERSATION_ID
Yes
TIME_SENT
Yes
YYYY-MM-DDTHH:MM:SSZ
The letter T separates the date from the
time, which is generally specified in UTC. If it is a
local time, the closing Z is omitted.
Page 5 of 40
Training Courseware
Java Mapping
INTERFACE
Yes
INTERFACE_NAMESPACE
Yes
Yes
SENDER_PARTY_AGENCY
Yes
SENDER_PARTY_SCHEME
Yes
SENDER_SERVICE
Yes
Yes
RECEIVER_NAMESPACE
Yes
RECEIVER_PARTY
Yes
RECEIVER_PARTY_AGENCY
Yes
RECEIVER_PARTY_SCHEME
Yes
RECEIVER_SERVICE
Yes
3.2
No
SAX Parser
The Simple API for XML or SAX is faster and more efficient than using the
DOM. SAX is a Java based API that is very robust and effective. These SAX
parsers make it easy for you to start using the Simple API for XML.
SAX parser is an Event Driven Parser. You provide the callback or handler
methods, and the parser invokes them as it reads the XML data. Finally, you can't
"back up" to an earlier part of the document, or rearrange it, any more than you
can back up a serial data stream or rearrange characters you have read from that
stream. The following Packages need to be imported in your Java File to use the
SAX parser.
import
import
import
import
java.io.*;
org.xml.sax.*;
javax.xml.parsers.SAXParserFactory;
javax.xml.parsers.SAXParser;
Page 6 of 40
Training Courseware
Java Mapping
Called when the Parser completes parsing the Current XML File.
public void endDocument () throws SAXException
{
......
}
Called when the starting of the Element is reached. For Example if we have Tag
called <Title> ... </Title>, then this method is called when <Title> tag is
encountered while parsing the Current XML File. The AttributeList Parameter
has the list of all Attributes declared for the Current Element in the XML File.
public void startElement (String name, AttributeList attrs) throws SAXException
{
......
}
Called when the Ending of the current Element is reached. For example in the
above explanation, this method is called when </Title> tag is reached.
public void endElement (String name) throws SAXException
{
......
Page 7 of 40
Training Courseware
Java Mapping
While Parsing the XML file, if extra characters like space or enter Character are
encountered then this method is called. If you don't want to do anything special
with these characters, then you can normally leave this method blank.
public void characters (char buf [], int offset, int len) throws SAXException
{
......
}
In the XML File if the parser encounters a Processing Instruction which is declared
like this <?ProgramName:ItemList QUERY="Descr, Type, Cost"?> then this
method is called where Target parameter will have "ProgramName:ItemList" and
data parameter will have QUERY=" Descr, Type, Cost". You can invoke an
external
Program
from
this
Method
if
required.
public void processingInstruction (String target, String data) throws SAXException
{
.......
}
3.3
DOM Parser
The Document Object Model (DOM) defines a standard way for accessing
and manipulating XML documents. It presents an XML document as a tree
structure, and gives access to the structure through a set of objects.
To use the DOM parser following packages need to be imported.
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import
import
import
import
org.w3c.dom.Document;
org.w3c.dom.Element;
org.w3c.dom.Node;
org.w3c.dom.NodeList;
DOM parser internally uses SAX parser hence the method parse(in)
throws SAXExecption and therefore the above code has to be put in a try block.
In DOM parser the entire XML is loaded into the memory and consumes a
lot of resources and hence it is processor intensive. After the document gets
loaded it is maintained as a tree structure.
Page 8 of 40
Java Mapping
Training Courseware
Item
(Length=4)
Descr
Base
unit
Item
(Length=5)
Cost
Mat_Descr
Type
Descr
Cost
Mat_Descr
Type
950
Telephone
set
Giftset
Alarm
Clock
350
Clock
Single
ELEMENT NODE
TEXT NODE
\n
Newline
character
Page 9 of 40
Java Mapping
Training Courseware
Since the 1st <Item> includes 4 elements under it i.e. <Descr>, <Cost>,
<Mat_Descr> and <Type> hence its length is 4 and length of each of the child
elements under <Item> is 1. It can also be possible that the length of <Item>
element be greater than 4 even if it has only 4 tags present under it. This is
because while parsing the document it also counts the newline characters or
blank spaces as a Node of type TEXT, hence the length of the 2nd <Item> is 5.
Some common set of objects which are used to access the tree structure
are given below.
org.w3c.dom.Document
The Document object represents the entire XML document. It is
the root-node of a document and provides the primary access to the
document's data. All nodes in a node-tree are childnodes of the
Document object.
A node can be an element node, an attribute node, a text node,
or any other of the node types explained in the "org.w3c.dom.Node"
section.
org.w3c.dom.Element
The Element object represents an element in an XML document.
If an element contains text, the text is represented in a text-node.
Element object can be used directly to retrieve either an Attr
object (Attribute) by name or an attribute value by name.
org.w3c.dom.Node
The Node object represents a node in the node-tree. A node
can be an element node, an attribute node, a text node, or any other
of the node types explained.
The following table lists the different node types, and which
node types they may have as children
Node type
Description
Children
Document
DocumentFragment
Represents
a
"lightweight"
Document object, which can
hold a portion of a document
Element,
ProcessingInstruction,
Comment, Text,
CDATASection,
EntityReference
DocumentType
None
Page 10 of 40
Java Mapping
Training Courseware
EntityReference
Element,
ProcessingInstruction,
Comment, Text,
CDATASection,
EntityReference
Element
Represents an element
Element, Text,
Comment,
ProcessingInstruction,
CDATASection,
EntityReference
Attr
Represents an attribute
Text, EntityReference
ProcessingInstruction
Represents
instruction"
None
Comment
Represents a comment
None
Text
Represents
textual
content
(character data) in an element
or attribute
None
CDATASection
None
Entity
Represents an entity
Element,
ProcessingInstruction,
Comment, Text,
CDATASection,
EntityReference
Notation
None
"processing
org.w3c.dom.NodeList
The NodeList object represents a node and its child-nodes as a
node-tree.
A node can be an element node, an attribute node, a text node,
or any other node types.
4.0
Page 11 of 40
Training Courseware
Java Mapping
4.1
Graphical mapping
Java mapping
XSLT mapping
ABAP mapping
4.2
When the required output is other than XML like Text, Html or XHTML
(html displayed as XML).
Page 12 of 40
Training Courseware
4.3
5.0
Java Mapping
Once the java mapping has been imported into XI, to incorporate any
further changes one has to compile the java program and import the
class file again into XI.
Next create a Package within that Project using File > New > Package (use
the Browse... button to select your project if it is not already listed in
Source Folder field).
Page 13 of 40
Training Courseware
Java Mapping
To create a Java class, use the Java Class wizard File > New > Class
(again use the Browse... buttons within the wizard to select the
appropriate Project and Package for your class).
aii_map_api.jar
To import an external jar file, go to the project properties > Java Build
Path > Libraries > Add External Jars
Page 14 of 40
Training Courseware
Java Mapping
To run any Java program, click on Run > Run.... Select Java Application as
the launch configuration and click New. Identify the program in the Project
and Class fields and then click Run.
NOTE: We are creating the main function only for testing the mapping
program in NWDS. Once it runs through successfully, remove the main
function and the constructor associated with that class before importing it
into XI.
6.0
Page 15 of 40
Training Courseware
Java Mapping
2. The next step is to identify the output structure which is to be mapped with
the source XML.
3. We then need to design a java program for mapping the source to target
structures using various classes and interfaces available.
Page 16 of 40
Training Courseware
Java Mapping
Page 17 of 40
Training Courseware
Java Mapping
Page 18 of 40
Training Courseware
Java Mapping
5. The next step is to define the Interface Mapping. The Source and Target
Message Interfaces are read. The mapping type is selected as java class and
the imported java class is selected as the mapping program to be used for the
transformation.
Page 19 of 40
Training Courseware
Java Mapping
Page 20 of 40
Training Courseware
7.0
Java Mapping
Examples
In Graphical Mapping, the parsing of source structure is handled internally
by XI. But, when you go for an explicit mapping technique like Java Mapping, you
have to parse the source XML structure, so that you can write the logic for your
mapping.
When the mapping class is executed, a method execute() is called, that
will take the source XML structure as the InputStream which has to be parsed
using SAX or DOM parser.
All the examples would be implemented within a File-to-File scenario.
7.1
Source message:
Page 21 of 40
Training Courseware
Java Mapping
Target message:
Page 22 of 40
Training Courseware
Java Mapping
}
catch (IOException e) {
e.notify();
}
}
This method will read the starting tag in the XML stream and writes it
back into the OutputStream as it is, except for the tag
MTO_SAP_MAT_DETAILS, which is replaced by MTI_FTP_MAT_DETAILS
in the output.
public void startElement(String namespaceURI, String sName, // simple name
String qName, // qualified name
Attributes attrs) throws SAXException {
String eName = sName; // element name
if ("".equals(eName))
eName = qName; // not namespace-aware
if ("ns0:MTO_SAP_MAT_DETAILS".equals(qName)){
try{
Echo.out.write (("<MTI_FTP_MAT_DETAILS>").getBytes());
}
catch(IOException e)
{
e.printStackTrace();
}
}
else{
try{
Echo.out.write (("<"+qName+">").getBytes());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This method will read the ending tag in the XML stream and writes it
back into the OutputStream as it is, except for the tag
MTO_SAP_MAT_DETAILS.
public void endElement(String namespaceURI, String sName, // simple name
String qName // qualified name
) throws SAXException {
String eName = sName; // element name
if ("".equals(eName))
eName = qName; // not namespace-aware
if ("ns0:MTO_SAP_MAT_DETAILS".equals(qName)){
try{
Page 23 of 40
Training Courseware
Java Mapping
Echo.out.write (("</MTI_FTP_MAT_DETAILS>").getBytes());
}
catch(Exception e)
{
e.printStackTrace();
}
}
else{
try{
Echo.out.write (("</"+qName+">").getBytes());
}
catch(Exception e)
{
e.printStackTrace();
}
This would copy the characters between the start and end tags of an
element into OutputStream.
public void characters(char buf[], int offset, int len)
throws SAXException {
String s = new String(buf, offset, len);
try{
Echo.out.write (s.getBytes());
}
catch(Exception e)
{
e.printStackTrace();
}
}
Package
7.2
Source message:
Page 24 of 40
Training Courseware
Java Mapping
Target message:
The target requirement is to categorize all the items from the
source message based on the material description and the type of
material.
For e.g; Cordless and Base Unit belongs to a Telephone set.
Page 25 of 40
Java Mapping
Training Courseware
The object of class Material would be used to hold the data retrieved
from the InputStream. If there are multiple items belonging to the
same category then the description and cost of all those items would
be stored in the vectors Descr and Cost.
class Material {
Vector Descr;
Vector Cost;
String TotalCost;
String MatDescr;
String Type;
}
Page 26 of 40
Training Courseware
Java Mapping
This method will read the starting tag (element) in the XML stream
and sets the appropriate flag which would be used later to determine
which element is getting processed currently.
public void startElement(String namespaceURI, String sName, // simple name
String qName, // qualified name
Attributes attrs) throws SAXException {
String eName = sName; // element name
if ("".equals(eName))
eName = qName; // not namespace-aware
if (eName.equals("Item")) {
ItemF = 1;
}
if (eName.equals("Descr")) {
DescrF = 1;
}
if (eName.equals("Cost")) {
CostF = 1;
}
if (eName.equals("Type")) {
TypeF = 1;
}
if (eName.equals("Mat_Descr")) {
MatDescrF = 1;
}
This method will reset the flag variables specifying the completion of
processing of an element i.e. whenever an end tag is encountered the
flag referring to that particular tag is reset.
When the Item end tag is encountered, since the item tag
encapsulates all the details of an item, it identifies that the processing
of all the details of that particular item is complete. Once the item is
Page 27 of 40
Training Courseware
Java Mapping
Page 28 of 40
Training Courseware
Java Mapping
MTemp.Cost.removeAllElements();
MTemp.Cost.addElement(s);
MTemp.TotalCost = new String(s);
}
if (ItemF == 1 && MatDescrF == 1) {
MTemp.MatDescr = s;
}
if (ItemF == 1 && TypeF == 1) {
MTemp.Type = s;
}
}
Package
7.3
Source message:
Target message:
Page 29 of 40
Training Courseware
Java Mapping
Page 30 of 40
Java Mapping
Training Courseware
Start of
execute(in,
out)
Write start tag
<MTI_OUTPUT>
into the
OutputStream
End of
execute(in, out)
Is Child !=
Null?
Yes
Type of
Child =
Text?
Yes
Write the node
value into the
OutputStream
No
Type of
Child =
Element?
Yes
No
Call function
getnodes(Child)
Page 31 of 40
Java Mapping
Training Courseware
Start of
getnodes(child)
Return
Is Child !=
Null?
Yes
Type of
Child =
Text?
Yes
Write the node
value into the
OutputStream
No
Type of
Child =
Element?
Yes
No
Call function
getnodes(Child)
Page 32 of 40
Training Courseware
Java Mapping
Page 33 of 40
Training Courseware
Java Mapping
}
catch (IOException ex) {
}
Package
7.4
Source message:
Target message:
Page 34 of 40
Training Courseware
Java Mapping
Package
7.5
Source message:
Page 35 of 40
Training Courseware
Java Mapping
Target message:
Package
7.6
Page 36 of 40
Training Courseware
Java Mapping
Source message:
Target message:
Page 37 of 40
Training Courseware
Java Mapping
The buffered input can be read line by line or even by characters. The
file which we are processing is a comma delimited file and the data
within a line read can be extracted easily using the delimiter.
The following code demonstrates how the Item and Cost within
each line of the file is read.
while ((line = bin.readLine()) != null) {
String Item = line.substring(0, line.indexOf(","));
String Cost = new String( line.toCharArray(),
line.indexOf(",") + 1,
line.length() - Item.length() - 1);
Package
8.0
The choice between DOM and SAX depends on several factors like Size of XML
Document, Speed, Memory Resources, Navigation and some times ease of programming
too.
Memory considerations
Ease of Programming
As the name implies SAX is a very simple solution to process the XML
Documents but puts the burden on the programmer. This is because in SAX the
programmer has to create his own object model and write code that respond to
the SAX events. Whereas incase of DOM, it creates the object model and gives a
reference to the object model. We can make use of DOM with less code but we
got to do lot of work to use SAX.
Page 38 of 40
Training Courseware
Java Mapping
Efficiency
SAX is more efficient than DOM when the object model that is built upon
on SAX by the programmer is simple. This is because SAX does less work than
DOM and can be really fast at runtime.
Navigation
Some scenarios
We take a few real time scenarios and analyze the appropriate use of SAX
and DOM.
1. Consider that a news agency Application has an XML Document that
holds the national, International and local news information. The users
of that news agency frequently search within that document structure
to find required information. Assuming that there are no memory
constrains, which one of the two (DOM, SAX) has to be used for paring
the XML Document by the application? As the Application needs to do
frequent search, DOM is considered the best solution. This is because
DOM creates a tree-based representation in memory and this tree
object model is very useful for frequent access or search. The only
disadvantage of DOM is that it consumes more memory resources. As
there are no memory constraints in this case, DOM is the best choice.
2. Consider that we need to extract only a subset of information that is
present in a large Size XML Document. Which is the best way to do it?
Event based API is the best choice to do it. This is because SAX
Processes the XML Documents sequentially and so it does not have to
process the whole document to extract the required information. On
the other hand, DOM creates a tree based in memory representation of
the whole document. Document size being large in this case, this
consumes lot of memory resources and is not the right choice.
3. Consider that XML documents of document management system
contain document data, application data, scripts or other code within
the document. These applications and scripts explore and edit the
document content. Which is the best way to process such XML
Documents? DOM is the best way to do process these types of XML
Documents. This is because DOM allows programs to access and edit
the information stored in these documents. On the other hand, SAX
can only deal with structured data.
9.0
References
Page 39 of 40
Training Courseware
Java Mapping
i) Links
(a) JAXP APIs for XML
http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/packagesummary.html
(b) Using the SAX and DOM APIs
http://java.sun.com/developer/TechTips/2000/tt0627.html
(c) XML DOM Tutorial
http://www.w3schools.com/dom/default.asp
(d) DOM Vs SAX
http://www.code101.com/Code101/DisplayArticle.aspx?cid=37
ii) SDN Weblogs/SAP help
(a) Java Mapping
http://help.sap.com/saphelp_nw04/helpdata/en/14/80243b4a66ae0ce
10000000a11402f/frameset.htm
(b) SAX Parser weblog
https://www.sdn.sap.com/irj/sdn/weblogs?blog=/pub/wlg/1817
(c) Java Mapping weblog
https://www.sdn.sap.com/irj/sdn/weblogs?blog=/pub/wlg/1945(Part1)
https://www.sdn.sap.com/irj/sdn/weblogs?blog=/pub/wlg/1946(Part2)
https://www.sdn.sap.com/irj/sdn/weblogs?blog=/pub/wlg/1947(Part3)
Page 40 of 40