Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;

import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

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

public class Main {
    /**
     * Revalida um objeto Document 
     * @param documento
     * @return Document
     * @throws ParserConfigurationException 
     * @throws IOException 
     * @throws SAXException 
     * @throws TransformerFactoryConfigurationError 
     * @throws TransformerException 
     * @throws TransformerConfigurationException 
     */
    public static Document revalidaDocument(Document documento)
            throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException,
            TransformerException, TransformerFactoryConfigurationError {

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        Document doc = null;
        DocumentBuilder db;
        db = dbf.newDocumentBuilder();
        InputSource is = converterDoc(documento);
        if (is != null) {
            doc = db.parse(is);
        }
        return doc;
    }

    /**
     *  Classe utilitaria para converter Document em InputSource
     * @param documento
     * @return InputSource
     * @throws TransformerFactoryConfigurationError 
     * @throws TransformerException 
     * @throws TransformerConfigurationException 
     */
    private static InputSource converterDoc(Document documento)
            throws TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError {

        Document doc = documento;
        DOMSource source = new DOMSource(doc);
        StringWriter xmlAsWriter = new StringWriter();
        StreamResult result = new StreamResult(xmlAsWriter);
        TransformerFactory.newInstance().newTransformer().transform(source, result);
        StringReader xmlReader = new StringReader(xmlAsWriter.toString());
        InputSource iS = new InputSource(xmlReader);
        return iS;
    }
}