Extra Tips and Advices by PenTest Magazine Handling XML data...

9

Transcript of Extra Tips and Advices by PenTest Magazine Handling XML data...

Page 1: Extra Tips and Advices by PenTest Magazine Handling XML data …cassiopae.com/wp-content/uploads/2014/03/PenTest_OPEN_03... · 2018. 1. 7. · Extra Tips and Advices by PenTest Magazine
Page 2: Extra Tips and Advices by PenTest Magazine Handling XML data …cassiopae.com/wp-content/uploads/2014/03/PenTest_OPEN_03... · 2018. 1. 7. · Extra Tips and Advices by PenTest Magazine

Extra Tips and Advices by PenTest Magazine

69

Handling XML data with Javaby Azza NAFTI

The success of a project depends on several factors – primarily, on the technical choices and the development language. Fortunately, Java software is highly portable across multiple operating systems hence, a solution for free, scalable open-source is achievable. We begin by presenting the article’s description and learning goals (XML, Java EE platform). Consequently, we move to the manipulation of XML data with Java.

What the article says How to handle XML data, either by creating an XML file, or browse an existing XML file.

What you should knowThis article is intended for a beginner level audience, who already possess a first experience with XML and Java EE platform. We begin with a brief presentation as following:• XML stands for “eXtensible Markup Language”. It is extensible in a point of not using predefined tags as HTML and

allows defining new tags. XML is used to exchange data between disparate applications, because it allows to mod-el and store data in a portable manner. XML and Java have common-based portability through the systems inde-pendence and their environment.

• The Java EE platform is a set of coordinated specifications and practices that enables solutions for developing, de-ploying, and managing applications. It contains a large number of APIs such as SAX (Simple API for XML) and DOM (Document Object Model).

Firstly we will learn how to create an XML file from a Java class. Secondly, we move to step of browsing an XML file and retrieve the desired data from a Java class. All the manipulations will be made using the library JDOM.

Definition of JDOMJDOM (abbreviation for Java Document Object Model) is an open source library for handling XML files in Java. It integrates DOM and SAX. Also, it supports XPath and XSLT. And it uses external parsing to build documents.

Advantages of JDOMSimplicityThe simplicity of JDOM encompasses easy handling and effective XML documents in Java. However, DOM effect was not designed to be implemented in any programming language, and specifically in Java. The main criticism of DOM is that it does not take a full advantage of the Java power. Another criticism is that DOM also must represent HTML (with its imperfections, therefore, not only well-formed XML). The creators of JDOM have started from scratch, designing an API for pure XML and pure Java. The JDOM API is supposed to be more intuitive and less likely to generate programming errors.

This ease of use JDOM makes API more widespread.

DisadvantagesHas less featuresIn the role of three form manipulation, JDOM has fewer features than DOM, on the contrary, it offers greater ease to meet more traditional use cases.

Page 3: Extra Tips and Advices by PenTest Magazine Handling XML data …cassiopae.com/wp-content/uploads/2014/03/PenTest_OPEN_03... · 2018. 1. 7. · Extra Tips and Advices by PenTest Magazine

Extra Tips and Advices by PenTest Magazine

70

FeaturesJDOM provides several features:

• Creating XML documents

• Encapsulation of an XML document in the form of Java API objects

• Exporting a document to the file, a SAX stream or a DOM tree

• Support for XSLT

• Support for Xpath

CharacteristicsCharacteristic points of the JDOM API:

• It is developed specifically for Java and using the features of Java on syntactic or semantic level (using Java 2 collections , the new operator is able to instantiate elements redefinition of equals(), hashCode(), toString(), implementing Cloneable and Serializable interfaces, ... )

• It is intuitive and productive through the classes dedicated to each element, which is instantiated within their constructor and use getter / setter. For example, take a look at the text of an element:

DOM: String content = element.getFirstChild().getValue();JDOM: String text = element.getText();

• It operates fast and light

• It intends to hide the complexity of some XML aspects while respecting specifications

• It must allow interaction between SAX and DOM; JDOM can encapsulate an XML document into a hierarchy of objects from a stream, a DOM tree or SAX events. It is also able to export a document in these formats.

Create an XML fileYou must initially download the latest version of JDOM available at: http://www.jdom.org/dist/binary/. Then access the file /build/jdom.jar, placing it in your classpath.

We will create an XML file containing the coordinates of the employees in a company. We will create the XML root is “Company” in this case, the “Company” contains a list of employees “Employee”, which adequately contains the FirstName and LastName, Age,Occupation/Job/Position, Address and PhoneNumber for each employee in the class JDOM1 present in Listing 1.

Page 4: Extra Tips and Advices by PenTest Magazine Handling XML data …cassiopae.com/wp-content/uploads/2014/03/PenTest_OPEN_03... · 2018. 1. 7. · Extra Tips and Advices by PenTest Magazine

Extra Tips and Advices by PenTest Magazine

71

Listing 1. The JDOM1 Class

package XMLPackage;import java.io.*;import org.jdom2.*;import org.jdom2.output.*;

class JDOM1{ static Element root = new Element («Company»);

static Document document = new Document(root);

public static void main(String[] args) {

//////////////////////////// Employee1 ///////////////////////////// Element Employee = new Element(«Employee»); root.addContent(Employee);

Attribute classe = new Attribute(«degree»,»E1»); Employee.setAttribute(classe);

Element FirstName = new Element(«FirstName»); FirstName.setText(«John»); Employee.addContent(FirstName);

Element LastName = new Element(«LastName»); LastName.setText(«Blue»); Employee.addContent(LastName);

Element Age = new Element(«Age»); Age.setText(«40»); Employee.addContent(Age);

Element Job = new Element(«Job»); Job.setText(«Technical Director»); Employee.addContent(Job);

Element Address = new Element(«Address»); Address.setText(«London Road No5600,N60»); Employee.addContent(Address);

Element PhoneNumber = new Element(«PhoneNumber»); PhoneNumber.setText(«03-5327-1100»); Employee.addContent(PhoneNumber);

//////////////////////////// Employee2 ///////////////////////////// Element Employee2 = new Element(«Employee»); root.addContent(Employee2); Attribute classe2 = new Attribute(«degree»,»E2»); Employee2.setAttribute(classe2);

Element FirstName2 = new Element(«FirstName»); FirstName2.setText(«Davy»); Employee2.addContent(FirstName2);

Element LastName2 = new Element(«LastName»);

Page 5: Extra Tips and Advices by PenTest Magazine Handling XML data …cassiopae.com/wp-content/uploads/2014/03/PenTest_OPEN_03... · 2018. 1. 7. · Extra Tips and Advices by PenTest Magazine

Extra Tips and Advices by PenTest Magazine

72

LastName2.setText(«Red»); Employee2.addContent(LastName2);

Element Age2 = new Element(«Age»); Age2.setText(«30»); Employee2.addContent(Age2);

Element Job2 = new Element(«Job»); Job2.setText(«Analyst»); Employee2.addContent(Job2);

Element Address2 = new Element(«Address»); Address2.setText(«London Road No8900,N78»); Employee2.addContent(Address2);

Element PhoneNumber2 = new Element(«PhoneNumber»); PhoneNumber2.setText(«03-4214-5641»); Employee2.addContent(PhoneNumber2);

////////////////////////////// Employee3 /////////////////////////////// Element Employee3 = new Element(«Employee»); root.addContent(Employee3); Attribute classe3 = new Attribute(«degree»,»E3»); Employee3.setAttribute(classe3);

Element FirstName3 = new Element(«FirstName»); FirstName3.setText(«Eve»); Employee3.addContent(FirstName3);

Element LastName3 = new Element(«LastName»); LastName3.setText(«Green»); Employee3.addContent(LastName3);

Element Age3 = new Element(«Age»); Age3.setText(«29»); Employee3.addContent(Age3);

Element Job3 = new Element(«Job»); Job3.setText(«Developer»); Employee3.addContent(Job3);

Element Address3 = new Element(«Address»); Address3.setText(«London Road No6200,N19»); Employee3.addContent(Address3);

Element PhoneNumber3 = new Element(«PhoneNumber»); PhoneNumber3.setText(«03-5667-9636»); Employee3.addContent(PhoneNumber3);

display(); record(«Task1.xml»); }

static void display() { try { XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); out.output(document, System.out);

Page 6: Extra Tips and Advices by PenTest Magazine Handling XML data …cassiopae.com/wp-content/uploads/2014/03/PenTest_OPEN_03... · 2018. 1. 7. · Extra Tips and Advices by PenTest Magazine

Extra Tips and Advices by PenTest Magazine

73

} catch (java.io.IOException e){} }

static void record(String file) { try { XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); out.output(document, new FileOutputStream(file)); } catch (java.io.IOException e){} }}

Listing 2 shows the generated XML file “Task1”.

Listing 2. The XML file “Task1”

<?xml version=»1.0» encoding=»UTF-8»?><Company> <Employee degree=»E1»> <FirstName>John</FirstName> <LastName>Blue</LastName> <Age>40</Age> <Job>Technical Director</Job> <Address>London Road No5600,N60</Address> <PhoneNumber>03-5327-1100</PhoneNumber> </Employee> <Employee degree=»E2»> <FirstName>Davy</FirstName> <LastName>Red</LastName> <Age>30</Age> <Job>Analyst</Job> <Address>London Road No8900,N78</Address> <PhoneNumber>03-4214-5641</PhoneNumber> </Employee> <Employee degree=»E3»> <FirstName>Eve</FirstName> <LastName>Green</LastName> <Age>29</Age> <Job>Developer</Job> <Address>London Road No6200,N19</Address> <PhoneNumber>03-5667-9636</PhoneNumber> </Employee></Company>

Parsing an XML fileNow we will go through the created XML file in the directory containing our future class JDOM2 shown below in Listing 3.

Parse an XML file back to transform an XML file into a JDOM tree. We will use this builder “SAXBuilder”, based, as the name says on the SAX API.

We will use the same XML file (Task1.xml) that we have already created. We’ll go and retrieve the FirstName, LastName and Job of each employee.

Page 7: Extra Tips and Advices by PenTest Magazine Handling XML data …cassiopae.com/wp-content/uploads/2014/03/PenTest_OPEN_03... · 2018. 1. 7. · Extra Tips and Advices by PenTest Magazine

Extra Tips and Advices by PenTest Magazine

74

Listing 3. The JDOM2 Class

package XMLPackage;import java.io.*;import org.jdom2.*;import org.jdom2.input.*;import java.util.List;import java.util.Iterator;

class JDOM2{ static Document document; static Element root;

public static void main(String[] args) { SAXBuilder sxb = new SAXBuilder(); try { document = sxb.build(new File(«Task1.xml»)); } catch(Exception e){}

root = document.getRootElement();

displayALL(); } static void displayALL() { List listEmployees = root.getChildren(«Employee»);

Iterator i = listEmployees.iterator(); while(i.hasNext()) { Element current = (Element)i.next(); System.out.print(current.getChild(«FirstName»).getText()); System.out.print(‘ ‘); System.out.print(current.getChild(«LastName»).getText()); System.out.print(‘ ‘); System.out.println(current.getChild(«Job»).getText());

} }

}

The following result will be displayed as shown:

• John Blue Technical Director

• Davy Red Analyst

• Eve Green Developer

Page 8: Extra Tips and Advices by PenTest Magazine Handling XML data …cassiopae.com/wp-content/uploads/2014/03/PenTest_OPEN_03... · 2018. 1. 7. · Extra Tips and Advices by PenTest Magazine

Extra Tips and Advices by PenTest Magazine

75

Modify an XML fileWe will modify the content of our Task1.xml file by removing all Element Address of our tree, creating our class JDOM3 present in Listing 4.

Listing 4. The JDOM3 Class

package XMLPackage;import java.io.*;import org.jdom2.*;import org.jdom2.input.*;import java.util.List;import java.util.Iterator;import org.jdom2.output.*;

public class JDOM3{ static Document document; static Element root;

public static void main(String[] args) { try { readFile(«Task1.xml»); deleteElement(«Address»); registerFile(«Task2.xml»); } catch(Exception e){} }

static void readFile(String fichier) throws Exception { SAXBuilder sxb = new SAXBuilder(); document = sxb.build(new File(fichier)); root = document.getRootElement(); }

static void deleteElement(String element) { List listEmployees = root.getChildren(«Employee»); Iterator i = listEmployees.iterator(); while(i.hasNext()) { Element current = (Element)i.next(); if(current.getChild(element)!=null) { current.removeChild(element); current.setName(«employee_modify»); } } } static void registerFile(String file) throws Exception { XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());

Page 9: Extra Tips and Advices by PenTest Magazine Handling XML data …cassiopae.com/wp-content/uploads/2014/03/PenTest_OPEN_03... · 2018. 1. 7. · Extra Tips and Advices by PenTest Magazine

Extra Tips and Advices by PenTest Magazine

76

out.output(document, new FileOutputStream(file)); }}

File “Task2.xml” will be created. Listing 5 shows the generated XML file “Task2”.

Listing 5. The XML file “Task2”

<?xml version=»1.0» encoding=»UTF-8»?><Company> <employee_modify degree=»E1»> <FirstName>John</FirstName> <LastName>Blue</LastName> <Age>40</Age> <Job>Technical Director</Job> <PhoneNumber>03-5327-1100</PhoneNumber> </employee_modify> <employee_modify degree=»E2»> <FirstName>Davy</FirstName> <LastName>Red</LastName> <Age>30</Age> <Job>Analyst</Job> <PhoneNumber>03-4214-5641</PhoneNumber> </employee_modify> <employee_modify degree=»E3»> <FirstName>Eve</FirstName> <LastName>Green</LastName> <Age>29</Age> <Job>Developer</Job> <PhoneNumber>03-5667-9636</PhoneNumber> </employee_modify></Company>

ConclusionYou’ve simply learned how to create an XML file and browse through Java classes.

I gladly wish you a good luck in the use of presented tips I strongly recommend to try out as it will certainly fasten your work.

About the AuthorAzza NAFTI: Graduated in Computer Science and Quality. She works at Cassiopae MEA as Technical Consultant since 2010. Contact: [email protected].