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:com.idiominc.ws.opentopic.fo.i18n.PreprocessorTask.java

@Override
public void execute() throws BuildException {
    checkParameters();/* w w w . ja  va 2s  .  c o m*/

    log("Processing " + input + " to " + output, Project.MSG_INFO);
    OutputStream out = null;
    try {
        final DocumentBuilder documentBuilder = XMLUtils.getDocumentBuilder();
        documentBuilder.setEntityResolver(xmlcatalog);

        final Document doc = documentBuilder.parse(input);
        final Document conf = documentBuilder.parse(config);
        final MultilanguagePreprocessor preprocessor = new MultilanguagePreprocessor(new Configuration(conf));
        final Document document = preprocessor.process(doc);

        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setURIResolver(xmlcatalog);
        final Transformer transformer;
        if (style != null) {
            log("Loading stylesheet " + style, Project.MSG_INFO);
            transformer = transformerFactory.newTransformer(new StreamSource(style));
        } else {
            transformer = transformerFactory.newTransformer();
        }
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        if (doc.getDoctype() != null) {
            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doc.getDoctype().getPublicId());
            transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId());
        }

        out = new FileOutputStream(output);
        final StreamResult streamResult = new StreamResult(out);
        transformer.transform(new DOMSource(document), streamResult);
    } catch (final RuntimeException e) {
        throw e;
    } catch (final Exception e) {
        throw new BuildException(e);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:de.tudarmstadt.ukp.shibhttpclient.Utils.java

public static String xmlToString(Element doc) {
    StringWriter sw = new StringWriter();
    try {// w  w w .jav a  2s.  c  o m
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        transformer.transform(new DOMSource(doc), new StreamResult(sw));
        return sw.toString();
    } catch (TransformerException e) {
        LOG.error("Unable to print message contents: ", e);
        return "<ERROR: " + e.getMessage() + ">";
    }
}

From source file:cz.muni.fi.webmias.TeXConverter.java

/**
 * Converts TeX formula to MathML using LaTeXML through a web service.
 *
 * @param query String containing one or more keywords and TeX formulae
 * (formulae enclosed in $ or $$).// w w w. j  a  v  a2s  .c  om
 * @return String containing formulae converted to MathML that replaced
 * original TeX forms. Non math tokens are connected at the end.
 */
public static String convertTexLatexML(String query) {
    query = query.replaceAll("\\$\\$", "\\$");
    if (query.matches(".*\\$.+\\$.*")) {
        try {
            HttpClient httpclient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(LATEX_TO_XHTML_CONVERSION_WS_URL);

            // Request parameters and other properties.
            List<NameValuePair> params = new ArrayList<>(1);
            params.add(new BasicNameValuePair("code", query));
            httppost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            // Execute and get the response.
            HttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    try (InputStream responseContents = resEntity.getContent()) {
                        DocumentBuilder dBuilder = MIaSUtils.prepareDocumentBuilder();
                        org.w3c.dom.Document doc = dBuilder.parse(responseContents);
                        NodeList ps = doc.getElementsByTagName("p");
                        String convertedMath = "";
                        for (int k = 0; k < ps.getLength(); k++) {
                            Node p = ps.item(k);
                            NodeList pContents = p.getChildNodes();
                            for (int j = 0; j < pContents.getLength(); j++) {
                                Node pContent = pContents.item(j);
                                if (pContent instanceof Text) {
                                    convertedMath += pContent.getNodeValue() + "\n";
                                } else {
                                    TransformerFactory transFactory = TransformerFactory.newInstance();
                                    Transformer transformer = transFactory.newTransformer();
                                    StringWriter buffer = new StringWriter();
                                    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                    transformer.transform(new DOMSource(pContent), new StreamResult(buffer));
                                    convertedMath += buffer.toString() + "\n";
                                }
                            }
                        }
                        return convertedMath;
                    }
                }
            }

        } catch (TransformerException | SAXException | ParserConfigurationException | IOException ex) {
            Logger.getLogger(ProcessServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return query;
}

From source file:com.etsy.arbiter.OozieWorkflowGenerator.java

/**
 * Generate Oozie workflows from Arbiter workflows
 *
 * @param outputBase The directory in which to output the Oozie workflows
 * @param workflows The workflows to convert
 * @param generateGraphviz Indicate if Graphviz graphs should be generated for workflows
 * @param graphvizFormat The format in which Graphviz graphs should be generated if enabled
 *//*  www.jav a 2  s  .  c  o m*/
public void generateOozieWorkflows(String outputBase, List<Workflow> workflows, boolean generateGraphviz,
        String graphvizFormat) throws IOException, ParserConfigurationException, TransformerException {
    File outputBaseFile = new File(outputBase);
    FileUtils.forceMkdir(outputBaseFile);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    Date currentDate = new Date();
    String currentDateString = DATE_FORMAT.format(currentDate);

    for (Workflow workflow : workflows) {
        String outputDir = outputBase + "/" + workflow.getName();
        File outputDirFile = new File(outputDir);
        FileUtils.forceMkdir(outputDirFile);
        DirectedAcyclicGraph<Action, DefaultEdge> workflowGraph = null;

        try {
            workflowGraph = WorkflowGraphBuilder.buildWorkflowGraph(workflow, config, outputDir,
                    generateGraphviz, graphvizFormat);
        } catch (WorkflowGraphException w) {
            LOG.error("Unable to generate workflow", w);
            System.exit(1);
        }

        if (generateGraphviz) {
            GraphvizGenerator.generateGraphviz(workflowGraph, outputDir + "/" + workflow.getName() + ".dot",
                    graphvizFormat);
        }

        Document xmlDoc = builder.newDocument();

        Directives directives = new Directives();
        createRootElement(workflow.getName(), directives);

        Action kill = getActionByType(workflowGraph, "kill");
        Action end = getActionByType(workflowGraph, "end");
        Action start = getActionByType(workflowGraph, "start");
        Action errorHandler = workflow.getErrorHandler();
        Action finalTransition = kill == null ? end : kill;

        Action errorTransition = errorHandler == null ? (kill == null ? end : kill) : errorHandler;
        DepthFirstIterator<Action, DefaultEdge> iterator = new DepthFirstIterator<>(workflowGraph, start);

        while (iterator.hasNext()) {
            Action a = iterator.next();
            Action transition = getTransition(workflowGraph, a);
            switch (a.getType()) {
            case "start":
                if (transition == null) {
                    throw new RuntimeException("No transition found for start action");
                }
                directives.add("start").attr("to", transition.getName()).up();
                break;
            case "end":
                // Skip and add at the end
                break;
            case "fork":
                directives.add("fork").attr("name", a.getName());
                for (DefaultEdge edge : workflowGraph.outgoingEdgesOf(a)) {
                    Action target = workflowGraph.getEdgeTarget(edge);
                    directives.add("path").attr("start", target.getName()).up();
                }
                directives.up();
                break;
            case "join":
                if (transition == null) {
                    throw new RuntimeException(
                            String.format("No transition found for join action %s", a.getName()));
                }
                directives.add("join").attr("name", a.getName()).attr("to", transition.getName()).up();
                break;
            default:
                createActionElement(a, workflowGraph, transition,
                        a.equals(errorHandler) ? finalTransition : errorTransition, directives);
                directives.up();
                break;
            }
        }
        if (kill != null) {
            directives.add("kill").attr("name", kill.getName()).add("message")
                    .set(kill.getNamedArgs().get("message")).up().up();
        }
        if (end != null) {
            directives.add("end").attr("name", end.getName()).up();
        }

        try {
            new Xembler(directives).apply(xmlDoc);
        } catch (ImpossibleModificationException e) {
            throw new RuntimeException(e);
        }
        writeDocument(outputDirFile, xmlDoc, transformer, workflow.getName(), currentDateString);
    }
}

From source file:me.mayo.telnetkek.config.ConfigLoader.java

private boolean generateXML(final File file) {
    try {//from  ww w .  ja  v a 2  s. c  o m
        final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

        final Element rootElement = doc.createElement("configuration");
        doc.appendChild(rootElement);

        rootElement.appendChild(this.servers.listToXML(doc));
        rootElement.appendChild(this.playerCommands.listToXML(doc));
        rootElement.appendChild(this.favoriteButtons.listToXML(doc));

        final Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        transformer.transform(new DOMSource(doc), new StreamResult(file));

        return true;
    } catch (IllegalArgumentException | ParserConfigurationException | TransformerException | DOMException ex) {
        TelnetKek.LOGGER.log(Level.SEVERE, null, ex);
    }

    return false;
}

From source file:org.orcid.examples.jopmts.mvc.OrcidController.java

private String documentXml(Document orcidDocument)
        throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException {
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans = transfac.newTransformer();
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    trans.setOutputProperty(OutputKeys.INDENT, "yes");

    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    DOMSource source = new DOMSource(orcidDocument);
    trans.transform(source, result);//from  ww  w .j av  a  2  s  . c o m
    String xmlString = sw.toString();
    return xmlString;
}

From source file:it.unibas.spicy.persistence.xml.DAOXmlUtility.java

public void saveDOM(org.w3c.dom.Document document, String filename) throws DAOException {
    try {/* w w w  .ja v  a2 s .c  om*/
        File file = new java.io.File(filename);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", new Integer(2));
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(file);
        transformer.transform(source, result);

    } catch (Exception ex) {
        logger.error("- Exception in saveDOM: \n" + ex);
        throw new DAOException(ex.getMessage());
    }
}

From source file:org.openmrs.module.casereport.rest.v1_0.controller.CaseReportController.java

@RequestMapping(value = "/" + CaseReportConstants.MODULE_ID + "/{uuid}/document", method = RequestMethod.GET)
@ResponseBody//from  w w w  .  j a va 2 s . c  om
public Object getSubmittedCDAContents(@PathVariable("uuid") String uuid) {

    CaseReport cr = service.getCaseReportByUuid(uuid);
    if (cr == null) {
        throw new ObjectNotFoundException();
    }

    SimpleObject so = new SimpleObject();
    String pnrDoc = DocumentUtil.getSubmittedDocumentContents(cr);
    Exception e = null;
    if (StringUtils.isNotBlank(pnrDoc)) {
        try {
            Object o = webServiceTemplate.getUnmarshaller().unmarshal(new StringSource(pnrDoc));
            byte[] bytes = ((JAXBElement<ProvideAndRegisterDocumentSetRequestType>) o).getValue().getDocument()
                    .get(0).getValue();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder db = factory.newDocumentBuilder();
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "2");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            Document cdaDoc = db.parse(new ByteArrayInputStream(bytes));
            StringResult result = new StringResult();
            transformer.transform(new DOMSource(cdaDoc), result);
            so.add("contents", result.toString());

            return so;
        } catch (Exception ex) {
            e = ex;
        }
    }

    throw new APIException("casereport.error.submittedCDAdoc.fail", e);
}

From source file:net.bpelunit.framework.control.util.BPELUnitUtil.java

private static String serializeXML(Node node) throws TransformerException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty(OutputKeys.METHOD, "xml");
    ByteArrayOutputStream bOS = new ByteArrayOutputStream();
    t.transform(new DOMSource(node), new StreamResult(bOS));
    return bOS.toString();
}

From source file:hu.bme.mit.sette.common.util.XmlUtils.java

/**
 * Transforms the specified XML document to the specified result.
 *
 * @param document//  ww w .j a v a  2s.  c  o m
 *            The XML document.
 * @param result
 *            The result.
 * @throws TransformerException
 *             If an unrecoverable error occurs during the course of the
 *             transformation.
 */
private static void transformXml(final Document document, final Result result) throws TransformerException {
    Validate.notNull(document, "The document must not be null");
    Validate.notNull(result, "The result must not be null");

    // write XML to stream
    Transformer transformer = TransformerFactory.newInstance().newTransformer();

    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    transformer.transform(new DOMSource(document), result);
}