Example usage for javax.xml.transform OutputKeys OMIT_XML_DECLARATION

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

Introduction

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

Prototype

String OMIT_XML_DECLARATION

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

Click Source Link

Document

omit-xml-declaration = "yes" | "no".

Usage

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

public static String xmlToString(Element doc) {
    StringWriter sw = new StringWriter();
    try {//from w  w  w.  j  av a2s .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:com.idiominc.ws.opentopic.fo.i18n.PreprocessorTask.java

@Override
public void execute() throws BuildException {
    checkParameters();/*www  .jav  a 2 s.  co  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:ApplyXPathJAXP.java

static void printNode(Node node) throws Exception {
    if (isTextNode(node)) {
        System.out.println(node.getNodeValue());
    } else {/*from  w  w w  .j a va  2  s .c om*/
        // Set up an identity transformer to use as serializer.
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        serializer.transform(new DOMSource(node), new StreamResult(new OutputStreamWriter(System.out)));
    }

}

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  w w w  .ja v a  2 s  .  c  om
    String xmlString = sw.toString();
    return xmlString;
}

From source file:au.edu.rmit.GalagoSearchClient.java

protected String getElementContent(Element elem) throws TransformerException {
    StringWriter writer = new StringWriter();
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.transform(new DOMSource(elem), new StreamResult(writer));
    return writer.toString();
}

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   www .j ava  2  s. c  o m*/
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:com.fluxit.camel.component.n4.N4Producer.java

/**
 * TODO JAVADOC!!!!//from  ww  w  . j  av  a 2s .c  o m
 */
public void process(Exchange exchange) throws Exception {

    Object resultBody = null;

    LOG.debug("Exchange en N4 Producer: {0}", exchange.getIn().getBody());

    XsltUriResolver uriResolver = new XsltUriResolver(exchange.getContext().getClassResolver(), null);

    if (endpoint.getUriXSLTInput() != null && endpoint.getTransformerForInput() != null) {
        LOG.trace("Creando transformer para input de XSLT");
        Transformer transformer = TransformerFactory.newInstance()
                .newTransformer(uriResolver.resolve(endpoint.getUriXSLTInput(), null));
        // omito la declaracion de XML en la salida
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        endpoint.setTransformerForInput(transformer);
    }

    if (endpoint.getProviderType().equals(N4Endpoint.FILTER_PROVIDER)) {

        String httpQuery = "";

        if (endpoint.getUriMapInput() != null) {

            Object body = exchange.getIn().getBody();
            MapperURITransformForFilter inputTransformer = new MapperURITransformForFilter();
            httpQuery = inputTransformer.transformURI(endpoint.getUriMapInput(), body);

        } else if (endpoint.getUriXSLTInput() != null) {

            if ((exchange.getIn().getBody() instanceof List)) {
                throw new IllegalArgumentException(
                        "Como cuerpo del mensaje existe una lista pero no existe mapa de conversion en la property uriMapInput ");
            }

            // TODO chequear que si viene en modo POJO no se puede hacer
            StringWriter writer = new StringWriter();
            Source body = exchange.getIn().getBody(Source.class);
            endpoint.getTransformerForInput().transform(body, new StreamResult(writer));
            httpQuery = writer.toString();
            LOG.debug("La query luego de la transformacion XSLT es {0}", httpQuery);
        }

        // TODO VER QU USAR PARA CREAR LA URL CON UN BUILDER
        // FIXME CAMBIAR LOS VALORES DE SCOPE POR PROPERTIES DEL SISTEMA
        String url = new StringBuffer(endpoint.getN4EndpointURI()).append("?").append("filtername=")
                .append(endpoint.getFilterName()).append("&").append(httpQuery)
                .append("&operatorId=ICT&complexId=TPL&facilityId=PLP&yardId=ZPB").toString();

        LOG.debug("Se invocar a la URL {0} con el usuario {1} y password {2}", url, endpoint.getN4User(),
                endpoint.getN4Pass());

        HttpClient client = createHttpClient();

        // Create a method instance.
        GetMethod method = new GetMethod(url);

        resultBody = invokeHttp(url, client, method);

        // TODO hacer la transformacin
        if (endpoint.getUriXSLTOutput() != null) {

            if (endpoint.getTransformerForOutput() == null) {

                LOG.trace("Creando transformer para output de XSLT");
                Transformer transformer = TransformerFactory.newInstance()
                        .newTransformer(uriResolver.resolve(endpoint.getUriXSLTOutput(), null));
                transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                endpoint.setTransformerForOutput(transformer);
            }

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            endpoint.getTransformerForOutput().transform(new StreamSource((InputStream) resultBody),
                    new StreamResult(outputStream));

            resultBody = new ByteArrayInputStream(outputStream.toByteArray());

            // TODO chequear que el defaultCharset este bien
            LOG.debug("Resultado de la transformacion XSLT de salida: {0}",
                    new String(outputStream.toByteArray(), Charset.defaultCharset()));

        } // end if de transformacion XSLT output

        if (endpoint.getClassSerialization() != null) {
            JAXBElement<?> element = endpoint.getJaxbContext().createUnmarshaller().unmarshal(
                    new StreamSource((InputStream) resultBody),
                    Class.forName(endpoint.getClassSerialization()));

            Object value = element.getValue();

            resultBody = value;

        } // end if de serializacion

    } else if (endpoint.getProviderType() == N4Endpoint.GENERIC_WS_PROVIDER) {
        // TODO hacer todo el procesamiento para el ws generico
    }

    exchange.getOut().setBody(resultBody);

}

From source file:com.sun.portal.portletcontainer.admin.PortletRegistryHelper.java

public static synchronized void writeFile(Document document, File file) throws PortletRegistryException {
    FileOutputStream output = null;
    try {/*from w ww . j  a v a2 s.  c  o m*/
        // Use a Transformer for output
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.ENCODING, CharEncoding.UTF_8);
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "5");

        DOMSource source = new DOMSource(document);
        // StreamResult result = new StreamResult(System.out);
        output = new FileOutputStream(file);
        StreamResult result = new StreamResult(output);
        transformer.transform(source, result);
    } catch (TransformerConfigurationException tce) {
        throw new PortletRegistryException(tce);
    } catch (TransformerException te) {
        throw new PortletRegistryException(te);
    } catch (Exception e) {
        throw new PortletRegistryException(e);
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException ex) {
                SilverTrace.warn("portlet", PortletRegistryHelper.class.getSimpleName() + ".writeFile()",
                        "root.EX_NO_MESSAGE", ex);
            }
        }
    }
}

From source file:hydrograph.ui.common.util.XMLUtil.java

/**
 * //w  w  w . j  a  v a2  s . c  om
 * Format given XML string
 * 
 * @param xmlString
 * @return String
 */
public static String formatXML(String xmlString) {

    try (Writer writer = new StringWriter()) {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(TRANSFORMER_INDENT_AMOUNT_KEY, INDENT_SPACE);
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        //initialize StreamResult with File object to save to file
        StreamResult result = new StreamResult(writer);

        Document xmlDoc = convertStringToDocument(xmlString);

        if (xmlDoc == null) {
            return xmlString;
        }

        DOMSource source = new DOMSource(xmlDoc);
        transformer.transform(source, result);
        return result.getWriter().toString();
    } catch (TransformerException e) {
        logger.debug("Unable to format XML string", e);
    } catch (IOException e) {
        logger.debug("Unable to format XML string", e);
    }

    return null;
}

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 a  2s  . c o m
 * @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;
}