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:org.openmrs.module.casereport.CdaDocumentGenerator.java

/**
 * Generates and returns a CDA document for the specified report form
 * /* w w w  .j  a v a 2 s .c  om*/
 * @param reportForm
 * @return the generated CDA document
 * @should generate a CDA document
 */
public String generate(CaseReportForm reportForm) throws Exception {
    //cdaMessage = StringUtils.replace(cdaMessage, getPlaceHolder("triggerList"), triggerList);
    //cdaMessage = StringUtils.replace(cdaMessage, getPlaceHolder("dateSubmitted"), DATE_FORMATTER.format(new Date()));
    //String oid1 = "2.25." + new BigInteger(reportForm.getReportUuid().getBytes());
    //String oid2 = "2.25." + new BigInteger(UUID.randomUUID().toString().getBytes())
    ClinicalDocument cdaDocument = new ClinicalDocument();
    cdaDocument.setRealmCode(new SET<CS<BindingRealm>>(
            new CS<BindingRealm>(BindingRealm.UniversalRealmOrContextUsedInEveryInstance)));
    cdaDocument.setTypeId(TYPE_ID_ROOT, EXTENSION);
    cdaDocument.setTemplateId(Arrays.asList(new II(TEMPLATE_ID_ROOT)));
    cdaDocument.setId(reportForm.getReportUuid());
    cdaDocument.setCode(new CE<String>(DOCUMENT_CODE, CODE_SYSTEM_LOINC, CODE_SYSTEM_NAME_LOINC, null,
            LOINC_DOCUMENT_NAME, null));
    cdaDocument.setTitle(TITLE);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(reportForm.getReportDate());
    cdaDocument.setEffectiveTime(calendar);
    cdaDocument.setConfidentialityCode(x_BasicConfidentialityKind.Normal);
    cdaDocument.setLanguageCode(LANGUAGE_CODE);
    cdaDocument.getRecordTarget().add(CdaUtil.createRecordTarget(reportForm));
    cdaDocument.getAuthor().add(CdaUtil.createAuthor(reportForm));
    cdaDocument.setComponent(CdaUtil.createComponent(reportForm));

    XmlIts1Formatter fmtr = new XmlIts1Formatter();
    //This instructs the XML ITS1 Formatter we want to use CDA datatypes
    fmtr.getGraphAides().add(new DatatypeFormatter(R1FormatterCompatibilityMode.ClinicalDocumentArchitecture));
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    fmtr.graph(out, cdaDocument);

    //Use a Transformer for output the cda in a pretty format
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputStream inputStream = new ByteArrayInputStream(out.toByteArray());
    Document doc = builder.parse(inputStream);

    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    StreamResult result = new StreamResult(new ByteArrayOutputStream());
    transformer.transform(new DOMSource(doc), result);

    return result.getOutputStream().toString();
}

From source file:org.openmrs.module.hl7query.util.ExceptionUtil.java

/**
 * /*from   ww w  .  j  a v a  2s . c  o  m*/
 * @param error
 *       The error message object which contains the appopriate error message description and the error code
 * @param segment
 *       An additional (optional) string used to contain additional details (etc. which parameter is causing the error)
 * @return
 *       An appopriately formed error message object containing details of  the error
 * This message is triggered is the user had wanted the response hl7 message to be in pipe delimited format
 */
private static Object writeXmlMessage(ErrorDetailsEnum error, Object segment) {
    String xmlString = null;
    String errorDescription = null;
    String stackTrace = null;
    try {
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.newDocument();

        //create the root element and add it to the document
        Element root = doc.createElement("error");
        doc.appendChild(root);

        //create child element, add an attribute, and add to root
        Element errorMsg = doc.createElement("errorMessage");
        root.appendChild(errorMsg);

        if (segment != null) {
            if (segment instanceof String) {
                errorDescription = error.getMessage().toString() + " " + segment;
            } else if (segment instanceof Exception) {
                errorDescription = error.getMessage().toString() + " "
                        + (ExceptionUtils.getRootCauseMessage((Exception) segment)).toString();
                stackTrace = ExceptionUtils.getFullStackTrace((Exception) segment);
            }
        } else {
            errorDescription = error.getMessage().toString();
        }

        //add a text element to the child               
        Text errorText = doc.createTextNode(errorDescription);
        errorMsg.appendChild(errorText);

        if (stackTrace != null) {
            Element errorTrace = doc.createElement("staceTrace");
            root.appendChild(errorTrace);

            Text stackTraceText = doc.createTextNode(stackTrace);
            errorTrace.appendChild(stackTraceText);
        }

        //create child element, add an attribute, and add to root
        Element errorCode = doc.createElement("errorCode");
        root.appendChild(errorCode);

        //add a text element to the child
        Text errorCodeText = doc.createTextNode(Integer.toString(error.getCode()));
        errorCode.appendChild(errorCodeText);

        //set up a transformer
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");

        //create string from xml tree
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        trans.transform(source, result);
        xmlString = sw.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return xmlString;
}

From source file:org.openmrs.module.metadatasharing.converter.BaseConverter.java

protected static String toString(Node doc) throws SerializationException {
    try {// w  w w. j a  va  2 s . com
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StreamResult result = new StreamResult(new StringWriter());
        transformer.transform(new DOMSource(doc), result);
        return result.getWriter().toString();
    } catch (Exception e) {
        throw new SerializationException(e);
    }
}

From source file:org.openmrs.projectbuendia.webservices.rest.XmlTestUtil.java

/**
 * Converts an XML document into a string, applying indentation. First all elements have
 * their text//w  w w  .j  a  v  a  2  s  . com
 * content trimmed, just for simplicity.
 */
static String toIndentedString(Document doc) throws TransformerException {
    for (Element element : toElementIterable(doc.getElementsByTagName("*"))) {
        for (Node node : toIterable(element.getChildNodes())) {
            if (node.getNodeType() == Node.TEXT_NODE) {
                node.setNodeValue(node.getNodeValue().trim());
            }
        }
    }
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

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

From source file:org.opentox.jaqpot3.qsar.util.PMMLProcess.java

private static String getNodeFromXML(String xml) throws JaqpotException {
    String res = "";
    try {//www.  j a v  a  2 s  . co  m
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
        Document doc = docBuilder.parse(bis);

        // XPath to retrieve the content of the <FamilyAnnualDeductibleAmount> tag
        XPath xpath = XPathFactory.newInstance().newXPath();
        String expression = "/PMML/TransformationDictionary";
        Node node = (Node) xpath.compile(expression).evaluate(doc, XPathConstants.NODE);

        StreamResult xmlOutput = new StreamResult(new StringWriter());
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(new DOMSource(node), xmlOutput);
        res = xmlOutput.getWriter().toString();

    } catch (Exception ex) {
        String message = "Unexpected exception was caught while generating"
                + " the PMML representaition of a trained model.";
        logger.error(message, ex);
        throw new JaqpotException(message, ex);
    }

    return res;
}

From source file:org.oryxeditor.server.BPELImporter.java

/**
 * The POST request./*from  www .j a  v  a2 s  .  co m*/
 */
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException {
    // No isMultipartContent => Error
    final boolean isMultipartContent = ServletFileUpload.isMultipartContent(req);
    if (!isMultipartContent) {
        printError(res, "No Multipart Content transmitted.");
        return;
    }

    // Get the uploaded file
    final FileItemFactory factory = new DiskFileItemFactory();
    final ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
    servletFileUpload.setSizeMax(-1);
    final List<?> items;
    try {
        items = servletFileUpload.parseRequest(req);
        if (items.size() != 1) {
            printError(res, "Not exactly one File.");
            return;
        }
    } catch (FileUploadException e) {
        handleException(res, e);
        return;
    }

    // === prepare the bpel source ===
    // Get filename and content
    final FileItem fileItem = (FileItem) items.get(0);
    final String fileName = fileItem.getName();

    if (!fileName.endsWith(".bpel")) {
        printError(res, "No file with .bepl extension uploaded.");
        return;
    }

    final String fileContent = fileItem.getString();

    // do a pre-processing on this bpel source
    // in this preprocessor the following works will be done:
    //     1. mark all node stencil sets with the attribute "isNodeStencilSet"
    //         mark all edge stencil sets with the attribute "isEdgeStencilSet"
    //         in order to avoid the prefix problem
    //     2. calculate the bounds of each shape
    //      3. generate for each shape a ID
    //     4. move the <link> elements from <links> element to
    //         top of the root <process> element, and record linkID
    //         as the value of element <outgoing> under the corresponding
    //         activity, so they could be easier to handle in BPEL2eRDF.xslt
    //      5. integrate the first <condition> and <activity> element
    //         under a If-block into a <elseIF> element, so they
    //         they could be easier to transform in BPEL2eRDF.xslt
    //      6. transform the value of attribute "opaque" from "yes" to "true"
    final String newContent = preprocessSource(res, fileContent);

    log.fine("newContent:");
    log.fine(newContent);

    // Get the input stream   
    final InputStream inputStream = new ByteArrayInputStream(newContent.getBytes());

    // Get the bpel source
    final Source bpelSource = new StreamSource(inputStream);

    // === prepare the xslt source ===
    // BPEL2eRDF XSLT source
    final String xsltFilename = getServletContext().getRealPath("/xslt/BPEL2eRDF.xslt");
    //       final String xsltFilename = System.getProperty("catalina.home") + "/webapps/oryx/xslt/BPEL2eRDF.xslt";
    final File bpel2eRDFxsltFile = new File(xsltFilename);
    final Source bpel2eRDFxsltSource = new StreamSource(bpel2eRDFxsltFile);

    // Transformer Factory
    final TransformerFactory transformerFactory = TransformerFactory.newInstance();

    // === Get the eRDF result ===
    String resultString = null;
    try {
        Transformer transformer = transformerFactory.newTransformer(bpel2eRDFxsltSource);
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StringWriter writer = new StringWriter();
        transformer.transform(bpelSource, new StreamResult(writer));
        resultString = writer.toString();
    } catch (Exception e) {
        handleException(res, e);
        return;
    }

    log.fine("reslut-XML");
    log.fine(resultString);

    if (resultString == null) {
        printResponse(res, "transformation error");
    }

    Repository rep = new Repository("");
    resultString = rep.erdfToJson(resultString, getServletContext());

    log.fine("reslut-json");
    log.fine(resultString);

    printResponse(res, resultString);
}

From source file:org.ow2.proactive.scheduler.common.job.factories.Job2XMLTransformer.java

/**
 * Creates the xml representation of the job in argument
 *
 * @throws TransformerException/* w ww  .j a v  a  2 s. c  om*/
 * @throws ParserConfigurationException
 */
public InputStream jobToxml(TaskFlowJob job) throws TransformerException, ParserConfigurationException {
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
    Document doc = docBuilder.newDocument();
    doc.setXmlStandalone(true);

    // create the xml tree corresponding to this job
    Element rootJob = createRootJobElement(doc, job);
    doc.appendChild(rootJob);

    // set up a transformer
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans = transfac.newTransformer();
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    // If the encoding property is set on the client JVM, use it (it has to match the server-side encoding),
    // otherwise use UTF-8
    if (PASchedulerProperties.FILE_ENCODING.isSet()) {
        trans.setOutputProperty(OutputKeys.ENCODING, PASchedulerProperties.FILE_ENCODING.getValueAsString());
    } else {
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    }
    trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

    // write the xml
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(baos);
    DOMSource source = new DOMSource(doc);
    trans.transform(source, result);
    byte[] array = baos.toByteArray();
    return new ByteArrayInputStream(array);
}

From source file:org.parosproxy.paros.extension.newreport.ReportGenerator.java

public static String getDebugXMLString(Document doc) throws TransformerException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    return writer.getBuffer().toString().replaceAll("\n|\r", "");
}

From source file:org.patientview.patientview.EmailUtils.java

private static String getNodeAsString(Node node) {
    String nodeAsString = "";
    try {/*  w  w w .  jav a 2s. c o  m*/
        // Set up the output transformer
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer trans = transformerFactory.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");

        // Print the DOM node

        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(node);
        trans.transform(source, result);
        String xmlString = sw.toString();

        nodeAsString += xmlString;
    } catch (TransformerException e) {
        LOGGER.error("Failed to transform node because {}.", e.getMessage());
        if (LOGGER.isDebugEnabled()) {
            e.printStackTrace();
        }
        // Just return the blank string
    }

    return nodeAsString;
}

From source file:org.pentaho.di.core.xml.XMLHandler.java

public static String formatNode(Node node) throws KettleXMLException {
    StringWriter sw = new StringWriter();
    try {/*  w w w .j  a va  2 s .  c  o m*/
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        t.transform(new DOMSource(node), new StreamResult(sw));
    } catch (Exception e) {
        throw new KettleXMLException("Unable to format Node as XML", e);
    }
    return sw.toString();
}