Example usage for org.w3c.dom Document cloneNode

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

Introduction

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

Prototype

public Node cloneNode(boolean deep);

Source Link

Document

Returns a duplicate of this node, i.e., serves as a generic copy constructor for nodes.

Usage

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

/**
 * Do the first topic pass on the database and check if the base XML is valid and set the Document Object's for each spec
 * topic. Also collect the ID Attributes that are used within the topics.
 *
 * @param buildData Information and data structures for the build.
 * @param topics    The list of topics to be checked and added to the database.
 * @throws BuildProcessingException Thrown if an unexpected error occurs during building.
 *//* w w w.  j  a v a2  s.c  o m*/
private void doTopicPass(final BuildData buildData, final Map<String, BaseTopicWrapper<?>> topics)
        throws BuildProcessingException {
    log.info("Doing " + buildData.getBuildLocale() + " First topic pass");

    // Check that we have some topics to process
    if (topics != null) {
        log.info("\tProcessing " + topics.size() + " Topics");

        final int showPercent = 10;
        final float total = topics.size();
        float current = 0;
        int lastPercent = 0;

        // Process each topic
        for (final Entry<String, BaseTopicWrapper<?>> topicEntry : topics.entrySet()) {
            final BaseTopicWrapper<?> topic = topicEntry.getValue();
            final String key = topicEntry.getKey();

            ++current;
            final int percent = Math.round(current / total * 100);
            if (percent - lastPercent >= showPercent) {
                lastPercent = percent;
                log.info("\tFirst topic Pass " + percent + "% Done");
            }

            // Get the Topic ID
            final Integer topicRevision = topic.getTopicRevision();

            boolean revHistoryTopic = topic.hasTag(buildData.getServerEntities().getRevisionHistoryTagId());
            boolean legalNoticeTopic = topic.hasTag(buildData.getServerEntities().getLegalNoticeTagId());
            boolean authorGroupTopic = topic.hasTag(buildData.getServerEntities().getAuthorGroupTagId());
            boolean abstractTopic = topic.hasTag(buildData.getServerEntities().getAbstractTagId());
            boolean infoTopic = topic.hasTag(buildData.getServerEntities().getInfoTagId());

            Document topicDoc = null;
            final String topicXML = topic.getXml();

            // Check if the app should be shutdown
            if (isShuttingDown.get()) {
                return;
            }

            boolean xmlValid = true;

            // Check that the Topic XML exists and isn't empty
            if (topicXML == null || topicXML.trim().isEmpty()) {
                buildData.getErrorDatabase().addWarning(topic, ErrorType.NO_CONTENT,
                        BuilderConstants.WARNING_EMPTY_TOPIC_XML);
                topicDoc = DocBookBuildUtilities.setTopicXMLForError(buildData, topic,
                        getErrorEmptyTopicTemplate().getValue());
                xmlValid = false;
            }

            // Check if the app should be shutdown
            if (isShuttingDown.get()) {
                return;
            }

            // Make sure we have valid XML
            if (xmlValid) {
                try {
                    final String fixedTopicXML;
                    if (buildData.getDocBookVersion() == DocBookVersion.DOCBOOK_50) {
                        fixedTopicXML = DocBookUtilities.addDocBook50Namespace(topicXML);
                    } else {
                        fixedTopicXML = topicXML;
                    }

                    topicDoc = XMLUtilities.convertStringToDocument(fixedTopicXML);

                    if (topicDoc == null) {
                        final String xmlStringInCDATA = XMLUtilities.wrapStringInCDATA(topic.getXml());
                        buildData.getErrorDatabase().addError(topic, ErrorType.INVALID_CONTENT,
                                BuilderConstants.ERROR_INVALID_XML_CONTENT
                                        + " The processed XML is <programlisting>" + xmlStringInCDATA
                                        + "</programlisting>");
                        topicDoc = DocBookBuildUtilities.setTopicXMLForError(buildData, topic,
                                getErrorInvalidValidationTopicTemplate().getValue());
                    }
                } catch (Exception ex) {
                    final String xmlStringInCDATA = XMLUtilities.wrapStringInCDATA(topic.getXml());
                    buildData.getErrorDatabase().addError(topic, ErrorType.INVALID_CONTENT,
                            BuilderConstants.ERROR_BAD_XML_STRUCTURE + " "
                                    + StringUtilities.escapeForXML(ex.getMessage())
                                    + " The processed XML is <programlisting>" + xmlStringInCDATA
                                    + "</programlisting>");
                    topicDoc = DocBookBuildUtilities.setTopicXMLForError(buildData, topic,
                            getErrorInvalidValidationTopicTemplate().getValue());
                }
            }

            // Make sure the topic has the correct root element and other items
            if (revHistoryTopic) {
                // If it is a translated build then check if we have anything more to merge together
                if (buildData.isTranslationBuild()) {
                    topicDoc = mergeAdditionalTranslatedXML(buildData, topicDoc, (TranslatedTopicWrapper) topic,
                            TopicType.REVISION_HISTORY);
                }

                DocBookUtilities.wrapDocumentInAppendix(topicDoc);
            } else if (authorGroupTopic) {
                // If it is a translated build then check if we have anything more to merge together
                if (buildData.isTranslationBuild()) {
                    topicDoc = mergeAdditionalTranslatedXML(buildData, topicDoc, (TranslatedTopicWrapper) topic,
                            TopicType.AUTHOR_GROUP);
                }

                DocBookUtilities.wrapDocumentInAuthorGroup(topicDoc);
            } else if (legalNoticeTopic) {
                DocBookUtilities.wrapDocumentInLegalNotice(topicDoc);
            } else if (abstractTopic) {
                DocBookUtilities.wrapDocument(topicDoc, "abstract");
            } else if (infoTopic) {
                if (buildData.getDocBookVersion() == DocBookVersion.DOCBOOK_50) {
                    DocBookUtilities.wrapDocument(topicDoc, "info");
                } else {
                    DocBookUtilities.wrapDocument(topicDoc, "sectioninfo");
                }
            } else {
                // Ensure the topic is wrapped in a section and the title matches the topic
                DocBookUtilities.wrapDocumentInSection(topicDoc);
                DocBookUtilities.setSectionTitle(buildData.getDocBookVersion(), topic.getTitle(), topicDoc);

                processTopicSectionInfo(buildData, topic, topicDoc);
            }

            // Add the document & topic to the database spec topics
            final List<ITopicNode> specTopics = buildData.getBuildDatabase().getTopicNodesForKey(key);
            for (final ITopicNode specTopic : specTopics) {
                // Check if the app should be shutdown
                if (isShuttingDown.get()) {
                    return;
                }

                if (buildData.getBuildOptions().getUseLatestVersions()) {
                    specTopic.setTopic(topic.clone(false));
                    specTopic.setXMLDocument((Document) topicDoc.cloneNode(true));
                } else {
                    /*
                     * Only set the topic for the spec topic if it matches the spec topic revision. If the Spec Topic
                     * Revision is null then we need to ensure that we get the latest version of the topic that was
                     * downloaded.
                     */
                    if ((specTopic.getRevision() == null && (specTopic.getTopic() == null
                            || specTopic.getTopic().getRevision() >= topicRevision))
                            || (specTopic.getRevision() != null && specTopic.getRevision() >= topicRevision)) {
                        specTopic.setTopic(topic.clone(false));
                        specTopic.setXMLDocument((Document) topicDoc.cloneNode(true));
                    }
                }
            }

        }
    } else {
        log.info("\tProcessing 0 Topics");
    }
}

From source file:org.ofbiz.shipment.thirdparty.usps.UspsServices.java

public static Map<String, Object> uspsPriorityMailInternationalLabel(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    String shipmentGatewayConfigId = (String) context.get("shipmentGatewayConfigId");
    String resource = (String) context.get("configProps");
    GenericValue shipmentRouteSegment = (GenericValue) context.get("shipmentRouteSegment");
    Locale locale = (Locale) context.get("locale");

    // Start the document
    Document requestDocument;
    boolean certify = false;
    String test = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "test", resource,
            "shipment.usps.test");
    if (!"Y".equalsIgnoreCase(test)) {
        requestDocument = createUspsRequestDocument("PriorityMailIntlRequest", false, delegator,
                shipmentGatewayConfigId, resource);
    } else {//from  www .  ja  v  a2 s  .  c o m
        requestDocument = createUspsRequestDocument("PriorityMailIntlCertifyRequest", false, delegator,
                shipmentGatewayConfigId, resource);
        certify = true;
    }
    Element rootElement = requestDocument.getDocumentElement();

    // Retrieve from/to address and package details
    GenericValue originAddress = null;
    GenericValue originTelecomNumber = null;
    GenericValue destinationAddress = null;
    GenericValue destinationProvince = null;
    GenericValue destinationCountry = null;
    GenericValue destinationTelecomNumber = null;
    List<GenericValue> shipmentPackageRouteSegs = null;
    try {
        originAddress = shipmentRouteSegment.getRelatedOne("OriginPostalAddress", false);
        originTelecomNumber = shipmentRouteSegment.getRelatedOne("OriginTelecomNumber", false);
        destinationAddress = shipmentRouteSegment.getRelatedOne("DestPostalAddress", false);
        if (destinationAddress != null) {
            destinationProvince = destinationAddress.getRelatedOne("StateProvinceGeo", false);
            destinationCountry = destinationAddress.getRelatedOne("CountryGeo", false);
        }
        destinationTelecomNumber = shipmentRouteSegment.getRelatedOne("DestTelecomNumber", false);
        shipmentPackageRouteSegs = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, null,
                false);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    if (originAddress == null || originTelecomNumber == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsPriorityMailLabelOriginAddressMissing", locale));
    }

    // Origin Info
    // USPS wants a separate first name and last, best we can do is split the string on the white space, if that doesn't work then default to putting the attnName in both fields
    String fromAttnName = originAddress.getString("attnName");
    String fromFirstName = StringUtils.defaultIfEmpty(StringUtils.substringBefore(fromAttnName, " "),
            fromAttnName);
    String fromLastName = StringUtils.defaultIfEmpty(StringUtils.substringAfter(fromAttnName, " "),
            fromAttnName);
    UtilXml.addChildElementValue(rootElement, "FromFirstName", fromFirstName, requestDocument);
    // UtilXml.addChildElementValue(rootElement, "FromMiddleInitial", "", requestDocument);
    UtilXml.addChildElementValue(rootElement, "FromLastName", fromLastName, requestDocument);
    UtilXml.addChildElementValue(rootElement, "FromFirm", originAddress.getString("toName"), requestDocument);
    // The following 2 assignments are not typos - USPS address1 = OFBiz address2, USPS address2 = OFBiz address1
    UtilXml.addChildElementValue(rootElement, "FromAddress1", originAddress.getString("address2"),
            requestDocument);
    UtilXml.addChildElementValue(rootElement, "FromAddress2", originAddress.getString("address1"),
            requestDocument);
    UtilXml.addChildElementValue(rootElement, "FromCity", originAddress.getString("city"), requestDocument);
    UtilXml.addChildElementValue(rootElement, "FromState", originAddress.getString("stateProvinceGeoId"),
            requestDocument);
    UtilXml.addChildElementValue(rootElement, "FromZip5", originAddress.getString("postalCode"),
            requestDocument);
    // USPS expects a phone number consisting of area code + contact number as a single numeric string
    String fromPhoneNumber = originTelecomNumber.getString("areaCode")
            + originTelecomNumber.getString("contactNumber");
    fromPhoneNumber = StringUtil.removeNonNumeric(fromPhoneNumber);
    UtilXml.addChildElementValue(rootElement, "FromPhone", fromPhoneNumber, requestDocument);

    // Destination Info
    UtilXml.addChildElementValue(rootElement, "ToName", destinationAddress.getString("attnName"),
            requestDocument);
    UtilXml.addChildElementValue(rootElement, "ToFirm", destinationAddress.getString("toName"),
            requestDocument);
    UtilXml.addChildElementValue(rootElement, "ToAddress1", destinationAddress.getString("address1"),
            requestDocument);
    UtilXml.addChildElementValue(rootElement, "ToAddress2", destinationAddress.getString("address2"),
            requestDocument);
    UtilXml.addChildElementValue(rootElement, "ToCity", destinationAddress.getString("city"), requestDocument);
    UtilXml.addChildElementValue(rootElement, "ToProvince", destinationProvince.getString("geoName"),
            requestDocument);
    // TODO: Test these country names, I think we're going to need to maintain a list of USPS names
    UtilXml.addChildElementValue(rootElement, "ToCountry", destinationCountry.getString("geoName"),
            requestDocument);
    UtilXml.addChildElementValue(rootElement, "ToPostalCode", destinationAddress.getString("postalCode"),
            requestDocument);
    // TODO: Figure out how to answer this question accurately
    UtilXml.addChildElementValue(rootElement, "ToPOBoxFlag", "N", requestDocument);
    String toPhoneNumber = destinationTelecomNumber.getString("countryCode")
            + destinationTelecomNumber.getString("areaCode")
            + destinationTelecomNumber.getString("contactNumber");
    UtilXml.addChildElementValue(rootElement, "ToPhone", toPhoneNumber, requestDocument);
    UtilXml.addChildElementValue(rootElement, "NonDeliveryOption", "RETURN", requestDocument);

    for (GenericValue shipmentPackageRouteSeg : shipmentPackageRouteSegs) {
        Document packageDocument = (Document) requestDocument.cloneNode(true);
        //Element packageRootElement = requestDocument.getDocumentElement();
        // This is our reference and can be whatever we want.  For lack of a better alternative we'll use shipmentId:shipmentPackageSeqId:shipmentRouteSegmentId
        String fromCustomsReference = shipmentRouteSegment.getString("shipmentId") + ":"
                + shipmentRouteSegment.getString("shipmentRouteSegmentId");
        fromCustomsReference = StringUtils.join(UtilMisc.toList(shipmentRouteSegment.get("shipmentId"),
                shipmentPackageRouteSeg.get("shipmentPackageSeqId"),
                shipmentRouteSegment.get("shipmentRouteSegementId")), ':');
        UtilXml.addChildElementValue(rootElement, "FromCustomsReference", fromCustomsReference,
                packageDocument);
        // Determine the container type for this package
        String container = "VARIABLE";
        String packageTypeCode = null;
        GenericValue shipmentPackage = null;
        List<GenericValue> shipmentPackageContents = null;
        try {
            shipmentPackage = shipmentPackageRouteSeg.getRelatedOne("ShipmentPackage", false);
            shipmentPackageContents = shipmentPackage.getRelated("ShipmentPackageContent", null, null, false);
            GenericValue shipmentBoxType = shipmentPackage.getRelatedOne("ShipmentBoxType", false);
            if (shipmentBoxType != null) {
                GenericValue carrierShipmentBoxType = EntityUtil.getFirst(shipmentBoxType
                        .getRelated("CarrierShipmentBoxType", UtilMisc.toMap("partyId", "USPS"), null, false));
                if (carrierShipmentBoxType != null) {
                    packageTypeCode = carrierShipmentBoxType.getString("packageTypeCode");
                    // Supported type codes
                    List<String> supportedPackageTypeCodes = UtilMisc.toList("LGFLATRATEBOX", "SMFLATRATEBOX",
                            "FLATRATEBOX", "MDFLATRATEBOX", "FLATRATEENV");
                    if (supportedPackageTypeCodes.contains(packageTypeCode)) {
                        container = packageTypeCode;
                    }
                }
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
        UtilXml.addChildElementValue(rootElement, "Container", container, packageDocument);
        /* TODO:
        UtilXml.addChildElementValue(rootElement, "Insured", "", packageDocument);
        UtilXml.addChildElementValue(rootElement, "InsuredNumber", "", packageDocument);
        UtilXml.addChildElementValue(rootElement, "InsuredAmount", "", packageDocument);
        */
        // According to the docs sending an empty postage tag will cause the postage to be calculated
        UtilXml.addChildElementValue(rootElement, "Postage", "", packageDocument);

        BigDecimal packageWeight = shipmentPackage.getBigDecimal("weight");
        String weightUomId = shipmentPackage.getString("weightUomId");
        BigDecimal packageWeightPounds = UomWorker.convertUom(packageWeight, weightUomId, "WT_lb", dispatcher);
        Integer[] packagePoundsOunces = convertPoundsToPoundsOunces(packageWeightPounds);
        UtilXml.addChildElementValue(rootElement, "GrossPounds", packagePoundsOunces[0].toString(),
                packageDocument);
        UtilXml.addChildElementValue(rootElement, "GrossOunces", packagePoundsOunces[1].toString(),
                packageDocument);

        UtilXml.addChildElementValue(rootElement, "ContentType", "MERCHANDISE", packageDocument);
        UtilXml.addChildElementValue(rootElement, "Agreement", "N", packageDocument);
        UtilXml.addChildElementValue(rootElement, "ImageType", "PDF", packageDocument);
        // TODO: Try the different layouts
        UtilXml.addChildElementValue(rootElement, "ImageType", "ALLINONEFILE", packageDocument);
        UtilXml.addChildElementValue(rootElement, "CustomerRefNo", fromCustomsReference, packageDocument);

        // Add the shipping contents
        Element shippingContents = UtilXml.addChildElement(rootElement, "ShippingContents", packageDocument);
        for (GenericValue shipmentPackageContent : shipmentPackageContents) {
            Element itemDetail = UtilXml.addChildElement(shippingContents, "ItemDetail", packageDocument);
            GenericValue product = null;
            GenericValue originGeo = null;
            try {
                GenericValue shipmentItem = shipmentPackageContent.getRelatedOne("ShipmentItem", false);
                product = shipmentItem.getRelatedOne("Product", false);
                originGeo = product.getRelatedOne("OriginGeo", false);
            } catch (GenericEntityException e) {
                Debug.logInfo(e, module);
            }

            UtilXml.addChildElementValue(itemDetail, "Description", product.getString("productName"),
                    packageDocument);
            UtilXml.addChildElementValue(itemDetail, "Quantity", shipmentPackageContent
                    .getBigDecimal("quantity").setScale(0, BigDecimal.ROUND_CEILING).toPlainString(),
                    packageDocument);
            String packageContentValue = ShipmentWorker.getShipmentPackageContentValue(shipmentPackageContent)
                    .setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString();
            UtilXml.addChildElementValue(itemDetail, "Value", packageContentValue, packageDocument);
            BigDecimal productWeight = ProductWorker.getProductWeight(product, "WT_lbs", delegator, dispatcher);
            Integer[] productPoundsOunces = convertPoundsToPoundsOunces(productWeight);
            UtilXml.addChildElementValue(itemDetail, "NetPounds", productPoundsOunces[0].toString(),
                    packageDocument);
            UtilXml.addChildElementValue(itemDetail, "NetOunces", productPoundsOunces[1].toString(),
                    packageDocument);
            UtilXml.addChildElementValue(itemDetail, "HSTariffNumber", "", packageDocument);
            UtilXml.addChildElementValue(itemDetail, "CountryOfOrigin", originGeo.getString("geoName"),
                    packageDocument);
        }

        // Send the request
        Document responseDocument = null;
        String api = certify ? "PriorityMailIntlCertify" : "PriorityMailIntl";
        try {
            responseDocument = sendUspsRequest(api, requestDocument, delegator, shipmentGatewayConfigId,
                    resource, locale);
        } catch (UspsRequestException e) {
            Debug.logInfo(e, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsPriorityMailLabelSendingError",
                    UtilMisc.toMap("errorString", e.getMessage()), locale));
        }
        Element responseElement = responseDocument.getDocumentElement();

        // TODO: No mention of error returns in the docs

        String labelImageString = UtilXml.childElementValue(responseElement, "LabelImage");
        if (UtilValidate.isEmpty(labelImageString)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsPriorityMailLabelResponseIncompleteElementLabelImage", locale));
        }
        shipmentPackageRouteSeg.setBytes("labelImage", Base64.base64Decode(labelImageString.getBytes()));
        String trackingCode = UtilXml.childElementValue(responseElement, "BarcodeNumber");
        if (UtilValidate.isEmpty(trackingCode)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsPriorityMailLabelResponseIncompleteElementBarcodeNumber", locale));
        }
        shipmentPackageRouteSeg.set("trackingCode", trackingCode);
        try {
            shipmentPackageRouteSeg.store();
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }

    }
    return ServiceUtil.returnSuccess();
}

From source file:org.ojbc.util.fedquery.processor.PrepareFederatedQueryMessage.java

Document removeSystemNamesNotIntendedForAdapter(Document requestMessage, String endpointUriValue) {

    //We need to clone the node because the recipient list message is mutable
    Document clonedRequestDocument = (Document) requestMessage.cloneNode(true);
    NodeList sourceSystems = clonedRequestDocument.getElementsByTagName("SourceSystemNameText");

    Set<Node> targetElementsToRemove = new HashSet<Node>();

    //Loop through the source systems and remove any source systems that don't match the system we are calling
    //We can't remove them from the live list so we put them in a set and remove later
    //http://stackoverflow.com/questions/1374088/removing-dom-nodes-when-traversing-a-nodelist
    for (int s = 0; s < sourceSystems.getLength(); s++) {

        Node sourceSystemNode = sourceSystems.item(s);

        if (sourceSystemNode.getNodeType() == Node.ELEMENT_NODE) {

            String currentSourceSystemNode = sourceSystemNode.getTextContent();

            if (!currentSourceSystemNode.equals(endpointUriValue)) {
                targetElementsToRemove.add(sourceSystemNode);
            }/*from  w  w w . java 2  s . c o  m*/
        }

    }

    for (Node e : targetElementsToRemove) {
        e.getParentNode().removeChild(e);
    }

    //Set the message body of the modified message
    return clonedRequestDocument;
}

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

/**
 * Constructs a CDA Consent for the given user.
 * /*from   ww  w .  ja va 2 s  .  c o  m*/
 * @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;
}