Showing posts with label XML Parser. Show all posts
Showing posts with label XML Parser. Show all posts

Sunday 18 July 2021

Dozer Mapping

Dozer is a Java Bean to Java Bean mapper that recursively copies data from one object to another. Typically, these Java Beans will be of different complex types.


Dozer supports simple property mapping, complex type mapping, bi-directional mapping, implicit-explicit mapping, as well as recursive mapping. This includes mapping collection attributes that also need mapping at the element level.


We can see the implementation of the dozer in this post. This way is not recommended since the update is not coming from the developer's side.


Here the Mapping is very easy.


Just add the maven dependency. then identify the source and destination classes. The add the mapping in the source class then this will automatically convert the object.


Consider the below example.


Maven dependency.


             <dependency>

<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
<version>5.5.1</version>

</dependency>


Source Object:


package com.greet.user;


import org.dozer.Mapping;


public class MessagePojo {

@Mapping("welcomeMessage")

String message;


public String getMessage() {

return message;

}


public void setMessage(String message) {

this.message = message;

}


public MessagePojo() {

}


}



Destination Object:


package com.greet.user;


public class GreetingPojo {

String welcomeMessage;

public GreetingPojo() {

super();

// TODO Auto-generated constructor stub

}


public GreetingPojo(String welcomeMessage, String greetings) {

super();

this.welcomeMessage = welcomeMessage;

this.greetings = greetings;

}


public String getWelcomeMessage() {

return welcomeMessage;

}


public void setWelcomeMessage(String welcomeMessage) {

this.welcomeMessage = welcomeMessage;

}


public String getGreetings() {

return greetings;

}


public void setGreetings(String greetings) {

this.greetings = greetings;

}


String greetings;


}


Here the Message Object in Message Pojo needs to be mapped to the GreetingPojo welcomeMessage. Hence I have used the mapping in the message POJO with the field name.


Then In the class where we are converting needs the below code.


Mapping:


MessagePojo msg = new MessagePojo();

msg.setMessage("Greetings from Spring Boot!");

GreetingPojo targetObj = new DozerBeanMapper().map(msg, GreetingPojo.class);


where msg is the source object and GreetingPojo class. This converts the messagePojo to the GreetigPojo. 


Happy Learning!!!!

Monday 5 July 2021

Create Xml Using the Stax Processor

StAX is a standard XML processing API that allows you to stream XML data from and to your application.


This API is better than the DOM parser in the case of Performance. It does not load the whole document to the memory like the DOM parser. SAX is a push API where else Stax is the pull API. Using the SAX for the creation of the document is not recommended.


The Below code is used to generate the below XML.



package com.searchendeca.main;

import java.io.StringWriter;


import javax.xml.stream.XMLOutputFactory;

import javax.xml.stream.XMLStreamException;

import javax.xml.stream.XMLStreamWriter;


public class StaxParserMain {


private void createStudentElements(XMLStreamWriter xmlStreamWriter) {

try {

createStreamWriter("FirstName", "Syed", xmlStreamWriter);

createStreamWriter("LastName", "Ghouse", xmlStreamWriter);

createStreamWriter("City", "Salem", xmlStreamWriter);

} catch (XMLStreamException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

private void createStreamWriter(String key, Object value, XMLStreamWriter xmlStreamWriter)

throws XMLStreamException {

if (value != null && value != "") {

if (value instanceof String) {

xmlStreamWriter.writeStartElement(key);

xmlStreamWriter.writeCharacters((String) value);

xmlStreamWriter.writeEndElement();

}

} else {

xmlStreamWriter.writeEmptyElement(key);

}


}


public static void main(String args[]) {

StringWriter stringwriter = new StringWriter();

XMLOutputFactory xmloutputfactory = XMLOutputFactory.newInstance();

StaxParserMain stax = new StaxParserMain();

try {

XMLStreamWriter xmlStreamWriter = xmloutputfactory.createXMLStreamWriter(stringwriter);

xmlStreamWriter.writeStartDocument();

xmlStreamWriter.writeStartElement("Student");

stax.createStudentElements(xmlStreamWriter);

xmlStreamWriter.writeEndElement();

xmlStreamWriter.writeEndDocument();

xmlStreamWriter.flush();

xmlStreamWriter.close();

String xmlString= stringwriter.getBuffer().toString();

System.out.println(xmlString);


} catch (XMLStreamException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}


}


The whole project can be found in Github here.


Happy Learning !!!

Create XML Using DOM Parser in JAVA

The Document Object Model (DOM) is an official recommendation of the World Wide Web Consortium (W3C). DOM reads the entire document and will be useful in case of the size of the XML is small. Performance-wise this is slow compared to other parsers since it loads the entire document. We can Perform the Operations using the DOM API.Its Stays in Tree Structure.


We can construct the Following XML using the DOM Parser.



We need to understand the following to get started.

The Node interface is the primary datatype for the entire Document Object Model. It represents a single node in the document tree. 

The Element interface represents an element in an HTML or XML document. Elements may have attributes associated with them; since the Element interface inherits from Node, the generic Node interface attribute attributes may be used to retrieve the set of all attributes for an element. 

In order to use the dom parser include the following dependency in the maven.

 <dependency>

   <groupId>xml-apis</groupId>

   <artifactId>xml-apis</artifactId>

   <version>1.4.01</version>

</dependency>


In the case of the Spring boot project, this should be included as part of the starter package itself I guess.


package com.searchendeca.main;

import java.io.StringWriter;


import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import javax.xml.transform.OutputKeys;

import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerConfigurationException;

import javax.xml.transform.TransformerException;

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;


public class DomParserMain {


private Element createStudentElement(Document doc, Element rootElement) {

rootElement.appendChild(createElements(doc, "FirstName", "Syed"));

rootElement.appendChild(createElements(doc, "LastName", "Ghouse"));

rootElement.appendChild(createElements(doc, "City", "Salem"));

return rootElement;

}


private Node createElements(Document doc, String name, String value) {

Element node = doc.createElement(name);

if (value != null && !value.isEmpty()) {

node.appendChild((doc.createTextNode(value)));

}

return node;

}


public static void main(String args[]) throws ParserConfigurationException {


DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder dBuilder;

String sampleXml;

DomParserMain domParser = new DomParserMain();

dBuilder = dbFactory.newDocumentBuilder();

Document doc = dBuilder.newDocument();

Element rootElement = doc.createElement("Student");

doc.appendChild(rootElement);

rootElement = domParser.createStudentElement(doc, rootElement);

TransformerFactory factory = TransformerFactory.newInstance();

Transformer transformer = null;

try {

transformer = factory.newTransformer();

StringWriter writer = new StringWriter();

try {

transformer.setOutputProperty(OutputKeys.INDENT, "yes");

transformer.transform(new DOMSource(doc), new StreamResult(writer));

sampleXml = writer.getBuffer().toString();

System.out.println(sampleXml);

} catch (TransformerException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

} catch (TransformerConfigurationException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}


}



The above code creates the XML in the desired output.


The Whole Project can be found in the Github link here.


Happy Learning!!!!!