How to calculate size of an Image

If ever you have a doubt on byte code of an image or size of an image, this is how it calculates of it. Every image consists of blocks called pixels. As we all know data is always stored informs of bits. So even pixels will consume some bits of memory. For suppose we have only white and black 0 represents white and 1 represents black. So each of these pixels consume one bit of memory. For example: we have an image of size 100X200 pixels. So total amount of memory in bits is 100*200*1=20,000 bits A byte is equal to 8 bits. So total amount of memory in bytes is 20,000/8=2500 bytes.   Now if you want to have shades of grey , definitely we must increase the bits of memory for a pixel. Say we have given 2 bits of memory for a pixel, we can store 4 shades of grey. 00 represents white 11 represent black 01 represents light grey 10 represent dark grey For example: we have an image of size 100X200 pixels . Total memory =(100*200*2)/8=5000 bytes   The Similar way if you allocate 3 bits per pixel, we can have 8 shades of color. 000 represent White 001 ,010,011,100,101,110 represent various shades of grey 111 represent black Total memory =(100*200*3)/8=7500 bytes From above 3 observations, we can easily derive a formula. n bits can produce 2^n patterns (2 to the nth power) Total no of colors= 2^bits  (2 to the power bits per pixel). 4 shades of colors=2*2 which is 2 bits per pixel 8 shades of  colors=2*2*2    which is 3 bits per pixel 16 shades of  colors=2*2*2*2 which is 4 bits per pixel 32 shades of  colors=2*2*2*2*2  which is 5 bits per pixel 64 shades of  colors=2*2*2*2*2*2  which is 6 bits per pixel For a general image representation, we need 256 colors. So 256 shades of colors=2*2*2*2*2*2*2*2 which is 8 bits per pixel           References: http://en.wikipedia.org/wiki/8-bit_color...

How to make a connection using Proxy in java

This Post will explain you, What is Proxy and  How to connect to a Proxy using a java program. A full example with detailed explanation ensures you to get a complete idea of the proxy concept. Sometimes we may need to connect to an URL or some resource from your application or java program via a proxy. Before showing you the code first let me explain you what is proxy? It’s purpose and how to use it? What is a Proxy Server? Proxy is an intermediate server which connects some set of machines and when one of those machines makes a request, proxy handles that request and sends its IP Address instead of actual machines IP.  This ensures 1. Faster response because the request would have already made my some other machine and so it may remain in cache. Some proxy servers also connects with memcached servers for faster response times. 2.  Administrator can monitor and filter the requests going outside to non intended websites and also he can restricts them. 3. Anonymous and hence more secure obviously.   Full Example of proxy connection in java ProxyConnections.java package com.developprojects.javasnippets; import java.io.IOException; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.Proxy; import java.net.URL; import java.net.URLConnection; public class ProxyConnections { public static void main(String args[]) { try { URL url = new URL( "http://developprojects.com/wp-content/uploads/2013/12/logo_developProjects.png"); Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress( "proxy.Test.com", 4327)); URLConnection connection = url.openConnection(proxy); } catch (MalformedURLException exception) { exception.printStackTrace(); } catch (IOException exception) { exception.printStackTrace(); } } } References: https://www.whatismyip.com/what-is-a-proxy/...

Encryption and Decryption using AES algorithm in Java

AESUtility.java package com.americanexpress.gpzn.services.processservice.galaxy.v1.util; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; public class AESEncryptionDecryption { private static final String CLASS_NAME = "AESEncryptionDecryption"; // 16 bytes or 128 bit Cipher Key.. private static final String CIPHER_KEY = "054cbdad4808e3de"; private static final String AES_ENCRYPTION = "AES"; private static byte[] keyBytes = CIPHER_KEY.getBytes(); public static void main(String args[]) { // Encrypting the Given String DevelopProjects.com using AES algorithm String encryptedString = getEncryptedString("DevelopProjects.com"); System.out.println("Encrypted String generated using the AES :::" + encryptedString); // Decrypting the Encrypted String using AES algorithm String decryptedString = getDecryptStatus(encryptedString); System.out.println("Decrypted String generated using the AES :::" + decryptedString); } /* * This is the encryption method where we will be the using the Cipher key * to encrypt using AES Algorithm and encode using Apache Byte Code . We * will pass the input String appended with time stamp to Cipher to get an * encrypted String and we will it encode it using Apache byte. */ public static String getEncryptedString(String inputString) { String methodName = "getEncryptedString"; System.out.println(methodName + "***inputString::" + inputString); String encodedString = ""; byte[] messageBytes = inputString.getBytes(); SecretKeySpec secretKeySpecification = new SecretKeySpec(keyBytes, AES_ENCRYPTION); Cipher cipher; try { // Code to Encrypt cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpecification); byte[] encryptedBytes = cipher.doFinal(messageBytes); encodedString = Base64.encodeBase64URLSafeString(encryptedBytes); } catch (NoSuchAlgorithmException e) { System.out.println(methodName + " Exception::" + e.getMessage()); } catch (NoSuchPaddingException e) { System.out.println(methodName + " Exception::" + e.getMessage()); } catch (InvalidKeyException e) { System.out.println(methodName + " Exception::" + e.getMessage()); } catch (IllegalBlockSizeException e) { System.out.println("Exception::" + e.getMessage()); } catch (BadPaddingException e) { System.out.println(methodName + " Exception::" + e.getMessage()); } return encodedString; } /* * This is the decryption method where we will be the using the Cipher key * to decrypt using AES Algorithm and decode using Apache Byte Code . We * will be decoding the encoded String which we will get from WEBUI and * decrypt the decoded String */ public static String getDecryptStatus(String encryptedString) { String methodName = "getDecryptStatus"; System.out.println(methodName + " Entry. Given encryptedString input is " + encryptedString); String decryptedString = ""; SecretKeySpec secretKeySpecification = new SecretKeySpec(keyBytes, AES_ENCRYPTION); Cipher cipher; try { // Code to Decrypt cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKeySpecification); byte[] decodedBytes = Base64.decodeBase64(encryptedString); byte[] originalMessage = cipher.doFinal(decodedBytes); decryptedString = new String(originalMessage); } catch (NoSuchAlgorithmException e) { System.out.println(methodName + " Exception::" + e.getMessage()); } catch (NoSuchPaddingException e) { System.out.println(methodName +...

How to copy contents of a database table to another in java

Suppose say abc is a advertising company and it allows its’ visitors to test their advertisements in test environments before making them live. We need to implement such a requirement by copying the the records of one table into the another table under 2 different databases. I have written the java code to copy contents of a database table to another. If ever you have some requirement or need to copy a contents of a table in a database to another, you might find the below example useful. In our below example we have 2 tables CM_ADS_METADATA_TEST and CM_ADS_METADATA under 2 different schemas dptest and dplive schemas. For just a sample, we have copied a complex table with clob data and copied a record from test to live table. We did a select query to fetch a record,copied it to the file and again read that file and inserted the record into the live table. CopyDataIntoDifDBs.java package com.developprojects.main; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import oracle.jdbc.OraclePreparedStatement; import oracle.jdbc.OracleResultSet; import oracle.xdb.XMLType; 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; /** * @author Swarup Reddy * */ public class CopyDataIntoDifDBs { private static TransformerFactory transformerFactory = null; public static void main(String[] args) throws SQLException, IllegalArgumentException, TransformerConfigurationException, TransformerException, IOException { transformerFactory = TransformerFactory.newInstance(); Connection connection = null; PreparedStatement preparedStatement = null; OraclePreparedStatement stmt = null; String sql = null; ResultSet resultSet = null; OracleResultSet orset = null; XMLType poxml; Document podoc; final String clmnSprtr = ",,,"; final String rowSprtr = "###"; String contentToFile; try { System.out.println("Creating Connection.."); Class.forName("oracle.jdbc.driver.OracleDriver"); connection = DriverManager.getConnection("jdbc:oracle:thin:@Localhost:1521:TestDB", "TestUser", "TestPassword"); System.out.println("Creating Connection Successfully"); sql = "SELECT * FROM dptest.CM_ADS_METADATA_TEST WHERE CM_TRMT_ID = 50131"; preparedStatement = connection.prepareStatement(sql); resultSet = preparedStatement.executeQuery(); orset = (OracleResultSet) resultSet; while (orset.next()) { Long CM_TRMT_ID = orset.getLong(1); System.out.println("CM_TRMT_ID " + CM_TRMT_ID.toString()); String ISO_ALPHA_LANG_CD = orset.getString(2).trim(); System.out.println("ISO_ALPHA_LANG_CD " + ISO_ALPHA_LANG_CD); String MKT_CD = orset.getString(3).trim(); System.out.println("MKT_CD " + MKT_CD); String PG_ID = orset.getString(4).trim(); System.out.println("PG_ID " + PG_ID); poxml = XMLType.createXML(orset.getOPAQUE(5)); podoc = (Document) poxml.getDOM(); String TRMT_DTL_DA = getXMLFromDOM(podoc); System.out.println("TRMT_DTL_DA ::" + TRMT_DTL_DA); String PZN_DCSN_ENGINE_ABRV_NM = orset.getString(6).trim(); System.out.println("PZN_DCSN_ENGINE_ABRV_NM ::" + PZN_DCSN_ENGINE_ABRV_NM); poxml = XMLType.createXML(orset.getOPAQUE(7)); podoc = (Document) poxml.getDOM(); String DCSN_ENGINE_CONV_TRMT_DA = getXMLFromDOM(podoc); System.out.println("DCSN_ENGINE_CONV_TRMT_DA ::" + DCSN_ENGINE_CONV_TRMT_DA); String LST_UPDT_USER_ID = orset.getString(8).trim(); System.out.println("LST_UPDT_USER_ID ::" + LST_UPDT_USER_ID); Timestamp LST_UPDT_TS = orset.getTimestamp(9); System.out.println("LST_UPDT_TS :: " + LST_UPDT_TS.toString()); contentToFile...

Encapsulation in Java with Example

Encapsulation is a basic principle of Java. Let me explain you encapsulation with a simple example.After reading the concept completely, I’m pretty sure you will never need to look back again to learn encapsulation concept. Encapsulation ensures to hide the implementation details of a class to the other classes. Basic elements in a class are instance variables and member functions. Let us assume that we have written a class “Car”. The class “car” has some public variables like minSpeed, maxSpeed and noOfTyres instances variables some methods using them to calculate some logic. Now say your friend has written some class called BenzCar and instantiated your Car class and have modified the instance variables of your Car class by mistake by initializing maxSpeed to 0 KMS and minSpeed to 100 KMS which are invalid by logic. So, now you are in serious trouble. Isn’t it? So, to prevent this kind of blunders you must prevent your Car Class’s instance variables initialization restricted by making them private and adding new public methods which should be the only way to initialize the instance variables of your class. Simple Example for understanding Encapsulation Without Encapsulation example: Class Car { Public int minSpeed; Public int maxSpeed; Public int noOfTyres; Public int OptimimSpeed(maxSpeed) { Return (maxSpeed)/2; } } package com.developprojects.withOutEncapsulation; public class BenzCar { public static void main(String args[]) { Car car = new Car(); car.minSpeed = 100; car.maxSpeed = 0; int optimumSpeed = car.optimimSpeed(car.maxSpeed); System.out .println("OptimimSpeed of Benz Car with out encapsulation ::kms " + optimumSpeed); } } How to implement Encapsulation in Java: Encapsulation is essential key feature of Object Oriented Programming. We should follow some simple rules to implement encapsulation in java. They are: Instance variable needs to safe guarded from other classes by making them private or protected access modifiers Make methods public and instance variables can only be accessed directly using these public methods. The naming conventions of these methods should be like set<VariableName> and get<VariableName> With Encapsulation Example: package com.developprojects.encapsulation; public class Car { private int minSpeed; private int maxSpeed; private int noOfTyres; /** * @return the minSpeed */ public int getMinSpeed() { return minSpeed; } /** * @param minSpeed * the minSpeed to set */ public void setMinSpeed(int minSpeed) { this.minSpeed = minSpeed; } /** * @return the maxSpeed */ public int getMaxSpeed() { return maxSpeed; } /** * @param maxSpeed * the maxSpeed to set */ public...

Introduction: Basic understanding of XPath and its related concepts

Introduction to XPath: Full form of XPath is XML Path. It is a query language designed to traverse through an xml document and select the required nodes using XPath Expressions and XPath functions, which I will discuss in the next chapters. XPath is a World Wide Web consortium (w3c) recommendation and the latest specification is Xpath 2.0. This specification is designed to be referenced normatively from other specifications defining a host language for it. It is not intended to be implemented outside a host language. The implementation ability of this specification has been tested in the context of its normative inclusion in host languages defined by the XQuery and XSLT. <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <dev:Corporation xmlns:dev="http://developprojects.com"> <dev:Organization> <dev:website category="technical"> <dev:name>developprojects.com</dev:name> <dev:topic>XPath Tutorial</dev:topic> <dev:author>Viswa Tej Swarup Reddy</dev:author> <dev:price>FREE</dev:price> </dev:website> </dev:Organization> </dev:Corporation>   Regular XPath terminology: The common XPath vocabularies you must know before proceeding further are: Nodes Atomic Values Items Nodes: Every XML document is a tree of nodes. Various types of nodes are Tag nodes Element nodes Attribute nodes Text nodes In the above XML example, < Corporation> is the root node. <Organization> tag is a node. <topic> XPath Tutorial</topic> is an element node. category=”technical” is an attribute node. XPath Tutorial is a text node. And in turn these nodes can be categorized internally based on their relationships in between. Some of them are namely Ancestor:  Ancestor nodes are parent nodes, if the parent nodes have parents, then we have to include their names too and it follows till the root node. In the above example the ancestor nodes of <author> node are <website>,<Organization>, <Corporation>.  Descendent: Descendent nodes are Child nodes, if the child nodes have children, then we have to include their names too and if follows till the lowest node is reached. In the above example the descendent nodes of <Organization> node are <website>, <name>, <topic>, <author>, <price>. Parent: Parent nodes are immediate parent of the selected node or attribute. In the above example <website> is the parent node for <name>, <topic>, <author>, <price>. Child:  Child nodes are the immediate child nodes of the selected nodes. In the above example, child nodes for <website> are <name>, <topic>, <author>, <price>. Siblings: The nodes which share a common parent are called siblings. In the above example, <name>, <topic>, <author>, <price> are siblings who share a common parent ,<website>. Text: Text nodes are just the values of the individual nodes. ...

How to convert a XML file into a csv file using java?

We Used a property file to get xpath expressions of the corresponding mapped elements in XML file. If you got an doubt regarding property file, you can go throw my tutorial about how to read a property file. Here I converted an XML file into a Document Object and I have used the configured Xpath Expressions in the property file to retrieve the values from XML document. XMLToCSVMappings.java package com.developprojects.java; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.TransformerFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; public class XMLToCSVMappings { private static XPathFactory xPathFactory = null; private static DocumentBuilderFactory domFactory = null; public static void main(String args[]) { domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); xPathFactory = XPathFactory.newInstance(); TransformerFactory.newInstance(); ReadXML(); } public static void ReadXML() { System.out.println("In ReadXML method"); File xmlFile = new File( "D:/Develop Projects Workspace/java/resources/sample.xml"); try { InputStream fis = new FileInputStream(xmlFile); if (fis != null) { Document xmlDoc = getDocFromXMLString(fis); HashMap<String, String> propertiesKeypair = readPropertyFile(); FileWriter writer = new FileWriter("c:\\SampleXMLtoCSVFile.csv"); writer.append("Key"); writer.append(','); writer.append("Value"); writer.append('\n'); for (Map.Entry<String, String> entry : propertiesKeypair .entrySet()) { System.out.println("Key : " + entry.getKey() + "Xpath value is::" + getElementValue(entry.getValue(), xmlDoc)); writer.append(entry.getKey()); writer.append(','); writer.append(getElementValue(entry.getValue(), xmlDoc)); writer.append('\n'); } writer.flush(); writer.close(); System.out .println("ResultMap Updated. CSV File is being generated..."); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public static Document getDocFromXMLString(InputStream xml) throws Exception { DocumentBuilder builder; Document doc; try { builder = domFactory.newDocumentBuilder(); doc = builder.parse(xml); } catch (Exception exception) { throw exception; } finally { } return doc; } public static String getElementValue(final String xpathExpression, final Document doc) { String textValue = null; try { XPath xpath = xPathFactory.newXPath(); textValue = xpath.evaluate(xpathExpression, doc); } catch (final XPathExpressionException xpathException) { xpathException.printStackTrace(); } return textValue; } public static HashMap<String, String> readPropertyFile() { System.out.println("In readPropertyFile method"); Properties prop = new Properties(); InputStream input; HashMap<String, String> Propvals = new HashMap<String, String>(); try { input = XMLToCSVMappings.class .getResourceAsStream("JustProperties.properties"); System.out.println("before load"); prop.load(input); System.out.println("Property File Loaded Succesfully"); Set<String> propertyNames = prop.stringPropertyNames(); for (String Property : propertyNames) { Propvals.put(Property, prop.getProperty(Property)); } System.out.println("HashMap generated::" + Propvals); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return Propvals; } } sample.xml <?xml version="1.0" encoding="UTF-8" ?> <channel> <title>DEVELOP PROJECTS</title> <link>http://www.developprojects.com</link> <Authur>Swarup Reddy Kovvuri</Authur> <language>Java</language> </channel> JustProperties.properties Author //Authur Website //link Language //language...

How to Read a Property File into Hash Map in Java

Property file is a typical plain java file with key and value pairs. It will have an extension of .properties.  Usually system level configurations or server level configuration. Each line typically refers to a configurable parameter. Format looks like key=value . Key being the Property name and value being the key’s Value. This is the simple Properties file  used in our sample program. AuthorInfo.properties Author=Viswa Teja Swarup Reddy Website=www.DevelopProjects.com Language=English Example Program to Read a Property file in Java package com.developprojects.java; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Properties; import java.util.Set; public class ReadPropertyFile { public static void main(String args[]) { readPropertyFile(); } public static void readPropertyFile() { System.out.println("In readPropertyFile method"); Properties prop = new Properties(); InputStream input; HashMap<String, String> propvals = new HashMap<String, String>(); try { input = ReadPropertyFile.class .getResourceAsStream("/AuthorInfo.properties"); prop.load(input); System.out.println("Property File Loaded Succesfully"); Set<String> propertyNames = prop.stringPropertyNames(); for (String Property : propertyNames) { System.out.println(Property + ":" + prop.getProperty(Property)); propvals.put(Property, prop.getProperty(Property)); } System.out.println("HashMap generated::" + propvals); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } output: In readPropertyFile method Property File Loaded Succesfully Language:English Website:www.DevelopProjects.com Author:Viswa Teja Swarup Reddy HashMap generated::{Website=www.DevelopProjects.com, Author=Viswa Teja Swarup Reddy, Language=English} Explanation: Properties prop = new Properties() creates a new Properties Object. HashMap<String, String> propvals = new HashMap<String, String>() creates a propvals HashMap Object. readPropertyFile() is the custom function which we have written to read the property file in the class path. The method getResourceAsStream returns an InputStream. By calling this method with class loader, it will search the resource in the class path. Load method will read the key value pairs from the given input stream. The rest of the program is just iterating the elements in property file. stringPropertyNames() returns a Set containing all the property keys. We iterated the set to get value of the corresponding key using the method, getProperty(<propertyName>). We are just storing the key value pairs just in the same order into our HashMap. In the next Program, I showed you how to write into a property...

How to Create XML Document or String Object in Java Dynamically

Explanation: This sample example will construct a XML / DOM / Document Object in java. We will create new instance of DocumentBuilderFactory using DocumentBuilderFactory.newInstance() method. The newDocumentBuilder will create new instance of DocumentBuilder with configured parameters. The newDocument() method will create new instance of Document Object to Build a DOM Tree.Element is an interface from org.w3c.dom package which extends from Node interface. Elements represents an element from an XML document.These Elements may have attributes, Nodes. This interface provides method which can help us build, read and edit a complex Dom Tree. This is the XML which we wish to generate dynamically using Java Document Object Model (DOM)   <?xml version="1.0" encoding="UTF-8" standalone="no"?> <DevelopProjects rootAttr="true"> <FirstChild flag="1"> This is the First Child in DevelopProjects.com <FirstChildNode flag="1.1"> This is the Child Element of FirstChild <FirstSubChildNode flag="1.1.1">This is the Sub Child Element of FirstChild</FirstSubChildNode> </FirstChildNode> </FirstChild> <SecondChild flag="2">This is the Second Child in DevelopProjects.com</SecondChild> <ThirdChild flag="3" /> <FourthChild flag="4" /> <FifthChild flag="5" /> <SixthChild flag="6" /> <SeventhChild flag="7" /> <EigthChild flag="8" /> <NinethChild flag="9" /> <TenthElement>This is how I'm 10 Now</TenthElement> </DevelopProjects> Sample Java Program to Create XML Object   package com.developprojects.java; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; 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.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; public class CreateXML { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(generateXML()); } public static String generateXML(){ System.out.println("generateXML() Entry"); Document doc=null; StringWriter writer = new StringWriter(); try { final String FLAG = "flag"; DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); doc = docBuilder.newDocument(); Element rootElement = doc.createElement("DevelopProjects"); doc.appendChild(rootElement); Attr attr = doc.createAttribute("rootAttr"); attr.setValue("true"); rootElement.setAttributeNode(attr); Element firstChildNode = doc.createElement("FirstChildNode"); attr = doc.createAttribute(FLAG); attr.setValue("1.1"); firstChildNode.setAttributeNode(attr); firstChildNode.appendChild(doc.createTextNode("This is the Child Element of FirstChild")); Element firstSubChildNode = doc.createElement("FirstSubChildNode"); attr = doc.createAttribute(FLAG); attr.setValue("1.1.1"); firstSubChildNode.setAttributeNode(attr); firstSubChildNode.appendChild(doc.createTextNode("This is the Sub Child Element of FirstChild")); Element firstChildElement = doc.createElement("FirstChild"); attr = doc.createAttribute(FLAG); attr.setValue("1"); firstChildElement.setAttributeNode(attr); firstChildElement.appendChild(doc.createTextNode("This is the First Child in DevelopProjects.com")); firstChildElement.appendChild(firstChildNode); firstChildNode.appendChild(firstSubChildNode); rootElement.appendChild(firstChildElement); Element secondChildElement = doc.createElement("SecondChild"); attr = doc.createAttribute(FLAG); attr.setValue("2"); secondChildElement.setAttributeNode(attr); secondChildElement.appendChild(doc.createTextNode("This is the Second Child in DevelopProjects.com")); rootElement.appendChild(secondChildElement); Element thirdChildElement = doc.createElement("ThirdChild"); attr = doc.createAttribute(FLAG); attr.setValue("3"); thirdChildElement.setAttributeNode(attr); rootElement.appendChild(thirdChildElement); Element fourthChildElement = doc.createElement("FourthChild"); attr = doc.createAttribute(FLAG); attr.setValue("4"); fourthChildElement.setAttributeNode(attr); rootElement.appendChild(fourthChildElement); Element fifthChildElement = doc.createElement("FifthChild"); attr = doc.createAttribute(FLAG); attr.setValue("5"); fifthChildElement.setAttributeNode(attr); rootElement.appendChild(fifthChildElement); Element sixthChildElement = doc.createElement("SixthChild"); attr = doc.createAttribute(FLAG); attr.setValue("6"); sixthChildElement.setAttributeNode(attr); rootElement.appendChild(sixthChildElement); Element seventhChildElement = doc.createElement("SeventhChild"); attr = doc.createAttribute(FLAG); attr.setValue("7"); seventhChildElement.setAttributeNode(attr); rootElement.appendChild(seventhChildElement); Element EightChildElement =...

How to Convert a Document DOM Object to XML String Object

Explanation: Document is an interface in org.w3c.dom package which extends Node Interface. This example is all about converting a document object to String Object which will be a valid XML. The method getXMLFromDOM() will take Document object as argument. So, we have created a document object using the method createDocument(). This createDocument() method is inturn clearly explained in my post How to Create or generate a Document Object. In my another post, you can find a sample program to Convert a XML String to DOM / Document object. In the current example in the method getXMLFromDOM(), DOMSource acts as a holder for a transformation Source tree in the form of a Document Object Model (DOM) tree. It implements the Source interface. StreamResult acts as an holder for a transformation result, which may be XML, plain Text, HTML, or some other form of markup. It is a class in javax.xml.transform.stream package which implements Result interface. Transformer is an abstract class which can be instantiated with transformerFactory.newTransformer(). It is a class in javax.xml.transform package whose instance method transform() will transform the xml Dom source to Stream result. The getWriter() method of StreamResult will return a characterStream of return type Writer which will be converted to String Object using the toString() method.    Java example to Convert a DOM / Document Object to XML String package com.developprojects.java; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; 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.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; public class DocumentToString { private static TransformerFactory transformerFactory = null; public static void main(String[] args) { transformerFactory = TransformerFactory.newInstance(); String XML = new String(); Document sampleDoc = createDocument(); try { XML = getXMLFromDOM(sampleDoc); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } System.out.println("String Generated from Document is " + XML); } // This method will convert a Document to String Object public static String getXMLFromDOM(Document requestXMLDoc) throws IllegalArgumentException, TransformerConfigurationException, TransformerException { if (requestXMLDoc == null) { System.out.println("Supplied document object is null"); throw new IllegalArgumentException("Document cannot be null"); } DOMSource source = new DOMSource(requestXMLDoc); StreamResult result = new StreamResult(new StringWriter()); Transformer transformer; try { transformer = transformerFactory.newTransformer(); transformer.transform(source, result); } catch (TransformerConfigurationException tConfigurationException) { System.out.println("TransformerConfigurationException::" + tConfigurationException); } catch (TransformerException transformerException) { System.out.println("TransformerConfigurationException::" + transformerException); } String returnString = result.getWriter().toString(); return returnString; } // This method will create a Document Object...