Example usage for javax.xml.transform OutputKeys METHOD

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

Introduction

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

Prototype

String METHOD

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

Click Source Link

Document

method = "xml" | "html" | "text" | expanded name.

Usage

From source file:org.chiba.xml.xforms.Model.java

private XSModel loadSchema(Element element)
        throws TransformerException, IllegalAccessException, InstantiationException, ClassNotFoundException {
    Element copy = (Element) element.cloneNode(true);
    NamespaceCtx.applyNamespaces(element, copy);

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.transform(new DOMSource(copy), new StreamResult(stream));
    byte[] array = stream.toByteArray();

    return loadSchema(new ByteArrayInputStream(array));
}

From source file:org.codice.ddf.catalog.transformer.html.RecordViewHelpers.java

public CharSequence buildMetadata(String metadata, Options options) {
    if (metadata == null) {
        return "";
    }//from  ww  w  . j a v a  2 s . c om
    try {
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        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");

        DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
        StreamResult result = new StreamResult(new StringWriter());

        transformer.transform(new DOMSource(builder.parse(new InputSource(new StringReader(metadata)))),
                result);
        StringBuilder sb = new StringBuilder();
        sb.append("<pre>").append(escapeHtml(result.getWriter().toString())).append("</pre>");
        return new Handlebars.SafeString(sb.toString());
    } catch (TransformerConfigurationException e) {
        LOGGER.warn("Failed to convert metadata to a pretty string", e);
    } catch (TransformerException e) {
        LOGGER.warn("Failed to convert metadata to a pretty string", e);
    } catch (SAXException e) {
        LOGGER.warn("Failed to convert metadata to a pretty string", e);
    } catch (ParserConfigurationException e) {
        LOGGER.warn("Failed to convert metadata to a pretty string", e);
    } catch (IOException e) {
        LOGGER.warn("Failed to convert metadata to a pretty string", e);
    }
    return metadata;
}

From source file:org.codice.opendx.NITFInputTransformer.java

private static String toString(Node doc) {
    if (doc == null)
        return "";

    try {//from   w w  w. java  2s  .  c  o  m
        StringWriter sw = new StringWriter();
        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.transform(new DOMSource(doc), new StreamResult(sw));
        return sw.toString();
    } catch (Exception ex) {
        throw new RuntimeException("Error converting to String", ex);
    }
}

From source file:org.commonjava.maven.galley.maven.model.view.JXPathContextAncestryTest.java

@Before
public void setup() throws Exception {
    docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

    transformer = TransformerFactory.newInstance().newTransformer();

    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    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", "2");
}

From source file:org.commonjava.maven.galley.maven.parse.XMLInfrastructure.java

public String toXML(final Node node, final boolean printXmlDeclaration) {
    String result;/*from  w ww.j  av  a2 s  .  c o  m*/
    try {
        final StringWriter sw = new StringWriter();

        final Transformer transformer = transformerFactory.newTransformer();

        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, printXmlDeclaration ? "no" : "yes");
        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", "2");

        final DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();

        Node doc;
        if (node instanceof Document) {
            doc = node;
        } else {
            doc = docBuilder.newDocument().importNode(node, true);
        }

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

        result = sw.toString();
    } catch (final TransformerException | ParserConfigurationException | DOMException e) {
        throw new GalleyMavenRuntimeException("Failed to render to XML: %s. Reason: %s", e, node,
                e.getMessage());
    }

    return result;
}

From source file:org.cruk.genologics.api.jaxb.JaxbAnnotationTest.java

@SuppressWarnings("unused")
private String reformat(String xml) throws Exception {
    byte[] xmlBytes = xml.getBytes("UTF8");
    Document doc = docBuilder.parse(new ByteArrayInputStream(xmlBytes));

    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(OutputKeys.STANDALONE, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    return writer.toString();
}

From source file:org.dspace.installer_edm.InstallerEDMAskosi.java

/**
 * Modifica el archivo web.xml de Askosi para indicarle el directorio de datos de Askosi
 *
 * @param webXmlFile archivo web.xml de Askosi
 *///from   w w w.j  a v a 2  s.  c  o m
private void changeWebXml(File webXmlFile, String webXmlFileName) {
    try {
        // se abre con DOM el archivo web.xml
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(webXmlFile);
        XPath xpathInputForms = XPathFactory.newInstance().newXPath();

        // se busca el elemento SKOSdirectory
        NodeList results = (NodeList) xpathInputForms.evaluate("//*[contains(*,\"SKOSdirectory\")]", doc,
                XPathConstants.NODESET);
        if (results.getLength() > 0) {
            Element contextParam = (Element) results.item(0);

            // se busca el elemento context-param como hijo del anterior
            if (contextParam.getTagName().equals("context-param")) {

                // se busca el elemento param-value como hijo del anterior
                NodeList resultsParamValue = contextParam.getElementsByTagName("param-value");
                if (resultsParamValue.getLength() > 0) {

                    // se modifica con la ruta del directorio de datos de Askosi
                    Element valueParam = (Element) resultsParamValue.item(0);
                    Text text = doc.createTextNode(finalAskosiDataDestDirFile.getAbsolutePath());
                    valueParam.replaceChild(text, valueParam.getFirstChild());

                    // se guarda
                    TransformerFactory transformerFactory = TransformerFactory.newInstance();
                    Transformer transformer = transformerFactory.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", "2");
                    DocumentType docType = doc.getDoctype();
                    if (docType != null) {
                        if (docType.getPublicId() != null)
                            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId());
                        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId());
                    }
                    DOMSource source = new DOMSource(doc);
                    StreamResult result = (fileSeparator.equals("\\")) ? new StreamResult(webXmlFileName)
                            : new StreamResult(webXmlFile);
                    transformer.transform(source, result);
                }
            }
        } else
            installerEDMDisplay.showQuestion(currentStepGlobal, "changeWebXml.noSKOSdirectory",
                    new String[] { webXmlFile.getAbsolutePath() });
    } catch (ParserConfigurationException e) {
        showException(e);
    } catch (SAXException e) {
        showException(e);
    } catch (IOException e) {
        showException(e);
    } catch (XPathExpressionException e) {
        showException(e);
    } catch (TransformerConfigurationException e) {
        showException(e);
    } catch (TransformerException e) {
        showException(e);
    }

}

From source file:org.dspace.installer_edm.InstallerEDMConfEDMExport.java

/**
 * Aadimos el contenido del documento jdom como archivo web.xml al flujo de escritura del war
 *
 * @param jarOutputStream flujo de escritura del war
 * @throws TransformerException//from  www  . ja va2 s .com
 * @throws IOException
 */
private void addNewWebXml(JarOutputStream jarOutputStream) throws TransformerException, IOException {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.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", "2");
    DocumentType docType = eDMExportDocument.getDoctype();
    if (docType != null) {
        if (docType.getPublicId() != null)
            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId());
        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId());
    }
    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    DOMSource source = new DOMSource(eDMExportDocument);
    transformer.transform(source, result);
    String xmlString = sw.toString();
    jarOutputStream.putNextEntry(new JarEntry("WEB-INF/web.xml"));
    jarOutputStream.write(xmlString.getBytes());
    jarOutputStream.closeEntry();
}

From source file:org.eclipse.swordfish.p2.internal.deploy.server.MetadataProcessor.java

/**
 * Write a document to an output stream/*from  w  w w  . j  a va  2  s. c o  m*/
 * 
 * NOTE: Package visibility to enable unit testing only!
 * 
 * @param doc - the document
 * @param isSimpleOutput - false = no idention
 * @param sink - the out put stream to write to
 * @throws IOException - on write errors.
 */
final void document2OutputStream(Document doc, boolean isSimpleOutput, OutputStream sink) throws IOException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t;

    try {
        t = tf.newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        if (!isSimpleOutput) {
            t.setOutputProperty(OutputKeys.METHOD, "xml");
            t.setOutputProperty(OutputKeys.INDENT, "yes");
        }

        StreamResult sr = new StreamResult(sink);
        t.transform(new DOMSource(doc), sr);

    } catch (TransformerException e) {
        logAndRethrowAsIOException("Error serializing document", e);
    }

}

From source file:org.expath.tools.model.exist.EXistSequence.java

/**
 * Borrowed from {@link org.expath.tools.saxon.model.SaxonSequence}
 *///from  w  w w.  j av  a2s. c  om
private Properties makeOutputProperties(final SerialParameters params) throws ToolsException {
    final Properties props = new Properties();

    setOutputKey(props, OutputKeys.METHOD, params.getMethod());
    setOutputKey(props, OutputKeys.MEDIA_TYPE, params.getMediaType());
    setOutputKey(props, OutputKeys.ENCODING, params.getEncoding());
    setOutputKey(props, OutputKeys.CDATA_SECTION_ELEMENTS, params.getCdataSectionElements());
    setOutputKey(props, OutputKeys.DOCTYPE_PUBLIC, params.getDoctypePublic());
    setOutputKey(props, OutputKeys.DOCTYPE_SYSTEM, params.getDoctypeSystem());
    setOutputKey(props, OutputKeys.INDENT, params.getIndent());
    setOutputKey(props, OutputKeys.OMIT_XML_DECLARATION, params.getOmitXmlDeclaration());
    setOutputKey(props, OutputKeys.STANDALONE, params.getStandalone());
    setOutputKey(props, OutputKeys.VERSION, params.getVersion());

    return props;
}