Example usage for org.dom4j.io OutputFormat createPrettyPrint

List of usage examples for org.dom4j.io OutputFormat createPrettyPrint

Introduction

In this page you can find the example usage for org.dom4j.io OutputFormat createPrettyPrint.

Prototype

public static OutputFormat createPrettyPrint() 

Source Link

Document

A static helper method to create the default pretty printing format.

Usage

From source file:org.opencms.configuration.CmsConfigurationManager.java

License:Open Source License

/**
 * Writes the XML configuration for the provided configuration instance.<p>
 * /*  w  w w .  j av  a  2s . c  om*/
 * @param clazz the configuration class to write the XML for
 * @throws IOException in case of I/O errors while writing
 * @throws CmsConfigurationException if the given class is not a valid configuration class
 */
public void writeConfiguration(Class<?> clazz) throws IOException, CmsConfigurationException {

    I_CmsXmlConfiguration configuration = getConfiguration(clazz);
    if (configuration == null) {
        throw new CmsConfigurationException(
                Messages.get().container(Messages.ERR_CONFIG_WITH_UNKNOWN_CLASS_1, clazz.getName()));
    }

    // generate the file URL for the XML input
    File file = new File(m_baseFolder, configuration.getXmlFileName());
    if (LOG.isDebugEnabled()) {
        LOG.debug(Messages.get().getBundle().key(Messages.LOG_WRITE_CONFIG_XMLFILE_1, file.getAbsolutePath()));
    }

    // generate the XML document 
    Document config = generateXml(configuration);

    // output the document
    XMLWriter writer = null;
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setIndentSize(4);
    format.setTrimText(false);
    format.setEncoding(CmsEncoder.ENCODING_UTF_8);

    try {
        OutputStream out = new FileOutputStream(file);
        writer = new XMLWriter(out, format);
        writer.write(config);
        writer.flush();
    } finally {
        if (writer != null) {
            writer.close();
        }
    }

    if (LOG.isInfoEnabled()) {
        LOG.info(Messages.get().getBundle().key(Messages.LOG_WRITE_CONFIG_SUCCESS_2, file.getAbsolutePath(),
                configuration.getClass().getName()));
    }
}

From source file:org.opencms.util.ant.CmsXmlUtils.java

License:Open Source License

/**
 * Marshals (writes) an XML document into an output stream using XML pretty-print formatting.<p>
 * //from w ww.j  a v a  2 s. c o  m
 * @param document the XML document to marshal
 * @param out the output stream to write to
 * @param encoding the encoding to use
 * @return the output stream with the xml content
 * @throws Exception if something goes wrong
 */
public static OutputStream marshal(Document document, OutputStream out, String encoding) throws Exception {

    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(encoding);

    XMLWriter writer = new XMLWriter(out, format);
    writer.setEscapeText(false);

    writer.write(document);
    writer.close();

    return out;
}

From source file:org.opencms.util.ant.CmsXmlUtils.java

License:Open Source License

/**
 * Marshals (writes) an XML node into an output stream using XML pretty-print formatting.<p>
 * /*from  w  w  w  .jav a  2  s .c o  m*/
 * @param node the XML node to marshal
 * @param encoding the encoding to use
 * 
 * @return the string with the xml content
 * 
 * @throws Exception if something goes wrong
 */
public static String marshal(Node node, String encoding) throws Exception {

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(encoding);
    format.setSuppressDeclaration(true);

    XMLWriter writer = new XMLWriter(out, format);
    writer.setEscapeText(false);

    writer.write(node);
    writer.close();
    return new String(out.toByteArray());
}

From source file:org.opencms.xml.CmsXmlUtils.java

License:Open Source License

/**
 * Marshals (writes) an XML document into an output stream using XML pretty-print formatting.<p>
 * /* w w  w.  j a v  a 2s  .c o m*/
 * @param document the XML document to marshal
 * @param out the output stream to write to
 * @param encoding the encoding to use
 * @return the output stream with the xml content
 * @throws CmsXmlException if something goes wrong
 */
public static OutputStream marshal(Document document, OutputStream out, String encoding)
        throws CmsXmlException {

    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(encoding);

        XMLWriter writer = new XMLWriter(out, format);
        writer.setEscapeText(false);

        writer.write(document);
        writer.close();

    } catch (Exception e) {
        throw new CmsXmlException(Messages.get().container(Messages.ERR_MARSHALLING_XML_DOC_0), e);
    }

    return out;
}

From source file:org.opencms.xml.CmsXmlUtils.java

License:Open Source License

/**
 * Marshals (writes) an XML node into an output stream using XML pretty-print formatting.<p>
 * /* w ww.  ja  v  a  2s  .co m*/
 * @param node the XML node to marshal
 * @param encoding the encoding to use
 * 
 * @return the string with the xml content
 * 
 * @throws CmsXmlException if something goes wrong
 */
public static String marshal(Node node, String encoding) throws CmsXmlException {

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(encoding);
        format.setSuppressDeclaration(true);

        XMLWriter writer = new XMLWriter(out, format);
        writer.setEscapeText(false);

        writer.write(node);
        writer.close();
    } catch (Exception e) {
        throw new CmsXmlException(Messages.get().container(Messages.ERR_MARSHALLING_XML_DOC_0), e);
    }
    return new String(out.toByteArray());
}

From source file:org.opencms.xml.CmsXmlUtils.java

License:Open Source License

/**
 * Validates the structure of a XML document contained in a byte array 
 * with the DTD or XML schema used by the document.<p>
 * /*from   w  ww  . j  a va 2  s  .  com*/
 * @param xmlStream a source providing a XML document that should be validated
 * @param resolver the XML entity resolver to use
 * 
 * @throws CmsXmlException if the validation fails
 */
public static void validateXmlStructure(InputStream xmlStream, EntityResolver resolver) throws CmsXmlException {

    XMLReader reader;
    try {
        reader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
    } catch (SAXException e) {
        // xerces parser not available - no schema validation possible
        if (LOG.isWarnEnabled()) {
            LOG.warn(Messages.get().getBundle().key(Messages.LOG_VALIDATION_INIT_XERXES_SAX_READER_FAILED_0),
                    e);
        }
        // no validation of the content is possible
        return;
    }
    // turn on validation
    try {
        reader.setFeature("http://xml.org/sax/features/validation", true);
        // turn on schema validation
        reader.setFeature("http://apache.org/xml/features/validation/schema", true);
        // configure namespace support
        reader.setFeature("http://xml.org/sax/features/namespaces", true);
        reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
    } catch (SAXNotRecognizedException e) {
        // should not happen as Xerces 2 support this feature
        if (LOG.isWarnEnabled()) {
            LOG.warn(Messages.get().getBundle().key(Messages.LOG_SAX_READER_FEATURE_NOT_RECOGNIZED_0), e);
        }
        // no validation of the content is possible
        return;
    } catch (SAXNotSupportedException e) {
        // should not happen as Xerces 2 support this feature
        if (LOG.isWarnEnabled()) {
            LOG.warn(Messages.get().getBundle().key(Messages.LOG_SAX_READER_FEATURE_NOT_SUPPORTED_0), e);
        }
        // no validation of the content is possible
        return;
    }

    // add an error handler which turns any errors into XML
    CmsXmlValidationErrorHandler errorHandler = new CmsXmlValidationErrorHandler();
    reader.setErrorHandler(errorHandler);

    if (resolver != null) {
        // set the resolver for the "opencms://" URIs
        reader.setEntityResolver(resolver);
    }

    try {
        reader.parse(new InputSource(xmlStream));
    } catch (IOException e) {
        // should not happen since we read form a byte array
        if (LOG.isErrorEnabled()) {
            LOG.error(Messages.get().getBundle().key(Messages.LOG_READ_XML_FROM_BYTE_ARR_FAILED_0), e);
        }
        return;
    } catch (SAXException e) {
        // should not happen since all errors are handled in the XML error handler
        if (LOG.isErrorEnabled()) {
            LOG.error(Messages.get().getBundle().key(Messages.LOG_PARSE_SAX_EXC_0), e);
        }
        return;
    }

    if (errorHandler.getErrors().elements().size() > 0) {
        // there was at last one validation error, so throw an exception
        StringWriter out = new StringWriter(256);
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(out, format);
        try {
            writer.write(errorHandler.getErrors());
            writer.write(errorHandler.getWarnings());
            writer.close();
        } catch (IOException e) {
            // should not happen since we write to a StringWriter
            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_STRINGWRITER_IO_EXC_0), e);
            }
        }
        // generate String from XML for display of document in error message
        throw new CmsXmlException(Messages.get().container(Messages.ERR_XML_VALIDATION_1, out.toString()));
    }
}

From source file:org.openremote.modeler.service.ProtocolParser.java

License:Open Source License

/**
 * Read xml from file./* www .  jav  a2  s  .  c  o  m*/
 * 
 * @param file the file
 * 
 * @return the document
 */
private Document readXmlFromFile(File file) {
    Document protocolDoc = null;
    SAXReader reader = new SAXReader();
    XMLErrorHandler errorHandler = new XMLErrorHandler();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);
    try {
        protocolDoc = reader.read(file);
        SAXParser parser = factory.newSAXParser();
        parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                "http://www.w3.org/2001/XMLSchema");
        parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",
                "file:" + this.getClass().getResource("/").getPath().toString() + PROTOCOL_XSD_FILE_NAME);
        SAXValidator validator = new SAXValidator(parser.getXMLReader());
        validator.setErrorHandler(errorHandler);

        validator.validate(protocolDoc);

        XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());

        if (errorHandler.getErrors().hasContent()) {
            writer.write(errorHandler.getErrors());
            throw new ParseProtocolException(
                    "validate xml schema on File " + file.getAbsolutePath() + " fail.");
        }
    } catch (ParserConfigurationException e) {
        throw new ParseProtocolException(
                "Read xml From File " + file.getAbsolutePath() + " occur ParserConfigurationException.", e);
    } catch (SAXException e) {
        throw new ParseProtocolException(
                "Read xml From File " + file.getAbsolutePath() + " occur SAXException.", e);
    } catch (UnsupportedEncodingException e) {
        throw new ParseProtocolException(
                "Read xml From File " + file.getAbsolutePath() + " occur UnsupportedEncodingException.", e);
    } catch (IOException e) {
        throw new ParseProtocolException("Read xml From File " + file.getAbsolutePath() + " occur IOException.",
                e);
    } catch (DocumentException e) {
        throw new ParseProtocolException(
                "Read xml From File " + file.getAbsolutePath() + " occur DocumentException.", e);
    }
    return protocolDoc;
}

From source file:org.openremote.modeler.service.TouchPanelParser.java

License:Open Source License

/**
 * Read xml from file./*from w  w  w.ja  v  a 2s  . c o m*/
 * 
 * @param file the file
 * 
 * @return the document
 */
private Document readXmlFromFile(File file) {
    Document panelDoc = null;
    SAXReader reader = new SAXReader();
    XMLErrorHandler errorHandler = new XMLErrorHandler();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);
    try {
        panelDoc = reader.read(file);
        SAXParser parser = factory.newSAXParser();
        parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                "http://www.w3.org/2001/XMLSchema");
        parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",
                "file:" + this.getClass().getResource("/").getPath().toString() + PANEL_XSD_FILE_NAME);
        SAXValidator validator = new SAXValidator(parser.getXMLReader());
        validator.setErrorHandler(errorHandler);

        validator.validate(panelDoc);

        XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());

        if (errorHandler.getErrors().hasContent()) {
            writer.write(errorHandler.getErrors());
            throw new ParseTouchPanelException(
                    "validate xml schema on File " + file.getAbsolutePath() + " fail.");
        }
    } catch (ParserConfigurationException e) {
        throw new ParseTouchPanelException(
                "Read xml From File " + file.getAbsolutePath() + " occur ParserConfigurationException.", e);
    } catch (SAXException e) {
        throw new ParseTouchPanelException(
                "Read xml From File " + file.getAbsolutePath() + " occur SAXException.", e);
    } catch (UnsupportedEncodingException e) {
        throw new ParseTouchPanelException(
                "Read xml From File " + file.getAbsolutePath() + " occur UnsupportedEncodingException.", e);
    } catch (IOException e) {
        throw new ParseTouchPanelException(
                "Read xml From File " + file.getAbsolutePath() + " occur IOException.", e);
    } catch (DocumentException e) {
        throw new ParseTouchPanelException(
                "Read xml From File " + file.getAbsolutePath() + " occur DocumentException.", e);
    }
    return panelDoc;
}

From source file:org.orbeon.oxf.transformer.xupdate.XUpdateDriver.java

License:Open Source License

public static void main(String[] args)
        throws TransformerException, IOException, ParserConfigurationException, SAXException {

    // Check arguments
    if (args.length != 2) {
        System.err.println("Syntax: java " + XUpdateDriver.class.getName() + " input.xml xupdate.xml");
        return;/*from   www. java  2s  .  c  o m*/
    }

    // Perform transformation
    Templates templates = createTemplates(new FileReader(args[1]));
    final NonLazySAXContentHandler saxContentHandler = new NonLazySAXContentHandler();
    templates.newTransformer().transform(
            new SAXSource(newXMLReader(), new InputSource(new FileReader(args[0]))),
            new SAXResult(saxContentHandler));

    // Output result
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setIndentSize(4);
    XMLWriter xmlWriter = new XMLWriter(System.out, format);
    xmlWriter.write(saxContentHandler.getDocument());
}

From source file:org.palooca.config.BaseConfig.java

License:Open Source License

public void saveConfig(Document document) {
    try {//from   ww w  .  j a v a  2  s . c o m
        Element root = document.getRootElement();
        if (root != null) {
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter writer = new XMLWriter(
                    new FileWriter(new File(URI.create(basePath + root.getName() + ".xml"))), format);
            writer.write(document);
            writer.close();
        }
    } catch (Exception e) {

    }
}