Tuesday, July 26, 2011

XML Creation On the Fly - Java Source Code

In my earlier article, I have shown you how to create the XML file using java APIs. Here I will show you how to do the same however without actually creating files. Here I will use the String buffer to hold the XML content that can be used to do further processing if needed.
 @Credit: Sumeet Chakraborty
Java API being used here is same as one earlier.
Another API being used:

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.Document;
import org.w3c.dom.Element;

public class XMLCreation {

      public static void main(String args[]) {

            XMLCreation xmlCreate = new XMLCreation();
            xmlCreate.createXML();
      }

      private void createXML() {

            String customerName = "Ramesh";
            String customerAddress = "Delhi";

            DocumentBuilder domBuilder = null;
            try {
                  DocumentBuilderFactory domFactory = DocumentBuilderFactory
                              .newInstance();
                  domBuilder = domFactory.newDocumentBuilder();
            } catch (ParserConfigurationException pcEx) {
                  System.out
                              .println("ParserConfiguration  "
                                          + pcEx.getMessage());
            } catch (Exception e) {
                  System.out
                              .println("Exception Occured"
                                          + e.getMessage());
            }
            Document newDoc = domBuilder.newDocument();

            // Root element
            Element rootElement = newDoc.createElement("CustomerInformation");
            newDoc.appendChild(rootElement);

            // Creating element containing value Name
            Element curElement = newDoc.createElement("Name");
            curElement.appendChild(newDoc.createTextNode(customerName));
            rootElement.appendChild(curElement);

            // Creating element signifies address
            Element keyElement = newDoc.createElement("Address");
            keyElement.appendChild(newDoc.createTextNode(customerAddress));
            rootElement.appendChild(keyElement);

            DOMSource sourceInt = new DOMSource(newDoc);

           
            //This will hold the XML content being built later on
//This is the difference where we are not creating file
//Instead, we are using StringWriter to hold the XML content
            StringWriter stew = new StringWriter();

            // File stew = new File("C:/sampleXMLfile.xml");

            StreamResult resultInt = new StreamResult(stew);

            TransformerFactory tFactoryInt = TransformerFactory.newInstance();
            Transformer transformerInt = null;

            try {
                  transformerInt = tFactoryInt.newTransformer();
                 
                  //this is where actually transformation happens and creates the XML
                 
                  transformerInt.transform(sourceInt, resultInt);
                  System.out.println("XML created as " + stew.getBuffer().toString());
            } catch (TransformerException tEx) {
                  System.out
                              .println("TransformerException Occured  "
                                          + tEx.getMessage());
            } catch (Exception e) {
                  System.out
                              .println("Exception Occured                                           + e.getMessage());
            }

      }
}

Create XML File using Java (Source Code)

Hi All,
After so much on the XML front in my blog, I am going to put here the java source code which will create XML file with some dummy data. Guess, it should be the first blog of XML. Nevertheless,  better late than never.

Simple Java Code to create one XML file:
API used:

import java.io.File;

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.Document;
import org.w3c.dom.Element;

public class XMLCreation {

      public static void main(String args[]) {

            XMLCreation xmlCreate = new XMLCreation();
            xmlCreate.createXML();
      }

      private void createXML() {

            String customerName = "Ramesh";
            String customerAddress = "Delhi";

            DocumentBuilder domBuilder = null;
            try {
                  DocumentBuilderFactory domFactory = DocumentBuilderFactory
                              .newInstance();
                  domBuilder = domFactory.newDocumentBuilder();
            } catch (ParserConfigurationException pcEx) {
                  System.out
                              .println("ParserConfiguration Exception "
                                          + pcEx.getMessage());
            } catch (Exception e) {
                  System.out
                              .println("Exception Occured "
                                          + e.getMessage());
            }
            Document newDoc = domBuilder.newDocument();

            // Root element
            Element rootElement = newDoc.createElement("CustomerInformation");
            newDoc.appendChild(rootElement);

            // Creating element containing value of Name
            Element curElement = newDoc.createElement("Name");
            curElement.appendChild(newDoc.createTextNode(customerName));
            rootElement.appendChild(curElement);

            // Creating element signifies address
            keyElement.appendChild(newDoc.createTextNode(customerAddress));
            rootElement.appendChild(keyElement);

            DOMSource sourceInt = new DOMSource(newDoc);


            File stew = new File("C:/sampleXMLfile.xml");

            StreamResult resultInt = new StreamResult(stew);

            TransformerFactory tFactoryInt = TransformerFactory.newInstance();
            Transformer transformerInt = null;

            try {
                  transformerInt = tFactoryInt.newTransformer();
            /* Transformation done here, which actually does the file creation*/   
transformerInt.transform(sourceInt, resultInt);
            } catch (TransformerException tEx) {
                  System.out
                              .println("TransformerException Occured "
                                          + tEx.getMessage());
            } catch (Exception e) {
                  System.out
                              .println("Exception Occured"
                                          + e.getMessage());
            }

      }
}

Difference between SAX and DOM Parsing in XML

There are very useful differences between SAX and DOM parsing. SAX Parser is the one which is developed to run the java programs especially. Primarily, if we want to extract the data from a xml file once, we should move to SAX, which is one time top to bottom read approach and if we want ot randomly pick the data in an xml file then the tree reperesentation of DOM model is to be put into use.

If we need to find a node and doesnt need to insert or delete we can go with SAX itself otherwise DOM provided we have more memory.

Few top level differences

SAX:
1. Parses node by node
2. Doesnt store the XML in memory
3. We cant insert or delete a node
4. Top to bottom traversing

DOM
1. Stores the entire XML document into memory before processing
2. Occupies more memory
3. We can insert or delete nodes
4. Traverse in any direction.

Source: obviously internet as you all know.

Download a file from ftp server – Java Source Code

In my earlier article, I have shown you how to upload a document into the ftp server. Here is the code to download a file from ftp server.

Jars required: commons-net-1.4.1.jar
import java.io.FileOutputStream;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

public class DownloadFromFtp {

      public static void main(String[] args) {
            DownloadFromFtp downloadFTP = new DownloadFromFtp();
            downloadFTP.downloadFromFTP();
      }

      private void downloadFromFTP() {
            try {

                  FTPClient ftpClient = new FTPClient();

                  // This is the file name to be downloaded
                  String fileName = "demo.txt";
                  // This is the ftp server details to be connected
                  ftpClient.connect("ftpserverlocation");
                  int replyCode = ftpClient.getReplyCode();
                  if (!FTPReply.isPositiveCompletion(replyCode)) {
                        System.out.println("Server DOwn");
                  }
                  // Credentials to login into the ftp server.
                  boolean login = ftpClient.login("username", "password");

                  // A particular directory where the file exists
                  boolean changeWorkingDirectory = ftpClient
                              .changeWorkingDirectory("ftpdirectory");

                  boolean setFileType = ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

                  ftpClient.enterLocalPassiveMode();

                  OutputStream data = (OutputStream) new FileOutputStream(fileName);

                  // Actually retrieving the file
                  ftpClient.retrieveFile(fileName, data);

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

}

Java Source Code to Upload a File into FTP Server

Here is the simple java code which will help uploading a file into a destination ftp server.

@Credit: Parvesh Mehla

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import javax.swing.JOptionPane;

public class UploadIntoFTP {

      UploadIntoFTP() {

      }

      private void doUpload() {

            // This is exact location of the file in the local server/machine
            // Source Location of the file
            File fileSource = new File("C:/demo.txt");

            // this is the file name only; not the lcoation
            String fileName = fileSource.getName();

            // Username and password to enter in to the ftp server
            String userName = "username";
            String password = "password";

            // this is the ftpserver details upto the folder in which file needs to
            // be uploaded
            String ftpServer = "ftpserverlocation/folderlocation";

            System.out.println(fileName);

            // Constructing the string buffer
            StringBuffer sb = new StringBuffer("ftp://");
            // check for authentication else assume its anonymous access.

            sb.append(userName);
            sb.append(':');
            sb.append(password);
            sb.append('@');

            sb.append(ftpServer);
            sb.append('/');
            sb.append(fileName);

            /*
             * UPloading mode type ==> a=ASCII mode, i=image (binary) mode, d= file
             * directory listing
             */
            sb.append(";type=a");

            System.out.println(sb.toString());

            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            try {

                  URL url = new URL(sb.toString());
                  System.out.println(url);
                  URLConnection urlc = url.openConnection();
                  bos = new BufferedOutputStream(urlc.getOutputStream());
                  bis = new BufferedInputStream(new FileInputStream(fileSource));

                  int i;

                  // read byte by byte until end of stream
                  while ((i = bis.read()) != -1) {
                        bos.write(i);
                  }
                  JOptionPane.showMessageDialog(null, fileName + " is uploaded",
                              "Press OK", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
                  e.printStackTrace();
            } finally {

                  if (bis != null)
                        try {
                              bis.close();
                        } catch (IOException ioe) {
                              ioe.printStackTrace();
                              System.out.println("IO exception after if bis " + ioe);
                        }
                  if (bos != null)
                        try {
                              bos.close();
                        } catch (IOException ioe) {
                              ioe.printStackTrace();
                              System.out.println("IO exception after if " + ioe);
                        }
            }
      }

      public static void main(String args[]) {
            UploadIntoFTP uploadIntoftp = new UploadIntoFTP();
            uploadIntoftp.doUpload();
      }
}

Total Pageviews