Example usage for javax.xml.transform OutputKeys INDENT

List of usage examples for javax.xml.transform OutputKeys INDENT

Introduction

In this page you can find the example usage for javax.xml.transform OutputKeys INDENT.

Prototype

String INDENT

To view the source code for javax.xml.transform OutputKeys INDENT.

Click Source Link

Document

indent = "yes" | "no".

Usage

From source file:Main.java

private static Transformer getThreadedTransformer(final boolean omitXmlDeclaration, final boolean standalone,
        final Map<Thread, Transformer> threadMap, final String xslURL)
        throws TransformerConfigurationException {
    final Thread currentThread = Thread.currentThread();
    Transformer transformer = null;
    if (threadMap != null) {
        transformer = threadMap.get(currentThread);
    }/* w ww.j  a  va2  s  . c o  m*/
    if (transformer == null) {
        if (xslURL == null) {
            transformer = tFactory.newTransformer(); // "never null"
        } else {
            transformer = tFactory.newTransformer(new StreamSource(xslURL));
        }
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        if (threadMap != null) {
            threadMap.put(currentThread, transformer);
        }
    }
    transformer.setOutputProperty(OutputKeys.STANDALONE, standalone ? "yes" : "no");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXmlDeclaration ? "yes" : "no");
    return transformer;
}

From source file:com.sun.portal.portletcontainer.admin.PortletRegistryHelper.java

public static synchronized void writeFile(Document document, File file) throws PortletRegistryException {
    FileOutputStream output = null;
    try {//from w  w w  .  j a  v  a 2 s  .c  o  m
        // Use a Transformer for output
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.ENCODING, CharEncoding.UTF_8);
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "5");

        DOMSource source = new DOMSource(document);
        // StreamResult result = new StreamResult(System.out);
        output = new FileOutputStream(file);
        StreamResult result = new StreamResult(output);
        transformer.transform(source, result);
    } catch (TransformerConfigurationException tce) {
        throw new PortletRegistryException(tce);
    } catch (TransformerException te) {
        throw new PortletRegistryException(te);
    } catch (Exception e) {
        throw new PortletRegistryException(e);
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException ex) {
                SilverTrace.warn("portlet", PortletRegistryHelper.class.getSimpleName() + ".writeFile()",
                        "root.EX_NO_MESSAGE", ex);
            }
        }
    }
}

From source file:edu.harvard.i2b2.fhir.Utils.java

public static String getStringFromDocument(Document doc) {
    try {//  www.j  ava 2 s. com
        doc.normalize();
        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        //
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        int indent = 2;
        if (indent > 0) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
                    Integer.toString(indent));
        }
        //

        transformer.transform(domSource, result);
        return writer.toString();
    } catch (TransformerException ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:org.lareferencia.backend.indexer.IntelligoIndexer.java

private Transformer buildTransformer() throws IndexerException {

    Transformer trf;/*from  w  ww.  j a va2  s. c  o  m*/

    try {

        StreamSource stylesource = new StreamSource(stylesheet);
        trf = xformFactory.newTransformer(stylesource);

        trf = MedatadaDOMHelper.buildXSLTTransformer(stylesheet);
        trf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trf.setOutputProperty(OutputKeys.INDENT, "yes");
        trf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    } catch (TransformerConfigurationException e) {
        throw new IndexerException(e.getMessage(), e.getCause());
    }

    return trf;

}

From source file:ee.ria.xroad.common.Request.java

/**
 * Converts the given SOAP message string to a pretty-printed format.
 * @param soap the SOAP XML to convert/*  w  w  w .  j a  v  a 2 s  . co  m*/
 * @return pretty-printed String of the SOAP XML
 */
public static String prettyFormat(String soap) {
    try {
        Source xmlInput = new StreamSource(new StringReader(soap));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();

        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:datascript.backend.xml.XmlExtension.java

public void generate(DataScriptEmitter emitter, TokenAST rootNode) throws Exception {
    if (params == null)
        throw new DataScriptException("No parameters set for XmlBackend!");

    if (!params.argumentExists("-xml")) {
        System.out.println("emitting XML file is disabled.");
        return;/*from  w w w.  j a va2s  .  c o  m*/
    }

    System.out.println("emitting xml");

    String fileName = params.getCommandlineArg("-xml");
    if (fileName == null) {
        fileName = "datascript.xml";
    }
    File outputFile = new File(params.getOutPathName(), fileName);
    this.rootNode = rootNode;
    FileOutputStream os = new FileOutputStream(outputFile);

    TransformerFactory tf = TransformerFactory.newInstance();
    tf.setAttribute("indent-number", new Integer(2));
    Transformer t = tf.newTransformer();
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty(OutputKeys.METHOD, "xml");
    Source source = new SAXSource(this, new InputSource());
    Result result = new StreamResult(new OutputStreamWriter(os));
    t.transform(source, result);
}

From source file:com.alfaariss.oa.util.configuration.handler.dummy.DummyConfigurationHandler.java

/**
 * Save the configuration to the screen.
 * @see IConfigurationHandler#saveConfiguration(org.w3c.dom.Document)
 *//*from  w  w  w.j  av  a 2  s .c  o m*/
public void saveConfiguration(Document oConfigurationDocument) throws ConfigurationException {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.VERSION, "1.0");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(oConfigurationDocument), new StreamResult(System.out));
    } catch (TransformerException e) {
        _logger.error("Error while transforming document", e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE);
    }
}

From source file:me.cavar.pg2tei.TEIDoc.java

/**
 *
 * @param doc/*  www. ja  v a2s . c om*/
 * @return
 */
public String getTEIXMLString(Document doc) {
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans;
    StringWriter strw = new StringWriter();
    StreamResult result = new StreamResult(strw);
    try {
        trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        // create string from xml tree
        DOMSource source = new DOMSource(doc);
        trans.transform(source, result);
    } catch (TransformerConfigurationException ex) {
        Logger.getLogger(TEIDoc.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TransformerException ex) {
        Logger.getLogger(TEIDoc.class.getName()).log(Level.SEVERE, null, ex);
    }
    return strw.toString();
}

From source file:org.syncope.core.scheduling.ReportJob.java

@Override
public void execute(final JobExecutionContext context) throws JobExecutionException {

    Report report = reportDAO.find(reportId);
    if (report == null) {
        throw new JobExecutionException("Report " + reportId + " not found");
    }/* www  .  j  a v a 2s . c  o  m*/

    // 1. create execution
    ReportExec execution = new ReportExec();
    execution.setStatus(ReportExecStatus.STARTED);
    execution.setStartDate(new Date());
    execution.setReport(report);
    execution = reportExecDAO.save(execution);

    // 2. define a SAX handler for generating result as XML
    TransformerHandler handler;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    zos.setLevel(Deflater.BEST_COMPRESSION);
    try {
        SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        handler = transformerFactory.newTransformerHandler();
        Transformer serializer = handler.getTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");

        // a single ZipEntry in the ZipOutputStream
        zos.putNextEntry(new ZipEntry(report.getName()));

        // streaming SAX handler in a compressed byte array stream
        handler.setResult(new StreamResult(zos));
    } catch (Exception e) {
        throw new JobExecutionException("While configuring for SAX generation", e, true);
    }

    execution.setStatus(ReportExecStatus.RUNNING);
    execution = reportExecDAO.save(execution);

    ConfigurableListableBeanFactory beanFactory = ApplicationContextManager.getApplicationContext()
            .getBeanFactory();

    // 3. actual report execution
    StringBuilder reportExecutionMessage = new StringBuilder();
    StringWriter exceptionWriter = new StringWriter();
    try {
        // report header
        handler.startDocument();
        AttributesImpl atts = new AttributesImpl();
        atts.addAttribute("", "", ATTR_NAME, XSD_STRING, report.getName());
        handler.startElement("", "", ELEMENT_REPORT, atts);

        // iterate over reportlet instances defined for this report
        for (ReportletConf reportletConf : report.getReportletConfs()) {
            Class reportletClass = null;
            try {
                reportletClass = Class.forName(reportletConf.getReportletClassName());
            } catch (ClassNotFoundException e) {
                LOG.error("Reportlet class not found: {}", reportletConf.getReportletClassName(), e);

            }

            if (reportletClass != null) {
                Reportlet autowired = (Reportlet) beanFactory.createBean(reportletClass,
                        AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false);
                autowired.setConf(reportletConf);

                // invoke reportlet
                try {
                    autowired.extract(handler);
                } catch (Exception e) {
                    execution.setStatus(ReportExecStatus.FAILURE);

                    Throwable t = e instanceof ReportException ? e.getCause() : e;
                    exceptionWriter.write(t.getMessage() + "\n\n");
                    t.printStackTrace(new PrintWriter(exceptionWriter));
                    reportExecutionMessage.append(exceptionWriter.toString()).append("\n==================\n");
                }
            }
        }

        // report footer
        handler.endElement("", "", ELEMENT_REPORT);
        handler.endDocument();

        if (!ReportExecStatus.FAILURE.name().equals(execution.getStatus())) {

            execution.setStatus(ReportExecStatus.SUCCESS);
        }
    } catch (Exception e) {
        execution.setStatus(ReportExecStatus.FAILURE);

        exceptionWriter.write(e.getMessage() + "\n\n");
        e.printStackTrace(new PrintWriter(exceptionWriter));
        reportExecutionMessage.append(exceptionWriter.toString());

        throw new JobExecutionException(e, true);
    } finally {
        try {
            zos.closeEntry();
            zos.close();
            baos.close();
        } catch (IOException e) {
            LOG.error("While closing StreamResult's backend", e);
        }

        execution.setExecResult(baos.toByteArray());
        execution.setMessage(reportExecutionMessage.toString());
        execution.setEndDate(new Date());
        reportExecDAO.save(execution);
    }
}

From source file:org.alloy.metal.xml.merge.ImportProcessor.java

public List<ResourceInputStream> extract(List<ResourceInputStream> sources) throws MergeException {
    try {/*from   w  w w. j  a  va  2  s .  c om*/
        DynamicResourceIterator resourceList = new DynamicResourceIterator();
        resourceList.addAll(sources);

        while (resourceList.hasNext()) {
            ResourceInputStream myStream = resourceList.nextResource();
            Document doc = builder.parse(myStream);
            NodeList nodeList = (NodeList) xPath.evaluate(IMPORT_PATH, doc, XPathConstants.NODESET);
            int length = nodeList.getLength();
            for (int j = 0; j < length; j++) {
                Element element = (Element) nodeList.item(j);
                Resource resource = loader.getResource(element.getAttribute("resource"));
                ResourceInputStream ris = new ResourceInputStream(resource.getInputStream(),
                        resource.getURL().toString());
                resourceList.addEmbeddedResource(ris);
                element.getParentNode().removeChild(element);
            }
            if (length > 0) {
                TransformerFactory tFactory = TransformerFactory.newInstance();
                Transformer xmlTransformer = tFactory.newTransformer();
                xmlTransformer.setOutputProperty(OutputKeys.VERSION, "1.0");
                xmlTransformer.setOutputProperty(OutputKeys.ENCODING, _String.CHARACTER_ENCODING.toString());
                xmlTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
                xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes");

                DOMSource source = new DOMSource(doc);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(baos));
                StreamResult result = new StreamResult(writer);
                xmlTransformer.transform(source, result);

                byte[] itemArray = baos.toByteArray();

                resourceList.set(resourceList.getPosition() - 1, new ResourceInputStream(
                        new ByteArrayInputStream(itemArray), null, myStream.getNames()));
            } else {
                myStream.reset();
            }
        }

        return resourceList;
    } catch (Exception e) {
        throw new MergeException(e);
    }
}