Example usage for org.w3c.dom Document adoptNode

List of usage examples for org.w3c.dom Document adoptNode

Introduction

In this page you can find the example usage for org.w3c.dom Document adoptNode.

Prototype

public Node adoptNode(Node source) throws DOMException;

Source Link

Document

Attempts to adopt a node from another document to this document.

Usage

From source file:de.qucosa.webapi.v1.DocumentResource.java

private void updateFileElementsInPlace(Document targetDocument, Document updateDocument,
        List<FileUpdateOperation> fileUpdateOperations, Element targetRoot, Element updateRoot,
        List<String> purgeDatastreamList) throws XPathExpressionException, FedoraClientException, IOException {
    List<Node> targetFileNodes = getChildNodesByName(targetRoot, "File");
    List<Node> updateFileNodes = getChildNodesByName(updateRoot, "File");
    for (Node targetNode : targetFileNodes) {
        Node idAttr = targetNode.getAttributes().getNamedItem("id");
        if (idAttr != null) {
            String idAttrValue = idAttr.getTextContent();
            if (!idAttrValue.isEmpty() && !((Boolean) xPath.evaluate("//File[@id='" + idAttrValue + "']",
                    updateDocument, XPathConstants.BOOLEAN))) {
                purgeDatastreamList.add(DSID_QUCOSA_ATT.concat(idAttrValue));
            }/*from  w w  w.j av a2s.  c  o m*/
        }
    }
    for (Node updateNode : updateFileNodes) {
        Node idAttr = updateNode.getAttributes().getNamedItem("id");
        if (idAttr == null) {
            targetDocument.adoptNode(updateNode);
            targetRoot.appendChild(updateNode);
        } else {
            String idAttrValue = idAttr.getTextContent();
            Node targetNode = (Node) xPath.evaluate("//File[@id='" + idAttrValue + "']", targetDocument,
                    XPathConstants.NODE);
            FileUpdateOperation fupo = updateFileNodeWith((Element) targetNode, (Element) updateNode);
            fupo.setDsid(DSID_QUCOSA_ATT.concat(idAttrValue));
            fileUpdateOperations.add(fupo);
        }
    }
}

From source file:de.qucosa.webapi.v1.DocumentResource.java

private Tuple<Collection<String>> updateWith(Document targetDocument, final Document updateDocument,
        List<FileUpdateOperation> fileUpdateOperations)
        throws XPathExpressionException, IOException, FedoraClientException {
    Element targetRoot = (Element) targetDocument.getElementsByTagName("Opus_Document").item(0);
    Element updateRoot = (Element) updateDocument.getElementsByTagName("Opus_Document").item(0);

    Set<String> distinctUpdateFieldList = new LinkedHashSet<>();
    NodeList updateFields = updateRoot.getChildNodes();
    for (int i = 0; i < updateFields.getLength(); i++) {
        distinctUpdateFieldList.add(updateFields.item(i).getNodeName());
    }//ww  w. j  a v  a 2s  . c o m

    for (String fn : distinctUpdateFieldList) {
        // cannot use getElementsByTagName() here because it searches recursively
        for (Node victim : getChildNodesByName(targetRoot, fn)) {
            if (!victim.getLocalName().equals("File")) {
                targetRoot.removeChild(victim);
            }
        }
    }

    for (int i = 0; i < updateFields.getLength(); i++) {
        // Update node needs to be cloned, otherwise it will
        // be removed from updateFields by adoptNode().
        Node updateNode = updateFields.item(i).cloneNode(true);
        if (updateNode.hasChildNodes() && !updateNode.getLocalName().equals("File")) {
            targetDocument.adoptNode(updateNode);
            targetRoot.appendChild(updateNode);
        }
    }

    List<String> purgeDatastreamList = new LinkedList<>();
    if ((Boolean) xPath.evaluate("//File", updateDocument, XPathConstants.BOOLEAN)) {
        updateFileElementsInPlace(targetDocument, updateDocument, fileUpdateOperations, targetRoot, updateRoot,
                purgeDatastreamList);
    }

    targetDocument.normalizeDocument();
    return new Tuple<>(distinctUpdateFieldList, purgeDatastreamList);
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandler.java

/**
 * This method takes the ER response and converts the Java objects to the Merge Response XML.
 * //from   www.j  ava 2 s .com
 * @param entityContainerNode
 * @param results
 * @param recordLimit
 * @param attributeParametersNode
 * @return
 * @throws ParserConfigurationException
 * @throws XPathExpressionException
 * @throws TransformerException
 */
private Document createResponseMessage(Node entityContainerNode, EntityResolutionResults results,
        Node attributeParametersNode, int recordLimit) throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);

    Document resultDocument = dbf.newDocumentBuilder().newDocument();

    Element entityMergeResultMessageElement = resultDocument.createElementNS(
            EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "EntityMergeResultMessage");
    resultDocument.appendChild(entityMergeResultMessageElement);

    Element entityContainerElement = resultDocument
            .createElementNS(EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "EntityContainer");
    entityMergeResultMessageElement.appendChild(entityContainerElement);

    NodeList inputEntityNodes = (NodeList) xpath.evaluate("er-ext:Entity", entityContainerNode,
            XPathConstants.NODESET);
    Collection<Element> inputEntityElements = null;
    if (attributeParametersNode == null) {
        inputEntityElements = new ArrayList<Element>();
    } else {
        inputEntityElements = TreeMultiset
                .create(new EntityElementComparator((Element) attributeParametersNode));
        //inputEntityElements = new ArrayList<Element>();
    }

    for (int i = 0; i < inputEntityNodes.getLength(); i++) {
        inputEntityElements.add((Element) inputEntityNodes.item(i));
    }

    if (attributeParametersNode == null) {
        LOG.warn("Attribute Parameters element was null, so records will not be sorted");
    }
    //Collections.sort((List<Element>) inputEntityElements, new EntityElementComparator((Element) attributeParametersNode));

    if (inputEntityElements.size() != inputEntityNodes.getLength()) {
        LOG.error("Lost elements in ER output sorting.  Input count=" + inputEntityNodes.getLength()
                + ", output count=" + inputEntityElements.size());
    }

    for (Element e : inputEntityElements) {
        Node clone = resultDocument.adoptNode(e.cloneNode(true));
        resultDocument.renameNode(clone, EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                e.getLocalName());
        entityContainerElement.appendChild(clone);
    }

    Element mergedRecordsElement = resultDocument
            .createElementNS(EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "MergedRecords");
    entityMergeResultMessageElement.appendChild(mergedRecordsElement);

    if (results != null) {

        List<RecordWrapper> records = results.getRecords();

        // Loop through RecordWrappers to extract info to create merged records
        for (RecordWrapper record : records) {
            LOG.debug("  !#!#!#!# Record 1, id=" + record.getExternalId() + ", externals="
                    + record.getRelatedIds());

            // Create Merged Record Container
            Element mergedRecordElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergedRecord");
            mergedRecordsElement.appendChild(mergedRecordElement);

            // Create Original Record Reference for 'first record'
            Element originalRecordRefElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference");
            originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE,
                    "ref", record.getExternalId());
            mergedRecordElement.appendChild(originalRecordRefElement);

            // Loop through and add any related records
            for (String relatedRecordId : record.getRelatedIds()) {
                originalRecordRefElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference");
                originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE,
                        "ref", relatedRecordId);
                mergedRecordElement.appendChild(originalRecordRefElement);
            }

            // Create Merge Quality Element
            Element mergeQualityElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergeQuality");
            mergedRecordElement.appendChild(mergeQualityElement);
            Set<AttributeStatistics> stats = results.getStatisticsForRecord(record.getExternalId());
            for (AttributeStatistics stat : stats) {
                Element stringDistanceStatsElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStatistics");
                mergeQualityElement.appendChild(stringDistanceStatsElement);
                Element xpathElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "AttributeXPath");
                stringDistanceStatsElement.appendChild(xpathElement);
                Node contentNode = resultDocument.createTextNode(stat.getAttributeName());
                xpathElement.appendChild(contentNode);
                Element meanElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceMeanInRecord");
                stringDistanceStatsElement.appendChild(meanElement);
                contentNode = resultDocument.createTextNode(String.valueOf(stat.getAverageStringDistance()));
                meanElement.appendChild(contentNode);
                Element sdElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStandardDeviationInRecord");
                stringDistanceStatsElement.appendChild(sdElement);
                contentNode = resultDocument
                        .createTextNode(String.valueOf(stat.getStandardDeviationStringDistance()));
                sdElement.appendChild(contentNode);

            }
        }

    } else {

        for (Element e : inputEntityElements) {

            String id = e.getAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE, "id");

            Element mergedRecordElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergedRecord");
            mergedRecordsElement.appendChild(mergedRecordElement);

            Element originalRecordRefElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference");
            originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE,
                    "ref", id);
            mergedRecordElement.appendChild(originalRecordRefElement);

            Element mergeQualityElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergeQuality");
            mergedRecordElement.appendChild(mergeQualityElement);
            XPath xp = XPathFactory.newInstance().newXPath();
            xp.setNamespaceContext(new EntityResolutionNamespaceContext());
            NodeList attributeParameterNodes = (NodeList) xp.evaluate("er-ext:AttributeParameter",
                    attributeParametersNode, XPathConstants.NODESET);
            for (int i = 0; i < attributeParameterNodes.getLength(); i++) {
                String attributeName = xp.evaluate("er-ext:AttributeXPath", attributeParametersNode);
                Element stringDistanceStatsElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStatistics");
                mergeQualityElement.appendChild(stringDistanceStatsElement);
                Element xpathElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "AttributeXPath");
                stringDistanceStatsElement.appendChild(xpathElement);
                Node contentNode = resultDocument.createTextNode(attributeName);
                xpathElement.appendChild(contentNode);
                Element meanElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceMeanInRecord");
                stringDistanceStatsElement.appendChild(meanElement);
                contentNode = resultDocument.createTextNode("0.0");
                meanElement.appendChild(contentNode);
                Element sdElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStandardDeviationInRecord");
                stringDistanceStatsElement.appendChild(sdElement);
                contentNode = resultDocument.createTextNode("0.0");
                sdElement.appendChild(contentNode);
            }

        }

    }

    Element recordLimitExceededElement = resultDocument.createElementNS(
            EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "RecordLimitExceededIndicator");
    recordLimitExceededElement.setTextContent(new Boolean(results == null).toString());
    entityMergeResultMessageElement.appendChild(recordLimitExceededElement);

    return resultDocument;

}

From source file:bridge.toolkit.commands.S1000DConverter.java

/**
 * modify scoEntryItem in scoEntryContent, move lom from scoEntryItem
 * /*ww  w  .  j a v a2 s.c om*/
 * @param nodes
 * @throws Exception
 */
private static void walkingthrough(Node nodes, org.w3c.dom.Document document) throws Exception {

    changeScoEntry(nodes, document);

    int length = nodes.getChildNodes().getLength();
    for (int i = 0; i < length; i++) {
        Node node = nodes.getChildNodes().item(i);

        changeScoEntry(node, document);

        if (node.getNodeName().equals("scoEntryItem")) {
            // the lom children must linked to the parent child (scoEntry)
            int lengthlom = node.getChildNodes().getLength();
            for (int lom = 0; lom < lengthlom; lom++) {
                if (node.getChildNodes().item(lom) != null
                        && node.getChildNodes().item(lom).getNodeName().equals("lom:lom")) {
                    // clone the node..
                    Node cloneLom = node.getChildNodes().item(lom).cloneNode(true);
                    // first of all I remove it
                    Node lomnode = node.getChildNodes().item(lom);
                    Node father = lomnode.getParentNode();
                    Node grandf = father.getParentNode();
                    father.removeChild(lomnode);
                    // then I add it to the new parent..
                    grandf.insertBefore(cloneLom, father);
                }

                // for each dmRef open the DM and read the real data module
                // content to be show in the lesson
                if (node.getChildNodes().item(lom) != null
                        && node.getChildNodes().item(lom).getNodeName().equals("dmRef")) {
                    String filename = resourcepack + "\\" + gettingDmfilename(node.getChildNodes().item(lom))
                            + ".xml";
                    if (new File(filename).exists()) {
                        // if the data module is a scoContent will copy each
                        // dmref in the scoEntry
                        org.w3c.dom.Document dm41 = getDoc(new File(filename));

                        if (processXPathSingleNode("dmodule/content/scoContent", dm41) != null)
                            ;
                        {
                            NodeList dmre = processXPath("/dmodule/content/scoContent/trainingStep/dmRef",
                                    dm41);
                            Node father = node.getChildNodes().item(lom).getParentNode();
                            father.removeChild(node.getChildNodes().item(lom));
                            // remove the reference to Scocontent and
                            // replace it with the dm inside
                            for (int nodi = 0; nodi < dmre.getLength(); nodi++) {
                                Node cloneref = dmre.item(nodi).cloneNode(true);
                                document.adoptNode(cloneref);
                                father.appendChild(cloneref);
                            }

                        }
                    }

                }

            }

            // rename scoEntryItem in scoEntry
            node = changeNodename(node, document, "scoEntryContent");
        }
        walkingthrough(node, document);
    }
}

From source file:de.codesourcery.spring.contextrewrite.XMLRewrite.java

private void mergeAttributes(Node source, Node target, Document targetDocument) {
    for (int i = 0, len = source.getAttributes().getLength(); i < len; i++) {
        final Node attrToMerge = source.getAttributes().item(i);
        final String attrName = attrToMerge.getNodeName();
        final String attrValue = attrToMerge.getNodeValue();
        final Optional<Node> existingAttr = findAttribute(target, attrToMerge);
        if (existingAttr.isPresent()) {
            final String[] existingValues = split(existingAttr.get().getNodeValue());

            if (attrName.endsWith(":schemaLocation") || attrName.equals("schemaLocation")) {
                final List<Pair> existingPairs = toPairs(existingValues);
                final List<Pair> newPairs = toPairs(split(attrValue));
                final String toAdd = newPairs.stream()
                        .filter(p -> existingPairs.stream().noneMatch(x -> x.sameFirst(p)))
                        .map(p -> p.first + " " + p.second).collect(Collectors.joining(" "));
                if (!toAdd.isEmpty()) {
                    existingAttr.get().setNodeValue(existingAttr.get().getNodeValue() + " " + toAdd);
                }//from   ww  w  .j a  v a 2 s.co  m
                continue;
            }

            // merge value
            if (Stream.of(existingValues).noneMatch(value -> value.equals(attrToMerge.getNodeValue()))) {
                if (existingValues.length == 0) {
                    debug("adding missing attribute value " + attrName + "=" + attrValue);
                    existingAttr.get().setNodeValue(attrValue);
                } else {
                    debug("Appending existing attribute " + existingAttr.get().getNodeName() + "=" + attrValue);
                    existingAttr.get().setNodeValue(existingAttr.get().getNodeValue() + " " + attrValue);
                }
            } else {
                debug("Already present: attribute " + existingAttr.get().getNodeName() + "=" + attrValue);
            }
        } else {
            debug("Adding new attribute " + attrName + "=" + attrValue);
            final Node cloned = targetDocument.adoptNode(attrToMerge.cloneNode(true));
            target.getAttributes().setNamedItem(cloned);
        }
    }
}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

@Override
public String getTypeData(int userId, Integer type) {
    String sql = "";
    PreparedStatement st;//from w  ww  .j  a  va 2 s . co m

    HashMap<Integer, Node> resolve = new HashMap<Integer, Node>();
    /// Node -> parent
    ArrayList<Object[]> entries = new ArrayList<Object[]>();

    ResultSet res = null;
    try {
        sql = "SELECT node_id, asm_type, xsi_type, parent_node, node_data, instance_rule "
                + "FROM definition_type " + "WHERE def_id=?";
        st = connection.prepareStatement(sql);
        st.setInt(1, type);
        res = st.executeQuery();

        /// Time to create data
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder;
        Document document = null;

        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        document = documentBuilder.newDocument();

        Element root = document.createElement("type");
        root.setAttribute("typeid", type.toString());
        document.appendChild(root);

        while (res.next()) {
            Integer id = res.getInt("node_id");
            String asmtype = res.getString("asm_type");
            String xsitype = res.getString("xsi_type");
            Integer parent = res.getInt("parent_node");
            if (res.wasNull())
                parent = null;
            String data = res.getString("node_data");
            Integer instance = res.getInt("instance_rule");

            Element nodeData = null;
            if (data != null) // Une ressource
            {
                data = "<asmResource>" + data + "</asmResource>";
                Document frag = documentBuilder.parse(new ByteArrayInputStream(data.getBytes("UTF-8")));
                nodeData = frag.getDocumentElement();
                nodeData.setAttribute("id", id.toString());
                nodeData.setAttribute("instance", instance.toString());
                document.adoptNode(nodeData);
                nodeData.setAttribute("xsi_type", xsitype);
            } else // Un bout de structure
            {
                nodeData = document.createElement(asmtype);
            }

            /// Info pour reconstruire l'arbre
            resolve.put(id, nodeData);
            Object[] obj = { nodeData, parent };
            entries.add(obj);
        }
        res.close();
        st.close();

        /// Reconstruction
        Iterator<Object[]> iter = entries.iterator();
        while (iter.hasNext()) {
            Object obj[] = iter.next();
            Node node = (Node) obj[0];
            Integer parent = (Integer) obj[1];
            if (parent != null) {
                Node parentNode = resolve.get(parent);
                parentNode.appendChild(node);
            } else
                root.appendChild(node);
        }

        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(document), new StreamResult(stw));
        return stw.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return "";
}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

private void processQuery(ResultSet result, HashMap<String, Node> resolve, ArrayList<Object[]> entries,
        Document document, DocumentBuilder parse)
        throws UnsupportedEncodingException, DOMException, SQLException, SAXException, IOException {
    if (result != null)
        while (result.next()) {
            String nodeUuid = result.getString("node_uuid");
            String childsId = result.getString("node_children_uuid");

            String type = result.getString("asm_type");

            String xsi_type = result.getString("xsi_type");
            if (null == xsi_type)
                xsi_type = "";

            String readRight = result.getInt("RD") == 1 ? "Y" : "N";
            String writeRight = result.getInt("WR") == 1 ? "Y" : "N";
            String submitRight = result.getInt("SB") == 1 ? "Y" : "N";
            String deleteRight = result.getInt("DL") == 1 ? "Y" : "N";
            String macro = result.getString("rules_id");
            if (macro != null)
                macro = "action=\"" + macro + "\"";
            else/* w  w  w  . ja  va 2s  .  c o m*/
                macro = "";

            String attr = result.getString("metadata_wad");
            String metaFragwad;
            if (!"".equals(attr)) /// Attributes exists
            {
                metaFragwad = "<metadata-wad " + attr + "/>";
            } else {
                metaFragwad = "<metadata-wad />";
            }

            attr = result.getString("metadata_epm");
            String metaFragepm;
            //            if( !"".equals(attr) )  /// Attributes exists
            if (attr != null && !"".equals(attr)) /// Attributes exists
            {
                metaFragepm = "<metadata-epm " + attr + "/>";
            } else {
                metaFragepm = "<metadata-epm />";
            }

            attr = result.getString("metadata");
            String metaFrag;
            //            if( !"".equals(attr) )  /// Attributes exists
            if (attr != null && !"".equals(attr)) /// Attributes exists
            {
                metaFrag = "<metadata " + attr + "/>";
            } else {
                metaFrag = "<metadata />";
            }

            String res_res_node_uuid = result.getString("res_res_node_uuid");
            String res_res_node = "";
            if (res_res_node_uuid != null && res_res_node_uuid.length() > 0) {
                String nodeContent = result.getString("r2_content");
                if (nodeContent != null) {
                    res_res_node = "<asmResource contextid=\"" + nodeUuid + "\" id=\"" + res_res_node_uuid
                            + "\" xsi_type=\"nodeRes\">" + nodeContent.trim() + "</asmResource>";
                }
            }

            String res_context_node_uuid = result.getString("res_context_node_uuid");
            String context_node = "";
            if (res_context_node_uuid != null && res_context_node_uuid.length() > 0) {
                String nodeContent = result.getString("r3_content");
                if (nodeContent != null) {
                    context_node = "<asmResource contextid=\"" + nodeUuid + "\" id=\"" + res_context_node_uuid
                            + "\" xsi_type=\"context\">" + nodeContent.trim() + "</asmResource>";
                }
            }

            String res_node_uuid = result.getString("res_node_uuid");
            String specific_node = "";
            if (res_node_uuid != null && res_node_uuid.length() > 0) {
                String nodeContent = result.getString("r1_content");
                if (nodeContent != null) {
                    specific_node = "<asmResource contextid=\"" + nodeUuid + "\" id=\"" + res_node_uuid
                            + "\" xsi_type=\"" + result.getString("r1_type") + "\">" + nodeContent.trim()
                            + "</asmResource>";
                }
            }

            String snode = "<" + type + " delete=\"" + deleteRight + "\" id=\"" + nodeUuid + "\" read=\""
                    + readRight + "\" submit=\"" + submitRight + "\" write=\"" + writeRight + "\" xsi_type=\""
                    + xsi_type + "\" " + macro + ">" + metaFragwad + metaFragepm + metaFrag + res_res_node
                    + context_node + specific_node + "</" + type + ">";

            Document frag = parse.parse(new ByteArrayInputStream(snode.getBytes("UTF-8")));
            Element ressource = frag.getDocumentElement();
            document.adoptNode(ressource);

            Node node = ressource;

            /// Prepare data to reconstruct tree
            resolve.put(nodeUuid, node);
            if (!"".equals(childsId) && childsId != null) {
                Object[] obj = { node, childsId };
                entries.add(obj);
            }
        }
}

From source file:com.portfolio.data.provider.MysqlDataProvider.java

private void processQuery(ResultSet result, HashMap<String, Node> resolve, ArrayList<Object[]> entries,
        Document document, DocumentBuilder parse, String role)
        throws UnsupportedEncodingException, DOMException, SQLException, SAXException, IOException {
    if (result != null)
        while (result.next()) {
            String nodeUuid = result.getString("node_uuid");
            if (nodeUuid == null)
                continue; // Cas o on a des droits sur plus de noeuds qui ne sont pas dans le portfolio

            String childsId = result.getString("node_children_uuid");

            String type = result.getString("asm_type");

            String xsi_type = result.getString("xsi_type");
            if (null == xsi_type)
                xsi_type = "";

            int rd = result.getInt("RD");
            String readRight = result.getInt("RD") == 1 ? "Y" : "N";
            String writeRight = result.getInt("WR") == 1 ? "Y" : "N";
            String submitRight = result.getInt("SB") == 1 ? "Y" : "N";
            String deleteRight = result.getInt("DL") == 1 ? "Y" : "N";
            String macro = result.getString("rules_id");
            if (macro != null)
                macro = "action=\"" + macro + "\"";
            else//from  w  w  w  .  jav  a 2  s  . c  om
                macro = "";

            String attr = result.getString("metadata_wad");
            String metaFragwad;
            //            if( !"".equals(attr) )  /// Attributes exists
            if (attr != null && !"".equals(attr)) /// Attributes exists
            {
                metaFragwad = "<metadata-wad " + attr + "/>";
            } else {
                metaFragwad = "<metadata-wad />";
            }

            attr = result.getString("metadata_epm");
            String metaFragepm;
            //            if( !"".equals(attr) )  /// Attributes exists
            if (attr != null && !"".equals(attr)) /// Attributes exists
            {
                metaFragepm = "<metadata-epm " + attr + "/>";
            } else {
                metaFragepm = "<metadata-epm />";
            }

            attr = result.getString("metadata");
            String metaFrag;
            //            if( !"".equals(attr) )  /// Attributes exists
            if (attr != null && !"".equals(attr)) /// Attributes exists
            {
                metaFrag = "<metadata " + attr + "/>";
            } else {
                metaFrag = "<metadata />";
            }

            String res_res_node_uuid = result.getString("res_res_node_uuid");
            String res_res_node = "";
            if (res_res_node_uuid != null && res_res_node_uuid.length() > 0) {
                String nodeContent = result.getString("r2_content");
                if (nodeContent != null) {
                    res_res_node = "<asmResource contextid=\"" + nodeUuid + "\" id=\"" + res_res_node_uuid
                            + "\" xsi_type=\"nodeRes\">" + nodeContent.trim() + "</asmResource>";
                }
            }

            String res_context_node_uuid = result.getString("res_context_node_uuid");
            String context_node = "";
            if (res_context_node_uuid != null && res_context_node_uuid.length() > 0) {
                String nodeContent = result.getString("r3_content");
                if (nodeContent != null) {
                    context_node = "<asmResource contextid=\"" + nodeUuid + "\" id=\"" + res_context_node_uuid
                            + "\" xsi_type=\"context\">" + nodeContent.trim() + "</asmResource>";
                } else {
                    context_node = "<asmResource contextid=\"" + nodeUuid + "\" id=\"" + res_context_node_uuid
                            + "\" xsi_type=\"context\"/>";
                }
            }

            String res_node_uuid = result.getString("res_node_uuid");
            String specific_node = "";
            if (res_node_uuid != null && res_node_uuid.length() > 0) {
                String nodeContent = result.getString("r1_content");
                if (nodeContent != null) {
                    specific_node = "<asmResource contextid=\"" + nodeUuid + "\" id=\"" + res_node_uuid
                            + "\" xsi_type=\"" + result.getString("r1_type") + "\">" + nodeContent.trim()
                            + "</asmResource>";
                }
            }

            /// On spcifie aussi le rle qui a t choisi dans la rcupration des donnes
            String snode = "<" + type + " delete=\"" + deleteRight + "\" id=\"" + nodeUuid + "\" read=\""
                    + readRight + "\" submit=\"" + submitRight + "\" write=\"" + writeRight + "\" xsi_type=\""
                    + xsi_type + "\" " + macro + " role=\"" + role + "\">" + metaFragwad + metaFragepm
                    + metaFrag + res_res_node + context_node + specific_node + "</" + type + ">";

            Document frag = parse.parse(new ByteArrayInputStream(snode.getBytes("UTF-8")));
            Element ressource = frag.getDocumentElement();
            document.adoptNode(ressource);

            Node node = ressource;

            /// Prepare data to reconstruct tree
            resolve.put(nodeUuid, node);
            if (!"".equals(childsId) && childsId != null) {
                Object[] obj = { node, childsId };
                entries.add(obj);
            }
        }
}

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 {//www.j  av a2s  . co  m
        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:nl.b3p.viewer.stripes.SldActionBean.java

private void addFilterToExistingSld() throws Exception {
    Filter f = CQL.toFilter(filter);

    f = (Filter) f.accept(new ChangeMatchCase(false), null);

    if (featureTypeName == null) {
        featureTypeName = layer;//from  w ww. j  ava  2s  .co m
    }
    FeatureTypeConstraint ftc = sldFactory.createFeatureTypeConstraint(featureTypeName, f, new Extent[] {});

    if (newSld == null) {

        SLDTransformer sldTransformer = new SLDTransformer();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        sldTransformer.transform(ftc, bos);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();

        Document sldXmlDoc = db.parse(new ByteArrayInputStream(sldXml));

        Document ftcDoc = db.parse(new ByteArrayInputStream(bos.toByteArray()));

        String sldVersion = sldXmlDoc.getDocumentElement().getAttribute("version");
        if ("1.1.0".equals(sldVersion)) {
            // replace sld:FeatureTypeName element generated by GeoTools
            // by se:FeatureTypeName
            NodeList sldFTNs = ftcDoc.getElementsByTagNameNS(NS_SLD, "FeatureTypeName");
            if (sldFTNs.getLength() == 1) {
                Node sldFTN = sldFTNs.item(0);
                Node seFTN = ftcDoc.createElementNS(NS_SE, "FeatureTypeName");
                seFTN.setTextContent(sldFTN.getTextContent());
                sldFTN.getParentNode().replaceChild(seFTN, sldFTN);
            }
        }

        // Ignore namespaces to tackle both SLD 1.0.0 and SLD 1.1.0
        // Add constraint to all NamedLayers, not only to the layer specified
        // in layers parameter

        NodeList namedLayers = sldXmlDoc.getElementsByTagNameNS(NS_SLD, "NamedLayer");
        for (int i = 0; i < namedLayers.getLength(); i++) {
            Node namedLayer = namedLayers.item(i);

            // Search where to insert the FeatureTypeConstraint from our ftcDoc

            // Insert LayerFeatureConstraints after sld:Name, se:Name or se:Description
            // and before sld:NamedStyle or sld:UserStyle so search backwards.
            // If we find an existing LayerFeatureConstraints, use that
            NodeList childs = namedLayer.getChildNodes();
            Node insertBefore = null;
            Node layerFeatureConstraints = null;
            int j = childs.getLength() - 1;
            do {
                Node child = childs.item(j);

                if ("LayerFeatureConstraints".equals(child.getLocalName())) {
                    layerFeatureConstraints = child;
                    break;
                }
                if ("Description".equals(child.getLocalName()) || "Name".equals(child.getLocalName())) {
                    break;
                }
                insertBefore = child;
                j--;
            } while (j >= 0);
            Node featureTypeConstraint = sldXmlDoc.adoptNode(ftcDoc.getDocumentElement().cloneNode(true));
            if (layerFeatureConstraints == null) {
                layerFeatureConstraints = sldXmlDoc.createElementNS(NS_SLD, "LayerFeatureConstraints");
                layerFeatureConstraints.appendChild(featureTypeConstraint);
                namedLayer.insertBefore(layerFeatureConstraints, insertBefore);
            } else {
                layerFeatureConstraints.appendChild(featureTypeConstraint);
            }
        }

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        DOMSource source = new DOMSource(sldXmlDoc);
        bos = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(bos);
        t.transform(source, result);
        sldXml = bos.toByteArray();
    }
}