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:ch.entwine.weblounge.bridge.oaipmh.util.XmlGen.java

private void write(OutputStream out) {
    try {/*  w w w .j a va 2 s.  c  o m*/
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(out);
        transformer.transform(source, result);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
}

From source file:eionet.gdem.qa.engines.SaxonImpl.java

@Override
protected void runQuery(XQScript script, OutputStream result) throws GDEMException {

    // Source sourceInput = null;
    // StringBuffer err_buf = new StringBuffer();

    Configuration config = new Configuration();

    // our own extension of Saxon's error listener to send feedback to the user
    SaxonListener listener = new SaxonListener();
    config.setErrorListener(listener);/*from  w  ww. j a v a  2s .c o  m*/
    config.setURIResolver(new QAURIResolver());

    config.setHostLanguage(Configuration.XQUERY);
    config.setLineNumbering(true);
    StaticQueryContext staticEnv = new StaticQueryContext(config);
    // staticEnv.setConfiguration(config);
    DynamicQueryContext dynamicEnv = new DynamicQueryContext(config);

    SaxonListener dynamicListener = new SaxonListener();
    dynamicEnv.setErrorListener(dynamicListener);

    Properties outputProps = new Properties();
    outputProps.setProperty(OutputKeys.INDENT, "no");
    outputProps.setProperty(OutputKeys.ENCODING, DEFAULT_ENCODING);
    // if the output is html, then use method="xml" in output, otherwise, it's not valid xml
    if (getOutputType().equals(HTML_CONTENT_TYPE)) {
        outputProps.setProperty(OutputKeys.METHOD, XML_CONTENT_TYPE);
    } else {
        outputProps.setProperty(OutputKeys.METHOD, getOutputType());
    }
    // add xml declaration only, if the output should be XML
    if (getOutputType().equals(XML_CONTENT_TYPE)) {
        outputProps.setProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    } else {
        outputProps.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    }
    String queriesPathURI = Utils.getURIfromPath(eionet.gdem.Properties.queriesFolder, true);
    if (queriesPathURI != null) {
        staticEnv.setBaseURI(queriesPathURI);
    }

    Reader queryReader = null;

    try {
        if (!Utils.isNullStr(script.getScriptSource())) {
            queryReader = new StringReader(script.getScriptSource());
        } else if (!Utils.isNullStr(script.getScriptFileName())) {
            queryReader = new FileReader(script.getScriptFileName());
        } else {
            throw new GDEMException("XQuery engine could not find script source or script file name!");
        }

        // handle xq Parameters, extract from Saxon code
        if (script.getParams() != null) {
            for (int p = 0; p < script.getParams().length; p++) {
                String arg = script.getParams()[p];
                int eq = arg.indexOf("=");
                if (eq < 1 || eq >= arg.length() - 1) {
                    throw new GDEMException("Bad param=value pair");
                    // handleError("Bad param=value pair", true);
                }
                String argname = arg.substring(0, eq);
                if (argname.startsWith("!")) {
                    // parameters starting with "!" are taken as output properties
                    outputProps.setProperty(argname.substring(1), arg.substring(eq + 1));
                } else if (argname.startsWith("+")) {
                    // parameters starting with "+" are taken as inputdocuments
                    // List sources = Transform.loadDocuments(arg.substring(eq+1), true, config);
                    // dynamicEnv.setParameter(argname.substring(1), sources);
                } else {
                    dynamicEnv.setParameter(argname, new StringValue(arg.substring(eq + 1)));
                }

            }
        }
        // compile XQuery
        XQueryExpression exp;
        try {
            exp = staticEnv.compileQuery(queryReader);
            staticEnv = exp.getStaticContext();
        } catch (net.sf.saxon.trans.XPathException e) {
            throw e;
        } catch (java.io.IOException e) {
            throw e;
        }

        try {
            // evaluating XQuery
            exp.run(dynamicEnv, new StreamResult(result), outputProps);
        } catch (net.sf.saxon.trans.XPathException e) {
            listener.error(e);
        }

    } catch (Exception e) {
        String errMsg = (listener.hasErrors() ? listener.getErrors() : e.toString());
        try {
            errMsg = parseErrors(errMsg, staticEnv);
        } catch (Exception ex) {
            LOGGER.error("Unable to parse exception string: " + ex.toString());
        }

        LOGGER.error("==== CATCHED EXCEPTION " + errMsg, e);
        throw new GDEMException(errMsg, e);
        // listener.error(e);
    } finally {
        if (queryReader != null) {
            try {
                queryReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (listener.hasErrors() || dynamicListener.hasErrors()) {
            String errMsg = listener.getErrors() + dynamicListener.getErrors();
            try {
                errMsg = parseErrors(errMsg, staticEnv);
            } catch (Exception ex) {
                LOGGER.error("Unable to parse exception string: " + ex.toString());
            }
            LOGGER.error(errMsg);
            throw new GDEMException(errMsg);
        }
    }
}

From source file:com.aurel.track.admin.customize.category.report.execute.ReportBeansToXML.java

/**
 * @param items/*from www. j a  va 2s . c o  m*/
 * @return
 */
public static void convertToXml(OutputStream outputStream, Document dom) {
    Transformer transformer = null;
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    } catch (TransformerConfigurationException e) {
        LOGGER.error(
                "Creating the transformer failed with TransformerConfigurationException: " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        return;
    }
    try {
        transformer.transform(new DOMSource(dom), new StreamResult(outputStream));
    } catch (TransformerException e) {
        LOGGER.error("Transform failed with TransformerException: " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
}

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

public static String xmlToString(Element doc) {
    StringWriter sw = new StringWriter();
    try {/*from   w  ww .  j a v  a2 s .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:it.unibas.spicy.persistence.xml.DAOXmlUtility.java

public void saveDOM(org.w3c.dom.Document document, String filename) throws DAOException {
    try {/*from   ww  w . j  a v a  2 s.c  o  m*/
        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: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:com.alfaariss.oa.util.configuration.handler.dummy.DummyConfigurationHandler.java

/**
 * Save the configuration to the screen.
 * @see IConfigurationHandler#saveConfiguration(org.w3c.dom.Document)
 *///  www. ja v  a2  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:org.alloy.metal.xml.merge.ImportProcessor.java

public List<ResourceInputStream> extract(List<ResourceInputStream> sources) throws MergeException {
    try {/*  www.j a  v a  2s .  c  o m*/
        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);
    }
}

From source file:com.bcmcgroup.flare.client.ClientUtil.java

/**
 * Convert a Document into a String//from   ww w .  ja  va  2  s.c  o m
 *
 * @param document           the Document to be converted to String
 * @param omitXmlDeclaration set to true if you'd like to omit the XML declaration, false otherwise
 * @return the String converted from a Document
 *
 */
public static String convertDocumentToString(Document document, boolean omitXmlDeclaration) {
    try {
        StringWriter stringWriter = new StringWriter();
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        Transformer transformer = transformerFactory.newTransformer();
        if (omitXmlDeclaration) {
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        } else {
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        }
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (TransformerException e) {
        logger.error("Transformer Exception when attempting to convert a document to a string. ");
    }
    return null;
}

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 v a  2 s.co 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);
}