Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;

import java.io.File;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.io.StringWriter;
import java.io.Writer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;

import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Main {
    /**
     * Creates a Document object
     * 
     * @return empty Document object
     * @throws ParserConfigurationException
     */
    public static Document getDocument() throws ParserConfigurationException {

        // Create and return document object
        return getDocumentBuilder().newDocument();
    }

    /**
     * Create a new document object with input element as the root.
     * 
     * @param inputElement
     *            Input Element object
     * @param deep
     *            Include child nodes of this element true/false
     * @return XML Document object
     * @throws IllegalArgumentException
     *             if input is invalid
     * @throws ParserConfigurationException
     */
    public static Document getDocument(final Element inputElement, final boolean deep)
            throws IllegalArgumentException, ParserConfigurationException {
        // Validate input element
        if (inputElement == null) {
            throw new IllegalArgumentException("Input element cannot be null in " + "XmlUtils.getDocument method");
        }

        // Create a new document
        final Document outputDocument = getDocument();

        // Import data from input element and
        // set as root element for output document
        outputDocument.appendChild(outputDocument.importNode(inputElement, deep));

        // return output document
        return outputDocument;
    }

    /**
     * Loads and constructs XML Document object from an input file
     * 
     * @param xmlFile
     *            File object for the xml file
     * @return XML Document object
     * @throws IllegalArgumentException
     *             if input file is null
     * @throws ParserConfigurationException
     * @throws IOException
     * @throws SAXException
     */
    public static Document getDocument(final File xmlFile)
            throws IllegalArgumentException, ParserConfigurationException, SAXException, IOException {
        if (xmlFile == null) {

            throw new IllegalArgumentException("Input xmlFile cannot be null in XmlUtils.getXMLfromfile method");

        }

        // Create document builder
        final DocumentBuilder documentBuilder = getDocumentBuilder();

        // load XML document from file
        final Document resultDocument = documentBuilder.parse(xmlFile);

        // return result document
        return resultDocument;
    }

    /**
     * This method converts input stream as an XML document
     * 
     * @param inputStream
     *            Input Stream
     * @return Content of input stream as an XML Document object
     * @throws IOException
     * @throws SAXException
     * @throws ParserConfigurationException
     * @throws IllegalArgumentException
     *             if input is not valid
     */
    public static Document getDocument(final InputStream inputStream)
            throws SAXException, IOException, ParserConfigurationException {

        // Create document builder
        final DocumentBuilder builder = getDocumentBuilder();

        // Parse input stream as document
        final Document document = builder.parse(inputStream);

        // return output document
        return document;
    }

    public static Document getDocument(final Source source) throws TransformerException, IllegalArgumentException,
            ParserConfigurationException, SAXException, IOException {
        // TODO: check if we can avoid read the source
        // into string.
        final String text = readSource(source);

        return getDocument(text);
    }

    /**
     * Constructs Document object from XML String. This method uses DOMParser to
     * generate a document from a string coded as a well-formed XML. This method
     * should be sparingly used to build XMLs as all XMLs should be attempted to
     * be built using Nodes and elements from scratch. The advantage of this is
     * that all encoding of special characters is automatically taken care of,
     * and is also the recommended way of building XML.
     * 
     * @param inputXMLString
     *            Input XML String
     * @return XML Document object
     * @throws IllegalArgumentException
     *             if input is invalid
     * @throws ParserConfigurationException
     * @throws IOException
     * @throws SAXException
     */
    public static Document getDocument(final String inputXMLString)
            throws IllegalArgumentException, ParserConfigurationException, SAXException, IOException {
        // Validate input XML string
        if (inputXMLString == null) {
            throw new IllegalArgumentException(
                    "Input XML string" + " cannot be null in XmlUtils.getDocument method");
        }

        // Create document builder
        final DocumentBuilder documentBuilder = getDocumentBuilder();

        // Convert input XML as a document object
        final Document resultDocument = documentBuilder.parse(new InputSource(
                new BufferedReader(new InputStreamReader(new ByteArrayInputStream(inputXMLString.getBytes())))));

        // Return result document
        return resultDocument;
    }

    private static DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {
        // TODO: check if we should cache the factory
        // Create a new Document Builder Factory instance
        final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

        // DomSource continue to have issue with default namespace
        // We discontinued usage of DomSource and move to StreamSource
        // As the result, we no longer want and need documentBuilderFactory
        // to be namesapce aware.
        // documentBuilderFactory.setNamespaceAware(true);

        // Create new document builder
        final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        return documentBuilder;
    }

    public static String readSource(final Source sourceToRead) throws TransformerException {
        // Create transformer
        final TransformerFactory tff = TransformerFactory.newInstance();
        final Transformer tf = tff.newTransformer();

        final Writer resultWriter = new StringWriter();

        final Result result = new StreamResult(resultWriter);

        tf.transform(sourceToRead, result);

        return resultWriter.toString();

    }
}