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.apache.cocoon.components.source.impl.WebDAVSource.java

/**
 * Sets a property for a source./*from w  w w  .  j a v  a 2  s  .c o  m*/
 *
 * @param sourceproperty Property of the source
 *
 * @throws SourceException If an exception occurs during this operation
 */
public void setSourceProperty(SourceProperty sourceproperty) throws SourceException {

    initResource(WebdavResource.NOACTION, DepthSupport.DEPTH_0);

    try {
        Node node = null;
        NodeList list = sourceproperty.getValue().getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            if ((list.item(i) instanceof Text && !"".equals(list.item(i).getNodeValue()))
                    || list.item(i) instanceof Element) {

                node = list.item(i);
                break;
            }
        }

        Properties format = new Properties();
        format.put(OutputKeys.METHOD, "xml");
        format.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
        String prop = XMLUtils.serializeNode(node, format);

        this.resource.proppatchMethod(new PropertyName(sourceproperty.getNamespace(), sourceproperty.getName()),
                prop, true);

    } catch (HttpException e) {
        final String message = "Unable to set property. Server responded " + e.getReasonCode() + " ("
                + e.getReason() + ") - " + e.getMessage();
        getLogger().debug(message);
        throw new SourceException("Could not set property ", e);
    } catch (Exception e) {
        throw new SourceException("Could not set property ", e);
    }
}

From source file:org.apache.cocoon.serialization.AbstractTextSerializer.java

/**
 * Set the configurations for this serializer.
 *///from   w w  w .  j a  va 2  s .  c  o m
public void configure(Configuration conf) throws ConfigurationException {
    // configure buffer size
    //   Configuration bsc = conf.getChild("buffer-size", false);
    //   if(null != bsc)
    //    outputBufferSize = bsc.getValueAsInteger(DEFAULT_BUFFER_SIZE);

    // configure xalan
    String cdataSectionElements = conf.getChild("cdata-section-elements").getValue(null);
    String dtPublic = conf.getChild("doctype-public").getValue(null);
    String dtSystem = conf.getChild("doctype-system").getValue(null);
    String encoding = conf.getChild("encoding").getValue(null);
    String indent = conf.getChild("indent").getValue(null);
    String mediaType = conf.getChild("media-type").getValue(null);
    String method = conf.getChild("method").getValue(null);
    String omitXMLDeclaration = conf.getChild("omit-xml-declaration").getValue(null);
    String standAlone = conf.getChild("standalone").getValue(null);
    String version = conf.getChild("version").getValue(null);

    final StringBuffer buffer = new StringBuffer();

    if (cdataSectionElements != null) {
        format.put(OutputKeys.CDATA_SECTION_ELEMENTS, cdataSectionElements);
        buffer.append(";cdata-section-elements=").append(cdataSectionElements);
    }
    if (dtPublic != null) {
        format.put(OutputKeys.DOCTYPE_PUBLIC, dtPublic);
        buffer.append(";doctype-public=").append(dtPublic);
    }
    if (dtSystem != null) {
        format.put(OutputKeys.DOCTYPE_SYSTEM, dtSystem);
        buffer.append(";doctype-system=").append(dtSystem);
    }
    if (encoding != null) {
        format.put(OutputKeys.ENCODING, encoding);
        buffer.append(";encoding=").append(encoding);
    }
    if (indent != null) {
        format.put(OutputKeys.INDENT, indent);
        buffer.append(";indent=").append(indent);
    }
    if (mediaType != null) {
        format.put(OutputKeys.MEDIA_TYPE, mediaType);
        buffer.append(";media-type=").append(mediaType);
    }
    if (method != null) {
        format.put(OutputKeys.METHOD, method);
        buffer.append(";method=").append(method);
    }
    if (omitXMLDeclaration != null) {
        format.put(OutputKeys.OMIT_XML_DECLARATION, omitXMLDeclaration);
        buffer.append(";omit-xml-declaration=").append(omitXMLDeclaration);
    }
    if (standAlone != null) {
        format.put(OutputKeys.STANDALONE, standAlone);
        buffer.append(";standalone=").append(standAlone);
    }
    if (version != null) {
        format.put(OutputKeys.VERSION, version);
        buffer.append(";version=").append(version);
    }

    if (buffer.length() > 0) {
        this.cachingKey = buffer.toString();
    }

    String tFactoryClass = conf.getChild("transformer-factory").getValue(null);
    if (tFactoryClass != null) {
        try {
            this.tfactory = (SAXTransformerFactory) ClassUtils.newInstance(tFactoryClass);
            if (getLogger().isDebugEnabled()) {
                getLogger().debug("Using transformer factory " + tFactoryClass);
            }
        } catch (Exception e) {
            throw new ConfigurationException("Cannot load transformer factory " + tFactoryClass, e);
        }
    } else {
        // Standard TrAX behaviour
        this.tfactory = (SAXTransformerFactory) TransformerFactory.newInstance();
    }
    tfactory.setErrorListener(new TraxErrorHandler(getLogger()));

    // Check if we need namespace as attributes.
    try {
        if (needsNamespacesAsAttributes()) {
            // Setup a correction pipe
            this.namespacePipe = new NamespaceAsAttributes();
            this.namespacePipe.enableLogging(getLogger());
        }
    } catch (Exception e) {
        getLogger().warn("Cannot know if transformer needs namespaces attributes - assuming NO.", e);
    }
}

From source file:org.apache.droids.tika.TikaHtmlParser.java

@Override
public TikaParse parse(ContentEntity entity, Task task) throws IOException, DroidsException {
    // Init Tika objects
    org.apache.tika.parser.Parser parser = new AutoDetectParser();
    Metadata metadata = new Metadata();

    String charset = entity.getCharset();
    if (charset == null) {
        charset = "UTF-8";
    }/*from w  w w . j ava  2s .  co  m*/

    StringWriter dataBuffer = new StringWriter();
    StringWriter bodyBuffer = new StringWriter();
    StringWriter mainContentBuffer = new StringWriter();

    SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler xmlHandler;
    try {
        xmlHandler = factory.newTransformerHandler();
    } catch (TransformerConfigurationException e) {
        throw new DroidsException(e);
    }
    xmlHandler.getTransformer().setOutputProperty(OutputKeys.METHOD, "xml");
    xmlHandler.setResult(new StreamResult(dataBuffer));

    BoilerpipeContentHandler mainContentHandler = new BoilerpipeContentHandler(mainContentBuffer);
    BodyContentHandler bodyHandler = new BodyContentHandler(bodyBuffer);
    LinkContentHandler linkHandler = new LinkContentHandler();

    TeeContentHandler parallelHandler = new TeeContentHandler(xmlHandler, mainContentHandler, bodyHandler,
            linkHandler);

    InputStream instream = entity.obtainContent();
    try {
        parser.parse(instream, parallelHandler, metadata, new ParseContext());

        ArrayList<Link> extractedTasks = new ArrayList<Link>();
        if (task instanceof Link) {
            int depth = task.getDepth() + 1;
            for (org.apache.tika.sax.Link tikaLink : linkHandler.getLinks()) {
                try {
                    URI uri = new URI(tikaLink.getUri());
                    // Test to see if the scheme is empty
                    // This would indicate a relative URL, so resolve it against the task URI
                    if (uri.getScheme() == null) {
                        uri = ((Link) task).getURI().resolve(uri);
                    }
                    extractedTasks.add(new LinkTask((Link) task, uri, depth, tikaLink.getText()));
                } catch (URISyntaxException e) {
                    if (log.isWarnEnabled()) {
                        log.warn("URI not valid: " + tikaLink.getUri());
                    }
                }
            }
        }
        return new TikaParseImpl(dataBuffer.toString(), extractedTasks, bodyBuffer.toString(),
                mainContentBuffer.toString(), metadata);
    } catch (SAXException ex) {
        throw new DroidsException("Failure parsing document " + task.getId(), ex);
    } catch (TikaException ex) {
        throw new DroidsException("Failure parsing document " + task.getId(), ex);
    } finally {
        instream.close();
    }
}

From source file:org.apache.hadoop.gateway.filter.rewrite.impl.html.HtmlFilterReaderBaseTest.java

public void dump(Node node, Writer writer) throws TransformerException {
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.METHOD, "xml");
    t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    t.transform(new DOMSource(node), new StreamResult(writer));
}

From source file:org.apache.hadoop.gateway.filter.rewrite.impl.html.HtmlFilterReaderBaseTest.java

public void dump(Node node, OutputStream stream) throws TransformerException {
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.METHOD, "xml");
    t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    t.transform(new DOMSource(node), new StreamResult(stream));
}

From source file:org.apache.jackrabbit.webdav.client.methods.XmlRequestEntity.java

public XmlRequestEntity(Document xmlDocument) throws IOException {
    super();//w  ww  .  ja va 2  s . c  o  m
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        transformer.transform(new DOMSource(xmlDocument), new StreamResult(out));
    } catch (TransformerException e) {
        log.error("XML serialization failed", e);
        IOException exception = new IOException("XML serialization failed");
        exception.initCause(e);
        throw exception;
    }

    delegatee = new StringRequestEntity(out.toString(), "text/xml", "UTF-8");
}

From source file:org.apache.shindig.gadgets.parse.ParseTreeSerializerBenchmark.java

private void timeParseDomSerialize(GadgetHtmlParser parser) throws GadgetException {
    org.w3c.dom.Document document = parser.parseDom(content);
    try {/*from   w  ww.  j  a  v  a 2 s  .c om*/
        long parseStart = System.currentTimeMillis();
        for (int i = 0; i < numRuns; ++i) {
            HtmlSerialization.serialize(document);
        }
        long parseMillis = System.currentTimeMillis() - parseStart;

        output("Serializing [" + parseMillis + " ms total: " + ((double) parseMillis) / numRuns + "ms/run]");
    } catch (Exception e) {
        throw new GadgetException(GadgetException.Code.HTML_PARSE_ERROR, e);
    }

    try {
        // Create an "identity" transformer - copies input to output
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.METHOD, "html");

        long parseStart = System.currentTimeMillis();
        for (int i = 0; i < numRuns; ++i) {
            StringWriter sw = new StringWriter((content.length() * 11) / 10);
            t.transform(new DOMSource(document), new StreamResult(sw));
            sw.toString();
        }
        long parseMillis = System.currentTimeMillis() - parseStart;

        output("Serializing DOM Transformer [" + parseMillis + " ms total: " + ((double) parseMillis) / numRuns
                + "ms/run]");

    } catch (Exception e) {
        throw new GadgetException(GadgetException.Code.HTML_PARSE_ERROR, e);
    }
}

From source file:org.apache.sling.its.servlets.ItsServlet.java

@Override
protected final void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {
    if (ResourceUtil.isNonExistingResource(request.getResource())) {
        LOG.error("No resource found for path: " + request.getResource().getPath());
        response.getWriter().write("500: No resource found for path: " + request.getResource().getPath());
        return;/*ww w  .  j av a2 s. c o  m*/
    }

    this.isHtml = request.getRequestPathInfo().getExtension().equals("html");

    try {
        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements.
        final Document doc = docBuilder.newDocument();
        createDocument(request.getResource(), doc);

        // make sure the encoding is set before getWriter() is called.
        if (this.isHtml) {
            response.setCharacterEncoding(CharEncoding.UTF_8);
            response.setContentType(MimeTypeMapper.HTML_MIME_TYPE);
            response.getWriter().write("<!DOCTYPE html>");
        } else {
            response.setCharacterEncoding(CharEncoding.UTF_8);
            response.setContentType(MimeTypeMapper.XML_MIME_TYPE);
        }

        // write the content into xml file.
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer();
        final DOMSource source = new DOMSource(doc);
        final StreamResult result = new StreamResult(response.getWriter());

        // set the correct properties for the xml or html file.
        transformer.setOutputProperty(OutputKeys.METHOD, Namespaces.XML_NS_PREFIX);
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        // Output the xml or html file.
        transformer.transform(source, result);
    } catch (final ParserConfigurationException pce) {
        LOG.error("Failed to create DocumentBuilder. Stack Trace: ", pce);
    } catch (final TransformerException tfe) {
        LOG.error("Failed to transform the document. Stack Trace: ", tfe);
    }
}

From source file:org.apache.sling.stanbol.ui.StanbolResourceViewer.java

private void setContent(Node jcrNode, String newContent) throws IOException, RepositoryException {

    try {/*w w w. j a  v a2  s .  c  o m*/
        Document doc = Utils.getXMLDocument(jcrNode);
        Element docElem = doc.getDocumentElement();
        if (docElem.getNodeName().equalsIgnoreCase("html")) {
            Element newBody = parseBody(newContent);
            Element body = (Element) doc.getElementsByTagName("body").item(0);
            org.w3c.dom.Node importedNewBody = doc.importNode(newBody, true);
            body.getParentNode().replaceChild(importedNewBody, body);
        } else {
            InputSource inputSource = new InputSource(new StringReader(newContent));
            Document newContentDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(inputSource);
            docElem = newContentDoc.getDocumentElement();
        }
        DOMSource domSource = new DOMSource(docElem);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        //StringWriter out = new StringWriter();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        StreamResult streamResult = new StreamResult(baos);
        transformer.transform(domSource, streamResult);
        //jcrNode.setProperty("jcr:content/jcr:data", out.toString());
        jcrNode.getProperty("jcr:content/jcr:data").setValue(new String(baos.toByteArray(), "utf-8"));
        jcrNode.save();
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException(e);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.solr.handler.dataimport.CustomTikaEntityProcessor.java

private static ContentHandler getHtmlHandler(Writer writer) throws TransformerConfigurationException {
    SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory.newInstance();
    TransformerHandler handler = factory.newTransformerHandler();
    handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "html");
    handler.setResult(new StreamResult(writer));
    return new ContentHandlerDecorator(handler) {
        @Override/*from  w ww  .j  a  v a  2  s  .  c  o  m*/
        public void startElement(String uri, String localName, String name, Attributes atts)
                throws SAXException {
            if (XHTMLContentHandler.XHTML.equals(uri)) {
                uri = null;
            }
            if (!"head".equals(localName)) {
                super.startElement(uri, localName, name, atts);
            }
        }

        @Override
        public void endElement(String uri, String localName, String name) throws SAXException {
            if (XHTMLContentHandler.XHTML.equals(uri)) {
                uri = null;
            }
            if (!"head".equals(localName)) {
                super.endElement(uri, localName, name);
            }
        }

        @Override
        public void startPrefixMapping(String prefix, String uri) {/* no op */
        }

        @Override
        public void endPrefixMapping(String prefix) {/* no op */
        }
    };
}