Example usage for org.w3c.dom Node insertBefore

List of usage examples for org.w3c.dom Node insertBefore

Introduction

In this page you can find the example usage for org.w3c.dom Node insertBefore.

Prototype

public Node insertBefore(Node newChild, Node refChild) throws DOMException;

Source Link

Document

Inserts the node newChild before the existing child node refChild.

Usage

From source file:org.infoscoop.service.ProxyConfService.java

/**
 * @param elementName//from w  ww. j  ava  2s. co  m
 * @param id
 * @param cacheLifeTime
 * @param type
 * @param pattern
 * @param replacement
 * @param host
 * @param port
 * @throws Exception
 */
public synchronized void addProxyConf(String elementName, String id, String cacheLifeTime, String type,
        String pattern, String replacement, String host, String port, Collection<String> headers)
        throws Exception {
    if (log.isInfoEnabled()) {
        log.info("addProxyConf: id=" + id + ", cacheLifeTime=" + cacheLifeTime + ", type=" + type + ", pattern="
                + pattern + ", replacement=" + replacement + ", host=" + host + ", port=" + port);
    }

    try {
        // Obtain data and transfer the result to Document.
        Proxyconf entity = this.proxyConfDAO.select();
        Document document = entity.getElement().getOwnerDocument();

        // Search for top Node.
        Node topNode = null;
        topNode = AdminServiceUtil.getNodeById(document, "/proxy-config", null);

        // Error
        if (topNode == null)
            throw new Exception("element not found [/proxy-config]");

        // Search for default
        Node defaultNode = null;
        defaultNode = AdminServiceUtil.getNodeById(document, "/proxy-config/default", null);

        // Create the Element to insert.
        if (id == null || id.length() == 0)
            id = String.valueOf(System.currentTimeMillis());
        Element element;
        element = document.createElement(elementName);
        element.setAttribute("id", id);
        if (type != null && type.length() > 0)
            element.setAttribute("type", type);
        if (cacheLifeTime != null && cacheLifeTime.length() > 0)
            element.setAttribute("cacheLifeTime", cacheLifeTime);
        if (pattern != null && pattern.length() > 0)
            element.setAttribute("pattern", pattern);
        if (replacement != null && replacement.length() > 0)
            element.setAttribute("replacement", replacement);
        if (host != null && host.length() > 0)
            element.setAttribute("host", host);
        if (port != null && port.length() > 0)
            element.setAttribute("port", port);

        if ("default".equals(elementName)) {
            // Added to the end of top Node.
            topNode.appendChild(element);
        } else if ("case".equals(elementName)) {
            if (defaultNode != null) {
                // Insert before default
                topNode.insertBefore(element, defaultNode);
            } else {
                // Added to the end of top Node.
                topNode.appendChild(element);
            }
        } else {
            throw new Exception("No elementname");
        }

        if (headers.size() > 0) {
            Node headersNode = document.createElement("headers");
            element.appendChild(headersNode);

            for (String header : headers) {
                Element headerNode = document.createElement("header");
                headerNode.appendChild(document.createTextNode(header));
                headersNode.appendChild(headerNode);
            }
        }
        entity.setElement(document.getDocumentElement());
        // Update
        proxyConfDAO.update(entity);
    } catch (Exception e) {
        log.error("Unexpected error occurred.", e);
        throw e;
    }
}

From source file:org.infoscoop.service.SearchEngineService.java

/**
 * @param engineId//  w w w  .ja va2s.c om
 * @param itemsMap
 * @param childTag
 * @throws Exception 
 */
public synchronized void updateSearchEngineItem(String engineId, Map itemsMap, String childTag)
        throws Exception {

    // Obtain data and transfer the result to Document.
    Searchengine temp = (Searchengine) this.searchEngineDAO.selectTemp();
    Document document = temp.getDocument();

    // Search for node matches engineId
    Node parentNode = null;
    parentNode = AdminServiceUtil.getNodeById(document, "//searchEngine", engineId);

    // Error
    if (parentNode == null)
        throw new Exception("element not found [//searchEngine]");

    // Search for Node matches childTag
    Node node = AdminServiceUtil.getNodeById(parentNode, "./" + childTag, null);

    // Delete itself as it is created again
    AdminServiceUtil.removeSelf(node);

    // Create element to be updated
    Element childElement = null;
    if (childTag.equals("auths")) {
        Collection auths = (Collection) itemsMap.get("auths");
        if (auths != null)
            childElement = MenuAuthorization.createAuthsElement(document, auths);
    } else if (!"rssPattern".equals(childTag)) {
        childElement = document.createElement(childTag);
        for (Iterator it = itemsMap.entrySet().iterator(); it.hasNext();) {
            Map.Entry pattern = (Map.Entry) it.next();
            String key = (String) pattern.getKey();
            String value = (String) pattern.getValue();
            childElement.setAttribute(key, value);
        }
    } else {
        childElement = document.createElement(childTag);
        String key = (String) itemsMap.keySet().iterator().next();
        childElement.appendChild(document.createTextNode((String) itemsMap.get(key)));
    }

    //      parentNode.appendChild(childElement);
    if (childElement != null)
        parentNode.insertBefore(childElement, parentNode.getFirstChild());

    temp.setDocument(document);
    // Update
    this.searchEngineDAO.update(temp);

}

From source file:org.jboss.pressgang.ccms.contentspec.builder.DocBookBuilder.java

/**
 * Adds a Topics contents as the introduction text for a Level.
 *
 * @param docBookVersion/*  www.  ja  v a 2 s  .com*/
 * @param level          The level the intro topic is being added for.
 * @param specTopic      The Topic that contains the introduction content.
 * @param parentNode     The DOM parent node the intro content is to be appended to.
 * @param doc            The DOM Document the content is to be added to.
 */
protected void addTopicContentsToLevelDocument(final DocBookVersion docBookVersion, final Level level,
        final SpecTopic specTopic, final Element parentNode, final Document doc, final boolean includeInfo) {
    final Node section = doc.importNode(specTopic.getXMLDocument().getDocumentElement(), true);

    final String infoName;
    if (docBookVersion == DocBookVersion.DOCBOOK_50) {
        infoName = "info";
    } else {
        infoName = DocBookUtilities.TOPIC_ROOT_SECTIONINFO_NODE_NAME;
    }

    if (includeInfo && (level.getLevelType() != LevelType.PART)) {
        // Reposition the sectioninfo
        final List<Node> sectionInfoNodes = XMLUtilities.getDirectChildNodes(section, infoName);
        if (sectionInfoNodes.size() != 0) {
            final String parentInfoName;
            if (docBookVersion == DocBookVersion.DOCBOOK_50) {
                parentInfoName = "info";
            } else {
                parentInfoName = parentNode.getNodeName() + "info";
            }

            // Check if the parent already has a info node
            final List<Node> infoNodes = XMLUtilities.getDirectChildNodes(parentNode, parentInfoName);
            final Node infoNode;
            if (infoNodes.size() == 0) {
                infoNode = doc.createElement(parentInfoName);
                DocBookUtilities.setInfo(docBookVersion, (Element) infoNode, parentNode);
            } else {
                infoNode = infoNodes.get(0);
            }

            // Merge the info text
            final NodeList sectionInfoChildren = sectionInfoNodes.get(0).getChildNodes();
            final Node firstNode = infoNode.getFirstChild();
            while (sectionInfoChildren.getLength() > 0) {
                if (firstNode != null) {
                    infoNode.insertBefore(sectionInfoChildren.item(0), firstNode);
                } else {
                    infoNode.appendChild(sectionInfoChildren.item(0));
                }
            }
        }
    }

    // Remove the title and sectioninfo
    final List<Node> titleNodes = XMLUtilities.getDirectChildNodes(section,
            DocBookUtilities.TOPIC_ROOT_TITLE_NODE_NAME, infoName);
    for (final Node removeNode : titleNodes) {
        section.removeChild(removeNode);
    }

    // Move the contents of the section to the chapter/level
    final NodeList sectionChildren = section.getChildNodes();
    while (sectionChildren.getLength() > 0) {
        parentNode.appendChild(sectionChildren.item(0));
    }
}

From source file:org.jboss.pressgang.ccms.contentspec.builder.DocBookBuilder.java

/**
 * Adds a revision element to the list of revisions in a revhistory element. This method ensures that the new revision is at
 * the top of the revhistory list.//from w  w w . j  a  v  a2  s  . com
 *
 * @param revHistory The revhistory element to add the revision to.
 * @param revision   The revision element to be added into the revisionhistory element.
 */
private void addRevisionToRevHistory(final Node revHistory, final Node revision) {
    if (revHistory.hasChildNodes()) {
        revHistory.insertBefore(revision, revHistory.getFirstChild());
    } else {
        revHistory.appendChild(revision);
    }
}

From source file:org.noerp.webtools.labelmanager.SaveLabelsToXmlFile.java

public static Map<String, Object> saveLabelsToXmlFile(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    Locale locale = (Locale) context.get("locale");
    String fileName = (String) context.get("fileName");
    if (UtilValidate.isEmpty(fileName)) {
        Debug.logError("labelFileName cannot be empty", module);
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resource,
                "saveLabelsToXmlFile.exceptionDuringSaveLabelsToXmlFile", locale));
    }//from w  w  w  .  j  ava 2s  .  c  om
    String key = (String) context.get("key");
    String keyComment = (String) context.get("keyComment");
    String update_label = (String) context.get("update_label");
    String confirm = (String) context.get("confirm");
    String removeLabel = (String) context.get("removeLabel");
    List<String> localeNames = UtilGenerics.cast(context.get("localeNames"));
    List<String> localeValues = UtilGenerics.cast(context.get("localeValues"));
    List<String> localeComments = UtilGenerics.cast(context.get("localeComments"));
    String apacheLicenseText = null;
    try {
        apacheLicenseText = FileUtil.readString("UTF-8",
                FileUtil.getFile("component://webtools/config/APACHE2_HEADER_FOR_XML"));
    } catch (IOException e) {
        Debug.logWarning(e, "Unable to read Apache License text file", module);
    }
    try {
        LabelManagerFactory factory = LabelManagerFactory.getInstance();
        LabelFile labelFile = factory.getLabelFile(fileName);
        if (labelFile == null) {
            Debug.logError("Invalid file name: " + fileName, module);
            return ServiceUtil.returnFailure(UtilProperties.getMessage(resource,
                    "saveLabelsToXmlFile.exceptionDuringSaveLabelsToXmlFile", locale));
        }
        synchronized (SaveLabelsToXmlFile.class) {
            factory.findMatchingLabels(null, fileName, null, null);
            Map<String, LabelInfo> labels = factory.getLabels();
            Set<String> labelsList = factory.getLabelsList();
            Set<String> localesFound = factory.getLocalesFound();
            for (String localeName : localeNames) {
                localesFound.add(localeName);
            }
            // Remove a Label
            if (UtilValidate.isNotEmpty(removeLabel)) {
                labels.remove(key + LabelManagerFactory.keySeparator + fileName);
            } else if (UtilValidate.isNotEmpty(confirm)) {
                LabelInfo label = labels.get(key + LabelManagerFactory.keySeparator + fileName);
                // Update a Label
                if (update_label.equalsIgnoreCase("Y")) {
                    if (UtilValidate.isNotEmpty(label)) {
                        factory.updateLabelValue(localeNames, localeValues, localeComments, label, key,
                                keyComment, fileName);
                    }
                    // Insert a new Label
                } else {
                    if (UtilValidate.isNotEmpty(label)) {
                        return ServiceUtil.returnError(
                                UtilProperties.getMessage(resource, "WebtoolsLabelManagerNewLabelExisting",
                                        UtilMisc.toMap("key", key, "fileName", fileName), locale));
                    } else {
                        if (UtilValidate.isEmpty(key)) {
                            return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                                    "WebtoolsLabelManagerNewLabelEmptyKey", locale));
                        } else {
                            int notEmptyLabels = factory.updateLabelValue(localeNames, localeValues,
                                    localeComments, null, key, keyComment, fileName);
                            if (notEmptyLabels == 0) {
                                return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                                        "WebtoolsLabelManagerNewLabelEmpty", locale));
                            }
                        }
                    }
                }
            }
            Document resourceDocument = UtilXml.makeEmptyXmlDocument("resource");
            Element resourceElem = resourceDocument.getDocumentElement();
            resourceElem.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            resourceElem.setAttribute("xsi:noNamespaceSchemaLocation",
                    "http://noerp.apache.org/dtds/noerp-properties.xsd");
            for (String labelKey : labelsList) {
                LabelInfo labelInfo = labels.get(labelKey);
                if (!(labelInfo.getFileName().equalsIgnoreCase(fileName))) {
                    continue;
                }
                Element propertyElem = UtilXml.addChildElement(resourceElem, "property", resourceDocument);
                propertyElem.setAttribute("key", StringEscapeUtils.unescapeHtml(labelInfo.getLabelKey()));
                if (UtilValidate.isNotEmpty(labelInfo.getLabelKeyComment())) {
                    Comment labelKeyComment = resourceDocument
                            .createComment(StringEscapeUtils.unescapeHtml(labelInfo.getLabelKeyComment()));
                    Node parent = propertyElem.getParentNode();
                    parent.insertBefore(labelKeyComment, propertyElem);
                }
                for (String localeFound : localesFound) {
                    LabelValue labelValue = labelInfo.getLabelValue(localeFound);
                    String valueString = null;
                    if (labelValue != null) {
                        valueString = labelValue.getLabelValue();
                    }
                    if (UtilValidate.isNotEmpty(valueString)) {
                        valueString = StringEscapeUtils.unescapeHtml(valueString);
                        Element valueElem = UtilXml.addChildElementValue(propertyElem, "value", valueString,
                                resourceDocument);
                        valueElem.setAttribute("xml:lang", localeFound);
                        if (UtilValidate.isNotEmpty(labelValue.getLabelComment())) {
                            Comment labelComment = resourceDocument.createComment(
                                    StringEscapeUtils.unescapeHtml(labelValue.getLabelComment()));
                            Node parent = valueElem.getParentNode();
                            parent.insertBefore(labelComment, valueElem);
                        }
                    }
                }
                FileOutputStream fos = new FileOutputStream(labelFile.file);
                try {
                    if (apacheLicenseText != null) {
                        fos.write(apacheLicenseText.getBytes());
                    }
                    UtilXml.writeXmlDocument(resourceElem, fos, "UTF-8", !(apacheLicenseText == null), true, 4);
                } finally {
                    fos.close();
                    // clear cache to see immediately the new labels and
                    // translations in OFBiz
                    UtilCache.clearCache("properties.UtilPropertiesBundleCache");
                }
            }
        }
    } catch (Exception e) {
        Debug.logError(e, "Exception during save labels to xml file:", module);
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resource,
                "saveLabelsToXmlFile.exceptionDuringSaveLabelsToXmlFile", locale));
    }
    return ServiceUtil.returnSuccess();
}

From source file:org.ofbiz.webtools.labelmanager.SaveLabelsToXmlFile.java

public static Map<String, Object> saveLabelsToXmlFile(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    Locale locale = (Locale) context.get("locale");
    String fileName = (String) context.get("fileName");
    if (UtilValidate.isEmpty(fileName)) {
        Debug.logError("labelFileName cannot be empty", module);
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resource,
                "saveLabelsToXmlFile.exceptionDuringSaveLabelsToXmlFile", locale));
    }/*from w  w  w  .  ja v  a  2s.c  o  m*/
    String key = (String) context.get("key");
    String keyComment = (String) context.get("keyComment");
    String update_label = (String) context.get("update_label");
    String confirm = (String) context.get("confirm");
    String removeLabel = (String) context.get("removeLabel");
    List<String> localeNames = UtilGenerics.cast(context.get("localeNames"));
    List<String> localeValues = UtilGenerics.cast(context.get("localeValues"));
    List<String> localeComments = UtilGenerics.cast(context.get("localeComments"));
    String apacheLicenseText = null;
    try {
        apacheLicenseText = FileUtil.readString("UTF-8",
                FileUtil.getFile("component://webtools/config/APACHE2_HEADER_FOR_XML"));
    } catch (IOException e) {
        Debug.logWarning(e, "Unable to read Apache License text file", module);
    }
    try {
        LabelManagerFactory factory = LabelManagerFactory.getInstance();
        LabelFile labelFile = factory.getLabelFile(fileName);
        if (labelFile == null) {
            Debug.logError("Invalid file name: " + fileName, module);
            return ServiceUtil.returnFailure(UtilProperties.getMessage(resource,
                    "saveLabelsToXmlFile.exceptionDuringSaveLabelsToXmlFile", locale));
        }
        synchronized (SaveLabelsToXmlFile.class) {
            factory.findMatchingLabels(null, fileName, null, null);
            Map<String, LabelInfo> labels = factory.getLabels();
            Set<String> labelsList = factory.getLabelsList();
            Set<String> localesFound = factory.getLocalesFound();
            for (String localeName : localeNames) {
                localesFound.add(localeName);
            }
            // Remove a Label
            if (UtilValidate.isNotEmpty(removeLabel)) {
                labels.remove(key + LabelManagerFactory.keySeparator + fileName);
            } else if (UtilValidate.isNotEmpty(confirm)) {
                LabelInfo label = labels.get(key + LabelManagerFactory.keySeparator + fileName);
                // Update a Label
                if (update_label.equalsIgnoreCase("Y")) {
                    if (UtilValidate.isNotEmpty(label)) {
                        factory.updateLabelValue(localeNames, localeValues, localeComments, label, key,
                                keyComment, fileName);
                    }
                    // Insert a new Label
                } else {
                    if (UtilValidate.isNotEmpty(label)) {
                        return ServiceUtil.returnError(
                                UtilProperties.getMessage(resource, "WebtoolsLabelManagerNewLabelExisting",
                                        UtilMisc.toMap("key", key, "fileName", fileName), locale));
                    } else {
                        if (UtilValidate.isEmpty(key)) {
                            return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                                    "WebtoolsLabelManagerNewLabelEmptyKey", locale));
                        } else {
                            int notEmptyLabels = factory.updateLabelValue(localeNames, localeValues,
                                    localeComments, null, key, keyComment, fileName);
                            if (notEmptyLabels == 0) {
                                return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                                        "WebtoolsLabelManagerNewLabelEmpty", locale));
                            }
                        }
                    }
                }
            }
            Document resourceDocument = UtilXml.makeEmptyXmlDocument("resource");
            Element resourceElem = resourceDocument.getDocumentElement();
            resourceElem.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            resourceElem.setAttribute("xsi:noNamespaceSchemaLocation",
                    "http://ofbiz.apache.org/dtds/ofbiz-properties.xsd");
            for (String labelKey : labelsList) {
                LabelInfo labelInfo = labels.get(labelKey);
                if (!(labelInfo.getFileName().equalsIgnoreCase(fileName))) {
                    continue;
                }
                Element propertyElem = UtilXml.addChildElement(resourceElem, "property", resourceDocument);
                propertyElem.setAttribute("key", StringEscapeUtils.unescapeHtml(labelInfo.getLabelKey()));
                if (UtilValidate.isNotEmpty(labelInfo.getLabelKeyComment())) {
                    Comment labelKeyComment = resourceDocument
                            .createComment(StringEscapeUtils.unescapeHtml(labelInfo.getLabelKeyComment()));
                    Node parent = propertyElem.getParentNode();
                    parent.insertBefore(labelKeyComment, propertyElem);
                }
                for (String localeFound : localesFound) {
                    LabelValue labelValue = labelInfo.getLabelValue(localeFound);
                    String valueString = null;
                    if (labelValue != null) {
                        valueString = labelValue.getLabelValue();
                    }
                    if (UtilValidate.isNotEmpty(valueString)) {
                        valueString = StringEscapeUtils.unescapeHtml(valueString);
                        Element valueElem = UtilXml.addChildElementValue(propertyElem, "value", valueString,
                                resourceDocument);
                        valueElem.setAttribute("xml:lang", localeFound);
                        if (UtilValidate.isNotEmpty(labelValue.getLabelComment())) {
                            Comment labelComment = resourceDocument.createComment(
                                    StringEscapeUtils.unescapeHtml(labelValue.getLabelComment()));
                            Node parent = valueElem.getParentNode();
                            parent.insertBefore(labelComment, valueElem);
                        }
                    }
                }
                FileOutputStream fos = new FileOutputStream(labelFile.file);
                try {
                    if (apacheLicenseText != null) {
                        fos.write(apacheLicenseText.getBytes());
                    }
                    UtilXml.writeXmlDocument(resourceElem, fos, "UTF-8", !(apacheLicenseText == null), true, 4);
                } finally {
                    fos.close();
                    // clear cache to see immediately the new labels and
                    // translations in OFBiz
                    UtilCache.clearCache("properties.UtilPropertiesBundleCache");
                }
            }
        }
    } catch (Exception e) {
        Debug.logError(e, "Exception during save labels to xml file:", module);
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resource,
                "saveLabelsToXmlFile.exceptionDuringSaveLabelsToXmlFile", locale));
    }
    return ServiceUtil.returnSuccess();
}

From source file:org.openehealth.coms.cc.web_frontend.consentcreator.service.DocumentFactory.java

/**
 * Constructs a CDA Consent for the given user.
 * /*from ww w.  j av a2 s . c om*/
 * @param user
 * @param policySet
 *            - null if either the participation should end or if a new
 *            PolicySet should be created.
 * @param author
 * @param participation
 *            - true if the user wants to participate, else false
 * @param out
 *            - The OutputStream on which the generated PDF presentation
 *            will be written
 * @return - The generated CDA file.
 * 
 */
public Document constructCDA(User user, Document policySet, User author, boolean participation,
        OutputStream out) {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document domCDA = null;
    Document domAssignedAuthor = null;
    Document domScanningDevice = null;
    Document domDataEnterer = null;
    Document domCustodian = null;
    Document domLegalAuthenticator = null;
    String cdaAsString = "";

    DocumentBuilder db = null;
    try {
        db = dbf.newDocumentBuilder();

        domCDA = db.parse(urlCdaSkeleton);
        domAssignedAuthor = db.parse(urlAssignedAuthor);
        domScanningDevice = db.parse(urlScanningDevice);
        domDataEnterer = db.parse(urlDataEnterer);
        domCustodian = db.parse(urlCustodian);
        domLegalAuthenticator = db.parse(urlLegalAuthenticator);

    } catch (Exception e) {
        Logger.getLogger(this.getClass()).error(e);
    }

    Date d = new Date();

    String uniqueID = RandomStringUtils.randomNumeric(64);

    domCDA.getElementsByTagName("id").item(0).getAttributes().item(0).setNodeValue(uniqueID);
    domCDA.getElementsByTagName("id").item(0).getAttributes().item(1)
            .setNodeValue("1.2.276.0.76.3.1.78.1.0.10.40");

    SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmssZ");

    domCDA.getElementsByTagName("effectiveTime").item(0).getAttributes().item(0).setTextContent(sd.format(d));

    Node title = domCDA.getElementsByTagName("title").item(0);

    if (participation) {
        title.setTextContent("Dies ist die Einwilligungserklrung fr die Teilnahme an ISIS von "
                + user.getForename() + " " + user.getName());
    } else {
        title.setTextContent("Dieses Dokument erklrt den Verzicht von " + user.getForename() + " "
                + user.getName() + " auf die Teilnahme an ISIS.");
    }

    Node pR = domCDA.getElementsByTagName("patientRole").item(0);

    NodeList prChildren = pR.getChildNodes();

    Node id = prChildren.item(1);

    // extension
    id.getAttributes().item(0).setNodeValue(user.getID()); // PID
    // root
    id.getAttributes().item(1).setNodeValue("1.2.276.0.76.3.1.78.1.0.10.20"); // Assigning
    // Authority

    NodeList addr = prChildren.item(3).getChildNodes();

    addr.item(1).setTextContent(user.getStreet());
    addr.item(3).setTextContent(user.getCity());
    addr.item(5).setTextContent("");//Hier knnte das Bundesland
    // stehen!

    addr.item(7).setTextContent(String.valueOf(user.getZipcode()));
    addr.item(9).setTextContent("Deutschland");// Es sollte nicht
    // standardmig Deutschland
    // gesetzt werden!

    NodeList pat = prChildren.item(5).getChildNodes();

    NodeList name = pat.item(1).getChildNodes();

    if (user.getGender().equalsIgnoreCase("male")) {
        name.item(1).setTextContent("Herr");
        pat.item(3).getAttributes().item(0).setTextContent("M");
    } else {
        name.item(1).setTextContent("Frau");
        pat.item(3).getAttributes().item(0).setTextContent("F");
    }
    name.item(3).setTextContent(user.getForename());
    name.item(5).setTextContent(user.getName());

    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");

    pat.item(5).getAttributes().item(0).setTextContent(formatter.format(user.getBirthdate()));

    if (policySet == null) {
        policySet = getSkeletonPolicySet(participation, user);

    }
    Document doc = db.newDocument();

    Element root = doc.createElement("component");
    doc.appendChild(root);

    Node copy = doc.importNode(policySet.getDocumentElement(), true);
    root.appendChild(copy);

    NodeList list = domCDA.getElementsByTagName("structuredBody");

    Node f = domCDA.importNode(doc.getDocumentElement(), true);

    list.item(0).appendChild(f);

    Node docuOfNode = domCDA.getElementsByTagName("documentationOf").item(0);

    if (author == user) {

        domAssignedAuthor.getElementsByTagName("time").item(0).getAttributes().item(0)
                .setNodeValue(sd.format(d));

        domAssignedAuthor.getElementsByTagName("id").item(0).getAttributes().item(0)
                .setNodeValue(author.getID()); // ID
        domAssignedAuthor.getElementsByTagName("id").item(0).getAttributes().item(1)
                .setNodeValue("1.2.276.0.76.3.1.78.1.0.10.20");// MPI-assigning
        // authority

        if (user.getGender().equalsIgnoreCase("male")) {
            domAssignedAuthor.getElementsByTagName("prefix").item(0).setTextContent("Herr");
        } else {
            name.item(1).setTextContent("Frau");
            domAssignedAuthor.getElementsByTagName("prefix").item(0).setTextContent("Frau");
        }

        // suffix Wert setzen
        // domAssignedAuthor.getElementsByTagName("suffix").item(0).getAttributes().item(0).setNodeValue("");

        domAssignedAuthor.getElementsByTagName("given").item(0).setTextContent(author.getForename());
        domAssignedAuthor.getElementsByTagName("family").item(0).setTextContent(author.getName());

        // TODO Werte setzen assignedPerson oder Werte loeschen
    } else if (author != user && author != null) {
        // Zukunft: Erzeugung durch Dritte
    } else {
        // Std values from AssignedAuthor.xml
    }

    Node copyAssignedAuthorNode = domCDA.importNode(domAssignedAuthor.getDocumentElement(), true);
    Node copyScanningDeviceNode = domCDA.importNode(domScanningDevice.getDocumentElement(), true);
    Node copyDataEntererNode = domCDA.importNode(domDataEnterer.getDocumentElement(), true);
    Node copyCustodianNode = domCDA.importNode(domCustodian.getDocumentElement(), true);
    Node copyLegalAuthenticator = domCDA.importNode(domLegalAuthenticator.getDocumentElement(), true);

    sd.applyPattern("yyyyMMdd");

    domCDA.getElementsByTagName("low").item(0).getAttributes().item(0).setNodeValue(sd.format(d));

    Date d2 = new Date((long) (d.getTime() + 30 * 3.1556926 * Math.pow(10, 10)));

    domCDA.getElementsByTagName("high").item(0).getAttributes().item(0).setNodeValue(sd.format(d2));

    copyAssignedAuthorNode.getChildNodes().item(3).getAttributes().item(0).setNodeValue(sd.format(d));

    Node clinicalDocumentNode = domCDA.getElementsByTagName("ClinicalDocument").item(0);

    clinicalDocumentNode.insertBefore(copyAssignedAuthorNode, docuOfNode);
    clinicalDocumentNode.insertBefore(copyScanningDeviceNode, docuOfNode);
    clinicalDocumentNode.insertBefore(copyDataEntererNode, docuOfNode);
    clinicalDocumentNode.insertBefore(copyCustodianNode, docuOfNode);
    clinicalDocumentNode.insertBefore(copyLegalAuthenticator, docuOfNode);

    Document noNSCDA = (Document) domCDA.cloneNode(true);

    NodeList l = noNSCDA.getElementsByTagName("ClinicalDocument");

    NamedNodeMap attributes = l.item(0).getAttributes();
    attributes.removeNamedItem("xmlns");
    attributes.removeNamedItem("xmlns:voc");
    attributes.removeNamedItem("xmlns:xsi");
    attributes.removeNamedItem("xsi:schemaLocation");

    l = noNSCDA.getElementsByTagName("PolicySet");
    attributes = l.item(0).getAttributes();
    attributes.removeNamedItem("xmlns");
    attributes.removeNamedItem("PolicyCombiningAlgId");
    attributes.removeNamedItem("xmlns:xsi");
    attributes.removeNamedItem("xsi:schemaLocation");
    attributes.removeNamedItem("PolicySetId");

    formatter = new SimpleDateFormat("dd.MM.yyyy");

    noNSCDA.getElementsByTagName("birthTime").item(0).getAttributes().item(0)
            .setTextContent(formatter.format(user.getBirthdate()));

    cdaAsString = getStringFromDocument(noNSCDA);
    Document nonXMLBody = constructPDF(cdaAsString, out);

    Node copyNode = domCDA.importNode(nonXMLBody.getDocumentElement(), true);

    Node component = domCDA.getElementsByTagName("component").item(0);

    Node structBody = component.getChildNodes().item(1);

    component.insertBefore(copyNode, structBody);

    NamedNodeMap nlm = domCDA.getDocumentElement().getElementsByTagName("PolicySet").item(0).getAttributes();
    // nlm.removeNamedItem("xmlns:xsi");
    // nlm.removeNamedItem("xsi:schemaLocation");

    return domCDA;
}

From source file:org.openehealth.coms.cc.web_frontend.consentcreator.service.DocumentFactory.java

/**
 * Adds a Document Rule to the given PolicySet.
 * /*  w w w. j  a  v a 2  s .  c o  m*/
 * @param policySet
 * @param rule
 * @param ruleType
 *            - defines to which Policy the rule will be added.
 * @return
 */
public Document addRuleToPolicySet(Document policySet, Document rule, int ruleType) {

    NodeList policies = policySet.getElementsByTagName("Policy");

    Node policy = policies.item(ruleType - 1);

    Vector<Node> ruleList = new Vector<Node>();

    for (int i = 0; i < policy.getChildNodes().getLength(); i++) {

        if (policy.getChildNodes().item(i).getNodeName().equalsIgnoreCase("Rule")) {

            ruleList.add(policy.getChildNodes().item(i));

        }
    }

    if (ruleList.size() > 0) {

        int ruleListLength = ruleList.size();

        String subjectOrgaNewRule = rule.getElementsByTagName("AttributeValue").item(0).getTextContent();

        String subjectPersonelNewRule = rule.getElementsByTagName("AttributeValue").item(1).getTextContent();

        String resourceNewRule = rule.getElementsByTagName("AttributeValue").item(2).getTextContent();

        int i = ruleListLength - 1;

        while (i >= 0) {

            String subjectOrgaRule = ruleList.elementAt(i).getChildNodes().item(3).getChildNodes().item(1)
                    .getChildNodes().item(1).getChildNodes().item(1).getChildNodes().item(1).getTextContent();
            String subjectPersonelRule = ruleList.elementAt(i).getChildNodes().item(3).getChildNodes().item(1)
                    .getChildNodes().item(1).getChildNodes().item(3).getChildNodes().item(1).getTextContent();
            String resourceRule = ruleList.elementAt(i).getChildNodes().item(3).getChildNodes().item(3)
                    .getChildNodes().item(1).getChildNodes().item(1).getChildNodes().item(1).getTextContent();

            if (getOIDLength(resourceRule) > getOIDLength(resourceNewRule)) {

                if (i == ruleListLength - 1) {

                    Node copy = policySet.importNode(rule.getDocumentElement(), true);

                    policy.appendChild(copy);
                } else {

                    Node copy = policySet.importNode(rule.getDocumentElement(), true);

                    policy.insertBefore(copy, ruleList.elementAt(i + 1));
                }
                i = -1;
            } else if (getOIDLength(resourceRule) == getOIDLength(resourceNewRule)) {

                if (getOIDLength(subjectOrgaRule) > getOIDLength(subjectOrgaNewRule)) {

                    Node copy = policySet.importNode(rule.getDocumentElement(), true);

                    if (i == ruleListLength - 1) {
                        policy.appendChild(copy);
                    } else {
                        policy.insertBefore(copy, ruleList.elementAt(i + 1));

                    }
                } else if (getOIDLength(subjectOrgaRule) == getOIDLength(subjectOrgaNewRule)) {

                    if (subjectPersonelRule.length() > subjectPersonelNewRule.length()) {

                        if (i == ruleListLength - 1) {

                            Node copy = policySet.importNode(rule.getDocumentElement(), true);

                            policy.appendChild(copy);
                        } else {

                            Node copy = policySet.importNode(rule.getDocumentElement(), true);

                            policy.insertBefore(copy, ruleList.elementAt(i + 1));
                        }
                        i = -1;

                    } else {

                        Node copy = policySet.importNode(rule.getDocumentElement(), true);
                        policy.insertBefore(copy, ruleList.elementAt(i));
                        i = -1;
                    }

                } else {

                    if (i == 0) {
                        Node copy = policySet.importNode(rule.getDocumentElement(), true);
                        policy.insertBefore(copy, ruleList.elementAt(i));
                        i = -1;
                    } else {
                        boolean added = false;

                        for (int t = i; t >= 0; t--) {

                            System.out.println(ruleList.elementAt(t).getChildNodes().item(3).getChildNodes()
                                    .item(1).getChildNodes().item(1).getChildNodes().item(1).getChildNodes()
                                    .item(1).getTextContent());

                            if (getOIDLength(resourceNewRule) == getOIDLength(ruleList.elementAt(t)
                                    .getChildNodes().item(3).getChildNodes().item(3).getChildNodes().item(1)
                                    .getChildNodes().item(1).getChildNodes().item(1).getTextContent())) {
                                // Grer gleich?
                                if (!(getOIDLength(subjectOrgaNewRule) > getOIDLength(ruleList.elementAt(t)
                                        .getChildNodes().item(3).getChildNodes().item(1).getChildNodes().item(1)
                                        .getChildNodes().item(1).getChildNodes().item(1).getTextContent()))) {

                                    if (!(subjectPersonelNewRule.length() > getOIDLength(
                                            ruleList.elementAt(t).getChildNodes().item(3).getChildNodes()
                                                    .item(1).getChildNodes().item(1).getChildNodes().item(3)
                                                    .getChildNodes().item(1).getTextContent()))) {

                                        if (t == ruleListLength - 1) {

                                            Node copy = policySet.importNode(rule.getDocumentElement(), true);

                                            policy.appendChild(copy);
                                        } else {

                                            Node copy = policySet.importNode(rule.getDocumentElement(), true);

                                            policy.insertBefore(copy, ruleList.elementAt(t + 1));
                                        }
                                        added = true;
                                        t = -1;

                                    } else {

                                        Node copy = policySet.importNode(rule.getDocumentElement(), true);
                                        policy.insertBefore(copy, ruleList.elementAt(t + 1));
                                        t = -1;
                                        added = true;
                                    }
                                }
                            } else {
                                Node copy = policySet.importNode(rule.getDocumentElement(), true);
                                policy.insertBefore(copy, ruleList.elementAt(t + 1));
                                t = -1;
                                added = true;
                            }
                        }
                        if (!added) {
                            Node copy = policySet.importNode(rule.getDocumentElement(), true);
                            policy.insertBefore(copy, ruleList.elementAt(0));
                            i = -1;
                        }
                    }
                }
                i = -1;
            } else if (getOIDLength(resourceRule) < getOIDLength(resourceNewRule) && i == 0) {

                Node copy = policySet.importNode(rule.getDocumentElement(), true);

                policy.insertBefore(copy, policy.getChildNodes().item(2));
                i = -1;
            }
            i--;
        }

    } else {
        Node copy = policySet.importNode(rule.getDocumentElement(), true);
        policy.appendChild(copy);
    }
    return policySet;
}

From source file:org.openengsb.openengsbplugin.base.ConfiguredMojo.java

private void insertConfigProfileIntoOrigPom(Document originalPom, Document mojoConfiguration,
        String profileName) throws XPathExpressionException {
    Node profileNode = mojoConfiguration.getFirstChild();

    Node idNode = mojoConfiguration.createElementNS(POM_NS_URI, "id");
    idNode.setTextContent(profileName);/*ww  w.  j a  va  2  s .c o  m*/
    profileNode.insertBefore(idNode, profileNode.getFirstChild());

    Node importedProfileNode = originalPom.importNode(profileNode, true);

    Tools.insertDomNode(originalPom, importedProfileNode, POM_PROFILE_XPATH, NS_CONTEXT);
}

From source file:org.regenstrief.util.XMLUtil.java

private final static boolean expandFragments(final Node parent, final Node ref, final Node frag) {
    if (frag instanceof DocumentFragment) {
        for (final Node child : new NodeArrayList(frag.getChildNodes())) { // Copy since we'll be modifying it
            if (!expandFragments(parent, ref, child)) {
                parent.insertBefore(child, ref);
            }/*from  w  w w .  j a v a  2  s .  com*/
        }
        parent.removeChild(frag);
        return true;
    }

    return false;
}