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:objective.taskboard.utils.XmlUtilsTest.java

private static void format(File inputXmlFile, File outputXmlFile) {
    try {/*w  w w  .  jav a 2s.  c o  m*/
        Document document = XmlUtils.asDocument(inputXmlFile);
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer idTransform = transFactory.newTransformer();
        idTransform.setOutputProperty(OutputKeys.METHOD, "xml");
        idTransform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        idTransform.setOutputProperty(OutputKeys.INDENT, "yes");
        idTransform.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        Source input = new DOMSource(document);
        Result output = new StreamResult(outputXmlFile);
        idTransform.transform(input, output);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.alfresco.repo.content.transform.EmailToPDFContentTransformer.java

/**
 * Returns an appropriate Tika ContentHandler for the requested content type. Normally you'll
 * let this work as default, but if you need fine-grained control of how the Tika events become
 * text then override and supply your own.
 *
 * @param targetMimeType//w  w w .  j  a  v a  2  s .  co m
 *            the target mime type
 * @param output
 *            the output
 * @return the content handler
 * @throws TransformerConfigurationException
 *             the transformer configuration exception
 */
protected ContentHandler getContentHandler(String targetMimeType, Writer output)
        throws TransformerConfigurationException {
    if (MimetypeMap.MIMETYPE_TEXT_PLAIN.equals(targetMimeType)) {
        return new BodyContentHandler(output);
    }

    SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory.newInstance();
    TransformerHandler handler = factory.newTransformerHandler();
    handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
    handler.setResult(new StreamResult(output));

    if (MimetypeMap.MIMETYPE_HTML.equals(targetMimeType)) {
        handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "html");
    } else if (MimetypeMap.MIMETYPE_XHTML.equals(targetMimeType)
            || MimetypeMap.MIMETYPE_XML.equals(targetMimeType)) {
        handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "xml");
    } else {
        throw new TransformerInfoException(WRONG_FORMAT_MESSAGE_ID,
                new IllegalArgumentException("Requested target type " + targetMimeType + " not supported"));
    }
    return handler;
}

From source file:org.alfresco.repo.content.transform.EMLParser.java

/**
 * Gets the content handler.//from www  .ja  v a  2 s. c o m
 *
 * @param targetMimeType
 *            the target mime type
 * @param output
 *            the output
 * @return the content handler
 * @throws TransformerConfigurationException
 *             the transformer configuration exception
 */
protected static ContentHandler getContentHandler(String targetMimeType, Writer output)
        throws TransformerConfigurationException {
    if (MimetypeMap.MIMETYPE_TEXT_PLAIN.equals(targetMimeType)) {
        return new BodyContentHandler(output);
    }

    SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory.newInstance();
    TransformerHandler handler = factory.newTransformerHandler();
    handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
    handler.setResult(new StreamResult(output));

    if (MimetypeMap.MIMETYPE_HTML.equals(targetMimeType)) {
        handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "html");
    } else if (MimetypeMap.MIMETYPE_XHTML.equals(targetMimeType)
            || MimetypeMap.MIMETYPE_XML.equals(targetMimeType)) {
        handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "xml");
    } else {

    }
    return handler;
}

From source file:org.alfresco.repo.content.transform.TikaPoweredContentTransformer.java

/**
 * Returns an appropriate Tika ContentHandler for the
 *  requested content type. Normally you'll let this
 *  work as default, but if you need fine-grained
 *  control of how the Tika events become text then
 *  override and supply your own.//from   w w  w.java  2s. c  o m
 */
protected ContentHandler getContentHandler(String targetMimeType, Writer output)
        throws TransformerConfigurationException {
    if (MimetypeMap.MIMETYPE_TEXT_PLAIN.equals(targetMimeType)) {
        return new BodyContentHandler(output);
    }

    SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler handler = factory.newTransformerHandler();
    handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
    handler.setResult(new StreamResult(output));

    if (MimetypeMap.MIMETYPE_HTML.equals(targetMimeType)) {
        handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "html");
        return new ExpandedTitleContentHandler(handler);
    } else if (MimetypeMap.MIMETYPE_XHTML.equals(targetMimeType)
            || MimetypeMap.MIMETYPE_XML.equals(targetMimeType)) {
        handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "xml");
    } else {
        throw new TransformerInfoException(WRONG_FORMAT_MESSAGE_ID,
                new IllegalArgumentException("Requested target type " + targetMimeType + " not supported"));
    }
    return handler;
}

From source file:org.alfresco.repo.rendition.executer.HTMLRenderingEngine.java

/**
 * Builds a Tika-compatible SAX content handler, which will
 *  be used to generate+capture the XHTML
 *//*from  w w  w. j  ava  2s  . c om*/
private ContentHandler buildContentHandler(Writer output, RenderingContext context) {
    // Create the main transformer
    SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler handler;

    try {
        handler = factory.newTransformerHandler();
    } catch (TransformerConfigurationException e) {
        throw new RenditionServiceException("SAX Processing isn't available - " + e);
    }

    handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
    handler.setResult(new StreamResult(output));
    handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "xml");

    // Change the image links as they go past
    String dirName = null, imgPrefix = null;
    if (context.getParamWithDefault(PARAM_IMAGES_SAME_FOLDER, false)) {
        imgPrefix = getImagesPrefixName(context);
    } else {
        dirName = getImagesDirectoryName(context);
    }
    ContentHandler contentHandler = new TikaImageRewritingContentHandler(handler, dirName, imgPrefix);

    // If required, wrap it to only return the body 
    boolean bodyOnly = context.getParamWithDefault(PARAM_BODY_CONTENTS_ONLY, false);
    if (bodyOnly) {
        contentHandler = new BodyContentHandler(contentHandler);
    }

    // All done
    return contentHandler;
}

From source file:org.alfresco.util.XMLUtil.java

/** utility function for serializing a node */
public static void print(final Node n, final Writer output, final boolean indent) {
    try {//from w  ww  .  j ava  2  s. c o m
        final TransformerFactory tf = TransformerFactory.newInstance();
        final Transformer t = tf.newTransformer();
        t.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no");
        t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        t.setOutputProperty(OutputKeys.METHOD, "xml");
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("writing out a document for "
                    + (n instanceof Document ? ((Document) n).getDocumentElement() : n).getNodeName() + " to "
                    + (output instanceof StringWriter ? "string" : output));
        }
        t.transform(new DOMSource(n), new StreamResult(output));
    } catch (TransformerException te) {
        te.printStackTrace();
        assert false : te.getMessage();
    }
}

From source file:org.ambraproject.util.TextUtils.java

/**
 * Transform a xml string to html text//from   ww  w.  jav  a2s .c  o  m
 * @param xmlContent xml
 * @return html html text
 */
public static String transformXMLtoHtmlText(String xmlContent) {
    if (xmlContent != null) {
        String htmlContent = "";

        try {
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            // surround the xml content with temporary root element to make sure that it can be parsed.
            InputSource source = new InputSource(
                    new StringReader("<temprootelement>" + xmlContent + "</temprootelement>"));
            Document doc = db.parse(source);

            // remove all the elements from the xml content
            StringWriter stw = new StringWriter();
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.METHOD, "text");
            transformer.transform(new DOMSource(doc), new StreamResult(stw));

            htmlContent = stw.toString();
            // make sure all the characters are escaped using html entities
            htmlContent = StringEscapeUtils.escapeHtml(htmlContent);

        } catch (Exception e) {
            log.info("Failed to transform " + xmlContent + " to html text", e);
        }

        return htmlContent;
    } else {
        return "";
    }
}

From source file:org.apache.ambari.server.upgrade.UpgradeCatalog220.java

protected void updateKnoxTopology() throws AmbariException {
    AmbariManagementController ambariManagementController = injector
            .getInstance(AmbariManagementController.class);
    for (final Cluster cluster : getCheckedClusterMap(ambariManagementController.getClusters()).values()) {
        Config topology = cluster.getDesiredConfigByType(TOPOLOGY_CONFIG);
        if (topology != null) {
            String content = topology.getProperties().get(CONTENT_PROPERTY);
            if (content != null) {
                Document topologyXml = convertStringToDocument(content);
                if (topologyXml != null) {
                    Element root = topologyXml.getDocumentElement();
                    if (root != null) {
                        NodeList providerNodes = root.getElementsByTagName("provider");
                        boolean authorizationProviderExists = false;
                        try {
                            for (int i = 0; i < providerNodes.getLength(); i++) {
                                Node providerNode = providerNodes.item(i);
                                NodeList childNodes = providerNode.getChildNodes();
                                for (int k = 0; k < childNodes.getLength(); k++) {
                                    Node child = childNodes.item(k);
                                    child.normalize();
                                    String childTextContent = child.getTextContent();
                                    if (childTextContent != null
                                            && childTextContent.toLowerCase().equals("authorization")) {
                                        authorizationProviderExists = true;
                                        break;
                                    }//from w ww . ja  v  a2s.c om
                                }
                                if (authorizationProviderExists) {
                                    break;
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            LOG.error(
                                    "Error occurred during check 'authorization' provider already exists in topology."
                                            + e);
                            return;
                        }
                        if (!authorizationProviderExists) {
                            NodeList nodeList = root.getElementsByTagName("gateway");
                            if (nodeList != null && nodeList.getLength() > 0) {
                                boolean rangerPluginEnabled = isConfigEnabled(cluster,
                                        AbstractUpgradeCatalog.CONFIGURATION_TYPE_RANGER_KNOX_PLUGIN_PROPERTIES,
                                        AbstractUpgradeCatalog.PROPERTY_RANGER_KNOX_PLUGIN_ENABLED);

                                Node gatewayNode = nodeList.item(0);
                                Element newProvider = topologyXml.createElement("provider");

                                Element role = topologyXml.createElement("role");
                                role.appendChild(topologyXml.createTextNode("authorization"));
                                newProvider.appendChild(role);

                                Element name = topologyXml.createElement("name");
                                if (rangerPluginEnabled) {
                                    name.appendChild(topologyXml.createTextNode("XASecurePDPKnox"));
                                } else {
                                    name.appendChild(topologyXml.createTextNode("AclsAuthz"));
                                }
                                newProvider.appendChild(name);

                                Element enabled = topologyXml.createElement("enabled");
                                enabled.appendChild(topologyXml.createTextNode("true"));
                                newProvider.appendChild(enabled);

                                gatewayNode.appendChild(newProvider);

                                DOMSource topologyDomSource = new DOMSource(root);
                                StringWriter writer = new StringWriter();
                                try {
                                    Transformer transformer = TransformerFactory.newInstance().newTransformer();
                                    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
                                    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                                    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
                                            "5");
                                    transformer.transform(topologyDomSource, new StreamResult(writer));
                                } catch (TransformerConfigurationException e) {
                                    e.printStackTrace();
                                    LOG.error(
                                            "Unable to create transformer instance, to convert Document(XML) to String. "
                                                    + e);
                                    return;
                                } catch (TransformerException e) {
                                    e.printStackTrace();
                                    LOG.error("Unable to transform Document(XML) to StringWriter. " + e);
                                    return;
                                }

                                content = writer.toString();
                                Map<String, String> updates = Collections.singletonMap(CONTENT_PROPERTY,
                                        content);
                                updateConfigurationPropertiesForCluster(cluster, TOPOLOGY_CONFIG, updates, true,
                                        false);
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:org.apache.cocoon.components.repository.impl.WebDAVRepository.java

public boolean saveContent(String uri, Node node) {

    try {/* w  w  w .  j  a  v  a2 s  .co m*/
        Properties format = new Properties();
        format.put(OutputKeys.METHOD, "xml");
        format.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
        return this.saveContent(uri, XMLUtils.serializeNode(node, format));

    } catch (ProcessingException pe) {
        this.getLogger().error("Error saving dom to: " + this.repoBaseUrl + uri, pe);
    }

    return false;
}

From source file:org.apache.cocoon.components.repository.impl.WebDAVRepositoryPropertyHelper.java

public boolean setProperty(String uri, String name, String namespace, Node value) {

    try {/* w  ww.  j  av a2  s. c  o m*/
        Properties format = new Properties();
        format.put(OutputKeys.METHOD, "xml");
        format.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
        return this.setProperty(uri, name, namespace, XMLUtils.serializeNode(value, format));

    } catch (ProcessingException pe) {
        this.getLogger().error("Error serializing node " + value, pe);
    }

    return false;
}