Example usage for javax.xml.transform.stream StreamResult getWriter

List of usage examples for javax.xml.transform.stream StreamResult getWriter

Introduction

In this page you can find the example usage for javax.xml.transform.stream StreamResult getWriter.

Prototype

public Writer getWriter() 

Source Link

Document

Get the character stream that was set with setWriter.

Usage

From source file:cz.incad.vdkcommon.solr.Indexer.java

private String transformXML(String xml, String uniqueCode, String codeType, String identifier, boolean bohemika,
        String zdrojConf) throws Exception {
    LOGGER.log(Level.FINE, "Transforming {0} ...", identifier);
    StreamResult destStream = new StreamResult(new StringWriter());
    transformer.setParameter("uniqueCode", uniqueCode);
    transformer.setParameter("codeType", codeType);
    transformer.setParameter("bohemika", Boolean.toString(bohemika));
    transformer.setParameter("zdrojConf", zdrojConf);
    transformer.transform(new StreamSource(new StringReader(xml)), destStream);
    LOGGER.log(Level.FINE, "Sending to index ...");
    StringWriter sw = (StringWriter) destStream.getWriter();
    return sw.toString();
}

From source file:info.ajaxplorer.synchro.SyncJob.java

protected void logDocument(Document d) {
    try {//from  w ww  .  j a  va2s  . c o  m
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        //initialize StreamResult with File object to save to file
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(d);
        transformer.transform(source, result);
        String xmlString = result.getWriter().toString();
        Logger.getRootLogger().info(xmlString);
    } catch (Exception e) {
    }
}

From source file:jef.tools.XMLUtils.java

private static void output(Node node, StreamResult sr, String encoding, int indent, Boolean XmlDeclarion)
        throws IOException {
    if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        sr.getWriter().write(node.getNodeValue());
        sr.getWriter().flush();//from   w w  w . j a va2 s  .co  m
        return;
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = null;
    try {
        if (indent > 0) {
            try {
                tf.setAttribute("indent-number", indent);
                t = tf.newTransformer();
                // ?XML??XML?
                t.setOutputProperty(OutputKeys.INDENT, "yes");
            } catch (Exception e) {
            }
        } else {
            t = tf.newTransformer();
        }

        t.setOutputProperty(OutputKeys.METHOD, "xml");
        if (encoding != null) {
            t.setOutputProperty(OutputKeys.ENCODING, encoding);
        }
        if (XmlDeclarion == null) {
            XmlDeclarion = (node instanceof Document);
        }
        if (node instanceof Document) {
            Document doc = (Document) node;
            if (doc.getDoctype() != null) {
                t.setOutputProperty(javax.xml.transform.OutputKeys.DOCTYPE_PUBLIC,
                        doc.getDoctype().getPublicId());
                t.setOutputProperty(javax.xml.transform.OutputKeys.DOCTYPE_SYSTEM,
                        doc.getDoctype().getSystemId());
            }
        }
        if (XmlDeclarion) {
            t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        } else {
            t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        }
    } catch (Exception tce) {
        throw new IOException(tce);
    }
    DOMSource doms = new DOMSource(node);
    try {
        t.transform(doms, sr);
    } catch (TransformerException te) {
        IOException ioe = new IOException();
        ioe.initCause(te);
        throw ioe;
    }
}

From source file:com.maxl.java.aips2sqlite.RealExpertInfo.java

private String prettyFormat(String input) {
    try {/*from  w  ww.j  a  va2s.  c  o m*/
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Exception e) {
        throw new RuntimeException(e); // simple exception handling, please review it
    }
}

From source file:io.pyd.synchro.SyncJob.java

protected void logDocument(Document d) {
    try {//  w ww  . j a  v a 2 s .c  o m
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        // initialize StreamResult with File object to save to file
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(d);
        transformer.transform(source, result);
        String xmlString = result.getWriter().toString();
        Logger.getRootLogger().info(xmlString);
    } catch (Exception e) {
    }
}

From source file:lcmc.data.VMSXML.java

/** Convert xml node to the string. */
private void saveDomainXML(final String configName, final Node node, final String defineCommand) {
    String xml = null;//from w  w  w . j a v a  2 s  . c  o  m
    try {
        final Transformer transformer = TransformerFactory.newInstance().newTransformer();
        final StreamResult res = new StreamResult(new StringWriter());
        final DOMSource src = new DOMSource(node);
        transformer.transform(src, res);
        xml = res.getWriter().toString();
    } catch (final javax.xml.transform.TransformerException e) {
        e.printStackTrace();
        return;
    }
    if (xml != null) {
        host.getSSH().scp(xml, configName, "0600", true, defineCommand, null, null);
    }
}

From source file:com.cloud.network.resource.PaloAltoResource.java

private String prettyFormat(String input) {
    int indent = 4;
    try {//from  ww w .  j  ava 2  s .c o  m
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Throwable e) {
        try {
            Source xmlInput = new StreamSource(new StringReader(input));
            StringWriter stringWriter = new StringWriter();
            StreamResult xmlOutput = new StreamResult(stringWriter);
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.transform(xmlInput, xmlOutput);
            return xmlOutput.getWriter().toString();
        } catch (Throwable t) {
            return input;
        }
    }
}

From source file:com.ext.portlet.epsos.EpsosHelperService.java

public byte[] generateDispensationDocumentFromPrescription(byte[] bytes, List<ViewResult> lines,
        List<ViewResult> dispensedLines, SpiritUserClientDto doctor, User user) {
    byte[] bytesED = null;
    try {/*from  w ww  .  j  a va 2 s  .  c om*/
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document dom = db.parse(new ByteArrayInputStream(bytes));

        XPath xpath = XPathFactory.newInstance().newXPath();

        // TODO change effective time
        // TODO change language code to fit dispenser
        // TODO change OID, have to use country b OID
        // TODO author must be the dispenser not the prescriber
        // TODO custodian and legal authenticator should be not copied from ep doc
        // TODO

        // fixes 
        // First I have to check if exists in order not to create it
        fixNode(dom, xpath, "/ClinicalDocument/legalAuthenticator/assignedEntity/representedOrganization/addr",
                "state", "N/A");

        // add telecom to patient role
        fixNode(dom, xpath, "/ClinicalDocument/author/assignedAuthor/representedOrganization/addr", "state",
                "N/A");

        // add street Address Line
        fixNode(dom, xpath, "/ClinicalDocument/legalAuthenticator/assignedEntity/representedOrganization/addr",
                "streetAddressLine", "N/A");

        // add City
        fixNode(dom, xpath, "/ClinicalDocument/legalAuthenticator/assignedEntity/representedOrganization/addr",
                "city", "N/A");
        // add postalcode
        fixNode(dom, xpath, "/ClinicalDocument/legalAuthenticator/assignedEntity/representedOrganization/addr",
                "postalCode", "N/A");

        fixNode(dom, xpath, "/ClinicalDocument/author/assignedAuthor/representedOrganization/addr",
                "streetAddressLine", "N/A");

        fixNode(dom, xpath, "/ClinicalDocument/author/assignedAuthor/representedOrganization/addr", "city",
                "N/A");

        fixNode(dom, xpath, "/ClinicalDocument/author/assignedAuthor/representedOrganization/addr",
                "postalCode", "N/A");

        changeNode(dom, xpath, "/ClinicalDocument/author/assignedAuthor/representedOrganization", "name",
                "N/A");

        fixNode(dom, xpath,
                "/ClinicalDocument/component/structuredBody/component/section/entry/supply/entryRelationship/substanceAdministration/author/assignedAuthor/representedOrganization/addr",
                "postalCode", "N/A");

        String ful_ext = "";
        String ful_root = "";
        XPathExpression ful1 = xpath.compile("/ClinicalDocument/component/structuredBody/component/section/id");
        NodeList fulRONodes = (NodeList) ful1.evaluate(dom, XPathConstants.NODESET);

        if (fulRONodes.getLength() > 0) {
            for (int t = 0; t < fulRONodes.getLength(); t++) {
                Node AddrNode = fulRONodes.item(t);
                try {
                    ful_ext = AddrNode.getAttributes().getNamedItem("extension").getNodeValue() + "";
                    ful_root = AddrNode.getAttributes().getNamedItem("root").getNodeValue() + "";
                } catch (Exception e) {
                }
            }
        }

        // fix infullfillment
        XPathExpression rootNodeExpr = xpath.compile("/ClinicalDocument");
        Node rootNode = (Node) rootNodeExpr.evaluate(dom, XPathConstants.NODE);

        try {
            Node infulfilment = null;
            XPathExpression salRO = xpath.compile("/ClinicalDocument/inFulfillmentOf");
            NodeList salRONodes = (NodeList) salRO.evaluate(dom, XPathConstants.NODESET);
            if (salRONodes.getLength() == 0) {
                XPathExpression salAddr = xpath.compile("/ClinicalDocument/relatedDocument");
                NodeList salAddrNodes = (NodeList) salAddr.evaluate(dom, XPathConstants.NODESET);
                if (salAddrNodes.getLength() > 0) {
                    for (int t = 0; t < salAddrNodes.getLength(); t++) {
                        Node AddrNode = salAddrNodes.item(t);
                        Node order = dom.createElement("inFulfillmentOf");
                        //legalNode.appendChild(order);
                        /*
                         * <relatedDocument typeCode="XFRM">
                        *      <parentDocument>
                        *      <id extension="2601010002.pdf.ep.52105899467.52105899468:39" root="2.16.840.1.113883.2.24.2.30"/>
                        *                     </parentDocument>
                        *                  </relatedDocument>
                         * 
                         * 
                         */
                        //Node order1 = dom.createElement("order");
                        Node order1 = dom.createElement("relatedDocument");
                        Node parentDoc = dom.createElement("parentDocument");
                        addAttribute(dom, parentDoc, "typeCode", "XFRM");
                        order1.appendChild(parentDoc);

                        Node orderNode = dom.createElement("id");
                        addAttribute(dom, orderNode, "extension", ful_ext);
                        addAttribute(dom, orderNode, "root", ful_root);
                        parentDoc.appendChild(orderNode);
                        rootNode.insertBefore(order, AddrNode);
                        infulfilment = rootNode.cloneNode(true);

                    }
                }
            }
        } catch (Exception e) {
            _log.error("Error fixing node inFulfillmentOf ...");
        }

        XPathExpression Telecom = xpath
                .compile("/ClinicalDocument/author/assignedAuthor/representedOrganization");
        NodeList TelecomNodes = (NodeList) Telecom.evaluate(dom, XPathConstants.NODESET);
        if (TelecomNodes.getLength() == 0) {
            for (int t = 0; t < TelecomNodes.getLength(); t++) {
                Node TelecomNode = TelecomNodes.item(t);
                Node telecom = dom.createElement("telecom");
                addAttribute(dom, telecom, "use", "WP");
                addAttribute(dom, telecom, "value", "mailto:demo@epsos.eu");
                TelecomNode.insertBefore(telecom, TelecomNodes.item(0));
            }
        }

        // header xpaths
        XPathExpression clinicalDocExpr = xpath.compile("/ClinicalDocument");
        Node clinicalDocNode = (Node) clinicalDocExpr.evaluate(dom, XPathConstants.NODE);
        if (clinicalDocNode != null) {
            addAttribute(dom, clinicalDocNode, "xmlns", "urn:hl7-org:v3");
            addAttribute(dom, clinicalDocNode, "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            addAttribute(dom, clinicalDocNode, "xsi:schemaLocation",
                    "urn:hl7-org:v3 CDASchema/CDA_extended.xsd");
            addAttribute(dom, clinicalDocNode, "classCode", "DOCCLIN");
            addAttribute(dom, clinicalDocNode, "moodCode", "EVN");
        }

        XPathExpression docTemplateIdExpr = xpath.compile("/ClinicalDocument/templateId");
        XPathExpression docCodeExpr = xpath.compile("/ClinicalDocument/code[@codeSystemName='"
                + XML_LOINC_SYSTEM + "' and @codeSystem='" + XML_LOINC_CODESYSTEM + "']");
        XPathExpression docTitleExpr = xpath.compile("/ClinicalDocument/title");

        // change templateId / LOINC code / title to dispensation root code
        NodeList templateIdNodes = (NodeList) docTemplateIdExpr.evaluate(dom, XPathConstants.NODESET);
        if (templateIdNodes != null) {
            for (int t = 0; t < templateIdNodes.getLength(); t++) {
                Node templateIdNode = templateIdNodes.item(t);
                templateIdNode.getAttributes().getNamedItem("root").setNodeValue(XML_DISPENSATION_TEMPLATEID);

                if (t > 0)
                    templateIdNode.getParentNode().removeChild(templateIdNode); // remove extra templateId nodes
            }
        }
        Node codeNode = (Node) docCodeExpr.evaluate(dom, XPathConstants.NODE);
        if (codeNode != null) {
            if (codeNode.getAttributes().getNamedItem("code") != null)
                codeNode.getAttributes().getNamedItem("code").setNodeValue(XML_DISPENSATION_LOINC_CODE);
            if (codeNode.getAttributes().getNamedItem("displayName") != null)
                codeNode.getAttributes().getNamedItem("displayName").setNodeValue("eDispensation");
            if (codeNode.getAttributes().getNamedItem("codeSystemName") != null)
                codeNode.getAttributes().getNamedItem("codeSystemName")
                        .setNodeValue(XML_DISPENSATION_LOINC_CODESYSTEMNAME);
            if (codeNode.getAttributes().getNamedItem("codeSystem") != null)
                codeNode.getAttributes().getNamedItem("codeSystem")
                        .setNodeValue(XML_DISPENSATION_LOINC_CODESYSTEM);
        }
        Node titleNode = (Node) docTitleExpr.evaluate(dom, XPathConstants.NODE);
        if (titleNode != null) {
            titleNode.setTextContent(XML_DISPENSATION_TITLE);
        }

        XPathExpression sectionExpr = xpath
                .compile("/ClinicalDocument/component/structuredBody/component/section[templateId/@root='"
                        + XML_PRESCRIPTION_ENTRY_TEMPLATEID + "']");
        XPathExpression substanceExpr = xpath.compile("entry/substanceAdministration");
        XPathExpression idExpr = xpath.compile("id");
        NodeList prescriptionNodes = (NodeList) sectionExpr.evaluate(dom, XPathConstants.NODESET);

        //   substanceAdministration.appendChild(newAuthorNode);

        if (prescriptionNodes != null && prescriptionNodes.getLength() > 0) {

            // calculate list of prescription ids to keep
            // calculate list of prescription lines to keep
            Set<String> prescriptionIdsToKeep = new HashSet<String>();
            Set<String> materialIdsToKeep = new HashSet<String>();
            HashMap<String, Node> materialReferences = new HashMap<String, Node>();
            if (dispensedLines != null && dispensedLines.size() > 0) {
                for (int i = 0; i < dispensedLines.size(); i++) {
                    ViewResult d_line = dispensedLines.get(i);
                    materialIdsToKeep.add((String) d_line.getField10());
                    prescriptionIdsToKeep.add((String) d_line.getField9());
                }
            }

            Node structuredBodyNode = null;
            for (int p = 0; p < prescriptionNodes.getLength(); p++) {
                // for each one of the prescription nodes (<component> tags) check if their id belongs to the list of prescription Ids to keep in dispensation document
                Node sectionNode = prescriptionNodes.item(p);
                Node idNode = (Node) idExpr.evaluate(sectionNode, XPathConstants.NODE);
                String prescrId = idNode.getAttributes().getNamedItem("extension").getNodeValue();
                if (prescriptionIdsToKeep.contains(prescrId)) {
                    NodeList substanceAdministrationNodes = (NodeList) substanceExpr.evaluate(sectionNode,
                            XPathConstants.NODESET);
                    if (substanceAdministrationNodes != null && substanceAdministrationNodes.getLength() > 0) {
                        for (int s = 0; s < substanceAdministrationNodes.getLength(); s++) {
                            // for each of the entries (substanceAdministration tags) within this prescription node
                            // check if the materialid in question is one of the dispensed ones, else do nothing
                            Node substanceAdministration = (Node) substanceAdministrationNodes.item(s);
                            Node substanceIdNode = (Node) idExpr.evaluate(substanceAdministration,
                                    XPathConstants.NODE);
                            String materialid = "";
                            try {
                                materialid = substanceIdNode.getAttributes().getNamedItem("extension")
                                        .getNodeValue();
                            } catch (Exception e) {
                                _log.error("error setting materialid");
                            }

                            if (materialIdsToKeep.contains(materialid)) {
                                // if the materialid is one of the dispensed ones, keep the substanceAdminstration node intact,
                                // as it will be used as an entryRelationship in the dispensation entry we will create
                                Node entryRelationshipNode = dom.createElement("entryRelationship");
                                addAttribute(dom, entryRelationshipNode, "typeCode", "REFR");
                                addTemplateId(dom, entryRelationshipNode, XML_DISPENSTATION_ENTRY_REFERENCEID);

                                entryRelationshipNode.appendChild(substanceAdministration);
                                materialReferences.put(materialid, entryRelationshipNode);

                            }
                        }
                    }
                }

                //    Then delete this node, dispensed lines will be written afterwards
                Node componentNode = sectionNode.getParentNode(); // component
                structuredBodyNode = componentNode.getParentNode(); // structuredBody
                structuredBodyNode.removeChild(componentNode);

            }

            // at the end of this for loop, prescription lines are removed from the document, and materialReferences hashmap contains
            // a mapping from materialId to ready nodes containing the entry relationship references to the corresponding prescription lines
            Node dispComponent = dom.createElement("component");
            Node dispSection = dom.createElement("section");

            addTemplateId(dom, dispSection, XML_DISPENSATION_ENTRY_PARENT_TEMPLATEID);
            addTemplateId(dom, dispSection, XML_DISPENSATION_ENTRY_TEMPLATEID);

            Node dispIdNode = dom.createElement("id");
            //addAttribute(dom, dispIdNode, "root", prescriptionIdsToKeep.iterator().next());
            addAttribute(dom, dispIdNode, "root", ful_root);
            addAttribute(dom, dispIdNode, "extension", ful_ext);
            dispSection.appendChild(dispIdNode);

            Node sectionCodeNode = dom.createElement("code");
            addAttribute(dom, sectionCodeNode, "code", "60590-7");
            addAttribute(dom, sectionCodeNode, "displayName", XML_DISPENSATION_TITLE);
            addAttribute(dom, sectionCodeNode, "codeSystem", XML_DISPENSATION_LOINC_CODESYSTEM);
            addAttribute(dom, sectionCodeNode, "codeSystemName", XML_DISPENSATION_LOINC_CODESYSTEMNAME);
            dispSection.appendChild(sectionCodeNode);

            Node title = dom.createElement("title");
            title.setTextContent(XML_DISPENSATION_TITLE);
            dispSection.appendChild(title);

            Node text = dom.createElement("text");
            Node textContent = this.generateDispensedLinesHtml(dispensedLines, db);
            textContent = textContent.cloneNode(true);
            dom.adoptNode(textContent);
            text.appendChild(textContent);
            dispSection.appendChild(text);
            dispComponent.appendChild(dispSection);

            structuredBodyNode.appendChild(dispComponent);

            for (int i = 0; i < dispensedLines.size(); i++) {
                ViewResult d_line = dispensedLines.get(i);
                String materialid = (String) d_line.getField10();
                // for each dispensed line create a dispensation entry in the document, and use the entryRelationship calculated above
                Node entry = dom.createElement("entry");
                Node supply = dom.createElement("supply");
                addAttribute(dom, supply, "classCode", "SPLY");
                addAttribute(dom, supply, "moodCode", "EVN");

                // add templateId tags
                addTemplateId(dom, supply, XML_DISPENSATION_ENTRY_SUPPLY_TEMPLATE1);
                addTemplateId(dom, supply, XML_DISPENSATION_ENTRY_SUPPLY_TEMPLATE2);
                addTemplateId(dom, supply, XML_DISPENSATION_ENTRY_SUPPLY_TEMPLATE3);

                // add id tag
                Node supplyId = dom.createElement("id");
                addAttribute(dom, supplyId, "root", XML_DISPENSATION_ENTRY_SUPPLY_ID_ROOT);
                addAttribute(dom, supplyId, "extension", (String) d_line.getField1());
                supply.appendChild(supplyId);

                // add quantity tag
                Node quantity = dom.createElement("quantity");
                String nrOfPacks = (String) d_line.getField8();
                nrOfPacks = nrOfPacks.trim();
                String value = nrOfPacks;
                String unit = "1";
                if (nrOfPacks.indexOf(" ") != -1) {
                    value = nrOfPacks.substring(0, nrOfPacks.indexOf(" "));
                    unit = nrOfPacks.substring(nrOfPacks.indexOf(" ") + 1);
                }
                addAttribute(dom, quantity, "value", (String) d_line.getField7());
                addAttribute(dom, quantity, "unit", (String) d_line.getField12());
                supply.appendChild(quantity);

                // add product tag
                addProductTag(dom, supply, d_line, materialReferences.get(materialid));

                // add performer tag
                addPerformerTag(dom, supply, doctor);

                // add entryRelationship tag
                supply.appendChild(materialReferences.get(materialid));

                // add substitution relationship tag
                if (d_line.getField3() != null && ((Boolean) d_line.getField3()).booleanValue()) {
                    Node substitutionNode = dom.createElement("entryRelationship");
                    addAttribute(dom, substitutionNode, "typeCode", "COMP");
                    Node substanceAdminNode = dom.createElement("substanceAdministration");
                    addAttribute(dom, substanceAdminNode, "classCode", "SBADM");
                    addAttribute(dom, substanceAdminNode, "moodCode", "INT");

                    Node seqNode = dom.createElement("doseQuantity");
                    addAttribute(dom, seqNode, "value", "1");
                    addAttribute(dom, seqNode, "unit", "1");
                    substanceAdminNode.appendChild(seqNode);
                    substitutionNode.appendChild(substanceAdminNode);
                    // changed quantity
                    if (lines.get(0).getField21().equals(d_line.getField7())) {

                    }
                    // changed name
                    if (lines.get(0).getField11().equals(d_line.getField2())) {

                    }
                    supply.appendChild(substitutionNode);
                }
                entry.appendChild(supply);
                dispSection.appendChild(entry);
            }

        }

        // copy author tag from eprescription
        XPathExpression authorExpr = xpath.compile("/ClinicalDocument/author");
        Node oldAuthorNode = (Node) authorExpr.evaluate(dom, XPathConstants.NODE);
        Node newAuthorNode = oldAuthorNode.cloneNode(true);

        XPathExpression substExpr = xpath.compile(
                "/ClinicalDocument/component/structuredBody/component/section/entry/supply/entryRelationship/substanceAdministration");
        NodeList substNodes = (NodeList) substExpr.evaluate(dom, XPathConstants.NODESET);

        XPathExpression entryRelExpr = xpath.compile(
                "/ClinicalDocument/component/structuredBody/component/section/entry/supply/entryRelationship/substanceAdministration/entryRelationship");
        NodeList entryRelNodes = (NodeList) entryRelExpr.evaluate(dom, XPathConstants.NODESET);
        Node entryRelNode = (Node) entryRelExpr.evaluate(dom, XPathConstants.NODE);

        if (substNodes != null) {
            //            for (int t=0; t<substNodes.getLength(); t++)
            //            {         
            int t = 0;
            Node substNode = substNodes.item(t);
            substNode.insertBefore(newAuthorNode, entryRelNode);
            //            }
        }

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

        //initialize StreamResult with File object to save to file
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(dom);
        transformer.transform(source, result);

        String xmlString = result.getWriter().toString();
        bytesED = xmlString.getBytes();
        System.out.println(xmlString);

    } catch (Exception e) {
        _log.error(e.getMessage());
    }

    return bytesED;
}

From source file:org.apache.fop.render.intermediate.AbstractBinaryWritingIFDocumentHandler.java

/** {@inheritDoc} */
public void setResult(Result result) throws IFException {
    if (result instanceof StreamResult) {
        StreamResult streamResult = (StreamResult) result;
        OutputStream out = streamResult.getOutputStream();
        if (out == null) {
            if (streamResult.getWriter() != null) {
                throw new IllegalArgumentException("FOP cannot use a Writer. Please supply an OutputStream!");
            }//from   w  w w .  j  a v  a2s.c  o m
            try {
                URL url = new URL(streamResult.getSystemId());
                File f = FileUtils.toFile(url);
                if (f != null) {
                    out = new java.io.FileOutputStream(f);
                } else {
                    out = url.openConnection().getOutputStream();
                }
            } catch (IOException ioe) {
                throw new IFException("I/O error while opening output stream", ioe);
            }
            out = new java.io.BufferedOutputStream(out);
            this.ownOutputStream = true;
        }
        if (out == null) {
            throw new IllegalArgumentException("Need a StreamResult with an OutputStream");
        }
        this.outputStream = out;
    } else {
        throw new UnsupportedOperationException("Unsupported Result subclass: " + result.getClass().getName());
    }
}

From source file:org.apache.geode.management.internal.configuration.utils.XmlUtils.java

private static String transform(Transformer transformer, Node element) throws TransformerException {
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(element);
    transformer.transform(source, result);

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