Example usage for org.w3c.dom Node removeChild

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

Introduction

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

Prototype

public Node removeChild(Node oldChild) throws DOMException;

Source Link

Document

Removes the child node indicated by oldChild from the list of children, and returns it.

Usage

From source file:com.panet.imeta.trans.steps.xmlinput.XMLInput.java

private Object[] getRowFromXML() throws KettleValueException {
    // finished reading the file, read the next file

    while (data.itemPosition >= data.itemCount || data.file == null) {
        data.file = null;/*from  ww w.j  av  a 2s. c o  m*/
        if (!openNextFile()) {
            return null;
        }
    }

    Object[] outputRowData = buildEmptyRow();

    // Get the item in the XML file...

    // First get the appropriate node

    Node itemNode;
    if (meta.getInputPosition().length > 1) {
        itemNode = XMLHandler.getSubNodeByNr(data.section, data.itemElement, data.itemPosition);
    } else {
        itemNode = data.section; // Only the root node, 1 element to read
        // in the whole document.
    }
    data.itemPosition++;

    // Read from the Node...
    for (int i = 0; i < meta.getInputFields().length; i++) {
        Node node = itemNode;

        XMLInputField xmlInputField = meta.getInputFields()[i];

        // This value will contain the value we're looking for...
        //
        String value = null;

        for (int p = 0; (value == null) && node != null && p < xmlInputField.getFieldPosition().length; p++) {
            XMLInputFieldPosition pos = xmlInputField.getFieldPosition()[p];

            switch (pos.getType()) {
            case XMLInputFieldPosition.XML_ELEMENT: {
                if (pos.getElementNr() <= 1) {
                    Node subNode = XMLHandler.getSubNode(node, pos.getName());
                    if (subNode != null) {
                        if (p == xmlInputField.getFieldPosition().length - 1) // last
                        // level
                        {
                            value = XMLHandler.getNodeValue(subNode);
                        }
                    } else {
                        if (log.isDebug())
                            logDebug(Messages.getString("XMLInput.Log.UnableToFindPosition", pos.toString(),
                                    node.toString()));
                    }
                    node = subNode;
                } else
                // Multiple possible values: get number
                // pos.getElementNr()!
                {
                    Node subNode = XMLHandler.getSubNodeByNr(node, pos.getName(), pos.getElementNr() - 1,
                            false);
                    if (subNode != null) {
                        if (p == xmlInputField.getFieldPosition().length - 1) // last
                        // level
                        {
                            value = XMLHandler.getNodeValue(subNode);
                        }
                    } else {
                        if (log.isDebug())
                            logDebug(Messages.getString("XMLInput.Log.UnableToFindPosition", pos.toString(),
                                    node.toString()));
                    }
                    node = subNode;
                }
            }
                break;

            case XMLInputFieldPosition.XML_ATTRIBUTE: {
                value = XMLHandler.getTagAttribute(node, pos.getName());
            }
                break;
            case XMLInputFieldPosition.XML_ROOT: {
                value = XMLHandler.getNodeValue(node);
            }
                break;
            default:
                break;
            }

        }

        // OK, we have grabbed the string called value
        // Trim it, convert it, ...

        // DO Trimming!
        switch (xmlInputField.getTrimType()) {
        case XMLInputField.TYPE_TRIM_LEFT:
            value = Const.ltrim(value);
            break;
        case XMLInputField.TYPE_TRIM_RIGHT:
            value = Const.rtrim(value);
            break;
        case XMLInputField.TYPE_TRIM_BOTH:
            value = Const.trim(value);
            break;
        default:
            break;
        }

        // System.out.println("after trim, field #"+i+" : "+v);

        // DO CONVERSIONS...
        //
        ValueMetaInterface targetValueMeta = data.outputRowMeta.getValueMeta(i);
        ValueMetaInterface sourceValueMeta = data.convertRowMeta.getValueMeta(i);
        outputRowData[i] = targetValueMeta.convertData(sourceValueMeta, value);

        // Do we need to repeat this field if it is null?
        if (meta.getInputFields()[i].isRepeated()) {
            if (data.previousRow != null && Const.isEmpty(value)) {
                outputRowData[i] = data.previousRow[i];
            }
        }
    } // End of loop over fields...

    int outputIndex = meta.getInputFields().length;

    // See if we need to add the filename to the row...
    if (meta.includeFilename() && !Const.isEmpty(meta.getFilenameField())) {
        outputRowData[outputIndex++] = KettleVFS.getFilename(data.file);
    }

    // See if we need to add the row number to the row...
    if (meta.includeRowNumber() && !Const.isEmpty(meta.getRowNumberField())) {
        outputRowData[outputIndex++] = new Long(data.rownr);
    }

    RowMetaInterface irow = getInputRowMeta();

    data.previousRow = irow == null ? outputRowData : (Object[]) irow.cloneRow(outputRowData); // copy it to make
    // surely the next step doesn't change it in between...
    data.rownr++;

    // Throw away the information in the item?
    NodeList nodeList = itemNode.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        itemNode.removeChild(nodeList.item(i));
    }

    return outputRowData;
}

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  a v a  2s  .  c o 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:be.ibridge.kettle.trans.step.xmlinput.XMLInput.java

private Row getRowFromXML() throws KettleValueException {
    while (data.itemPosition >= data.itemCount || data.file == null) // finished reading the file, read the next file!
    {//from w w  w  .  j  av  a2s. co m
        data.file = null;
        if (!openNextFile()) {
            return null;
        }
    }

    Row row = buildEmptyRow();

    // Get the item in the XML file...

    // First get the appropriate node

    Node itemNode;
    if (meta.getInputPosition().length > 1) {
        itemNode = XMLHandler.getSubNodeByNr(data.section, data.itemElement, data.itemPosition);
    } else {
        itemNode = data.section; // Only the root node, 1 element to read in the whole document.
    }
    data.itemPosition++;

    // Read from the Node...
    for (int i = 0; i < meta.getInputFields().length; i++) {
        Node node = itemNode;

        XMLInputField xmlInputField = meta.getInputFields()[i];

        String value = null;

        for (int p = 0; (value == null) && node != null && p < xmlInputField.getFieldPosition().length; p++) {
            XMLInputFieldPosition pos = xmlInputField.getFieldPosition()[p];

            switch (pos.getType()) {
            case XMLInputFieldPosition.XML_ELEMENT: {
                if (pos.getElementNr() <= 1) {
                    Node subNode = XMLHandler.getSubNode(node, pos.getName());
                    if (subNode != null) {
                        if (p == xmlInputField.getFieldPosition().length - 1) // last level
                        {
                            value = XMLHandler.getNodeValue(subNode);
                        }
                    } else {
                        if (log.isDebug())
                            logDebug(Messages.getString("XMLInput.Log.UnableToFindPosition", pos.toString(),
                                    node.toString()));
                    }
                    node = subNode;
                } else // Multiple possible values: get number pos.getElementNr()!
                {
                    Node subNode = XMLHandler.getSubNodeByNr(node, pos.getName(), pos.getElementNr() - 1,
                            false);
                    if (subNode != null) {
                        if (p == xmlInputField.getFieldPosition().length - 1) // last level
                        {
                            value = XMLHandler.getNodeValue(subNode);
                        }
                    } else {
                        if (log.isDebug())
                            logDebug(Messages.getString("XMLInput.Log.UnableToFindPosition", pos.toString(),
                                    node.toString()));
                    }
                    node = subNode;
                }
            }
                break;

            case XMLInputFieldPosition.XML_ATTRIBUTE: {
                value = XMLHandler.getTagAttribute(node, pos.getName());
            }
                break;
            case XMLInputFieldPosition.XML_ROOT: {
                value = XMLHandler.getNodeValue(node);
            }
                break;
            default:
                break;
            }

        }

        // OK, we have the string...
        Value v = row.getValue(i);

        if (value != null)
            v.setValue(value);
        else
            v.setNull();

        // DO Trimming!
        switch (xmlInputField.getTrimType()) {
        case XMLInputField.TYPE_TRIM_LEFT:
            v.ltrim();
            break;
        case XMLInputField.TYPE_TRIM_RIGHT:
            v.rtrim();
            break;
        case XMLInputField.TYPE_TRIM_BOTH:
            v.trim();
            break;
        default:
            break;
        }

        // System.out.println("after trim, field #"+i+" : "+v);

        // DO CONVERSIONS...
        switch (xmlInputField.getType()) {
        case Value.VALUE_TYPE_STRING:
            // System.out.println("Convert value to String :"+v);
            break;
        case Value.VALUE_TYPE_NUMBER:
            // System.out.println("Convert value to Number :"+v);
            if (xmlInputField.getFormat() != null && xmlInputField.getFormat().length() > 0) {
                if (xmlInputField.getDecimalSymbol() != null && xmlInputField.getDecimalSymbol().length() > 0) {
                    if (xmlInputField.getGroupSymbol() != null && xmlInputField.getGroupSymbol().length() > 0) {
                        if (xmlInputField.getCurrencySymbol() != null
                                && xmlInputField.getCurrencySymbol().length() > 0) {
                            v.str2num(xmlInputField.getFormat(), xmlInputField.getGroupSymbol(),
                                    xmlInputField.getGroupSymbol(), xmlInputField.getCurrencySymbol());
                        } else {
                            v.str2num(xmlInputField.getFormat(), xmlInputField.getGroupSymbol(),
                                    xmlInputField.getGroupSymbol());
                        }
                    } else {
                        v.str2num(xmlInputField.getFormat(), xmlInputField.getGroupSymbol());
                    }
                } else {
                    v.str2num(xmlInputField.getFormat()); // just a format mask
                }
            } else {
                v.str2num();
            }
            v.setLength(xmlInputField.getLength(), xmlInputField.getPrecision());
            break;
        case Value.VALUE_TYPE_INTEGER:
            // System.out.println("Convert value to integer :"+v);
            v.setValue(v.getInteger());
            v.setLength(xmlInputField.getLength(), xmlInputField.getPrecision());
            break;
        case Value.VALUE_TYPE_BIGNUMBER:
            // System.out.println("Convert value to BigNumber :"+v);
            v.setValue(v.getBigNumber());
            v.setLength(xmlInputField.getLength(), xmlInputField.getPrecision());
            break;
        case Value.VALUE_TYPE_DATE:
            // System.out.println("Convert value to Date :"+v);

            if (xmlInputField.getFormat() != null && xmlInputField.getFormat().length() > 0) {
                v.str2dat(xmlInputField.getFormat());
            } else {
                v.setValue(v.getDate());
            }
            break;
        case Value.VALUE_TYPE_BOOLEAN:
            v.setValue(v.getBoolean());
            break;
        default:
            break;
        }

        // Do we need to repeat this field if it is null?
        if (meta.getInputFields()[i].isRepeated()) {
            if (v.isNull() && data.previousRow != null) {
                Value previous = data.previousRow.getValue(i);
                v.setValue(previous);
            }
        }

    } // End of loop over fields...

    // See if we need to add the filename to the row...  
    if (meta.includeFilename() && meta.getFilenameField() != null && meta.getFilenameField().length() > 0) {
        Value fn = new Value(meta.getFilenameField(), KettleVFS.getFilename(data.file));
        row.addValue(fn);
    }

    // See if we need to add the row number to the row...  
    if (meta.includeRowNumber() && meta.getRowNumberField() != null && meta.getRowNumberField().length() > 0) {
        Value fn = new Value(meta.getRowNumberField(), data.rownr);
        row.addValue(fn);
    }

    data.previousRow = new Row(row); // copy it to make sure the next step doesn't change it in between... 
    data.rownr++;

    // Throw away the information in the item?
    NodeList nodeList = itemNode.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++)
        itemNode.removeChild(nodeList.item(i));

    return row;
}

From source file:nl.vumc.trait.oc.main.ImportODM.java

@Override
public void runCmd() throws ParserConfigurationException, DatatypeConfigurationException, ODMException,
        OCConnectorException, SAXException, IOException {
    OCWebServices connector = OCWebServices.getInstance(connectInfo, debug, false);
    InputStream reader;/*from  w  w w  .  j ava2  s.  c o m*/
    if (file.equals("-")) {
        reader = System.in;
    } else {
        reader = new FileInputStream(file);
    }
    ClinicalODMResolver odm = new ClinicalODMResolver(documentBuilder.parse(reader), connector, true);
    odm.resolveOdmDocument();
    Document odmDoc = odm.getOdm();
    Node odmNode = odm.getOdm().getFirstChild();
    // bulk load -- chop up into ClinicaDatas...
    NodeList clinicalDatas = odm.xPath(odmNode, "//ClinicalData");
    for (int i = 0; i < clinicalDatas.getLength(); ++i) {
        odmNode.removeChild(clinicalDatas.item(i));
    }
    for (int i = 0; i < clinicalDatas.getLength(); ++i) {
        odmNode.appendChild(clinicalDatas.item(i));
        logger.debug("============================ setOdm start =================");
        odm.setOdm(odmDoc); // important!
        logger.debug("Current ODM:\n" + odm.extraClean().toString());
        logger.debug("============================ setOdm end ===================");
        connector.importODM(odm.extraClean().toString());
        odmNode.removeChild(clinicalDatas.item(i));
    }
}

From source file:org.adl.parsers.dom.ADLDOMParser.java

/**
 * Traverses the DOM Tree and removes Ignorable Whitespace Text Nodes and
 * Comment Text.  The function also removes extension elements and
 * attributes that are not defined by SCORM.  If extensions are found
 * the function also sets a flag stating that extensions are present in the
 * input XML instance./*ww  w .  j a v a  2s.com*/
 *
 * @param iNode The node to be pruned of whitespace and comments<br>
 * @param iXMLFileName The XML file to be pruned
 */
private void pruneTree(Node iNode, String iXMLFileName) {
    String value;

    // is there anything to do?
    if (iNode == null)
        return;

    switch (iNode.getNodeType()) {
    case Node.PROCESSING_INSTRUCTION_NODE: {
        break;
    }
    case Node.DOCUMENT_NODE: {
        pruneTree(((Document) iNode).getDocumentElement(), iXMLFileName);
        break;
    }
    case Node.ELEMENT_NODE: {
        log.debug("Processing Element Node: [" + iNode.getLocalName() + "]");
        log.debug("************************************************");
        log.debug("Processing Element Node: [" + iNode.getLocalName() + "]");

        checkForSchemaLocations(iNode, iXMLFileName);

        // Get the list of attributes of the element
        NamedNodeMap attrList = iNode.getAttributes();

        // Loop over the attributes for this element, remove any attributes
        // that are extensions
        log.debug("Processing " + attrList.getLength() + " attributes");
        for (int i = 0; i < attrList.getLength(); i++) {
            Attr currentAttribute = (Attr) attrList.item(i);

            if (!(DOMTreeUtility.isSCORMAppProfileNode(currentAttribute, iNode))) {
                log.debug("Extension attribute, removing: [" + currentAttribute.getNamespaceURI() + "] "
                        + currentAttribute.getLocalName() + " from the its parent node ["
                        + iNode.getNamespaceURI() + "] " + iNode.getLocalName());

                // Remove the Element Node from the DOM
                attrList.removeNamedItemNS(currentAttribute.getNamespaceURI(), currentAttribute.getLocalName());
                i--;
                mExtensionsFound = true;
            } else {
                log.debug("Valid SCORM attribute, keeping attribute: [" + currentAttribute.getNamespaceURI()
                        + "] " + currentAttribute.getLocalName());
            }
        }

        log.debug("Done processing attributes for node: [" + iNode.getNamespaceURI() + "] "
                + iNode.getLocalName());
        log.debug("************************************************");

        // Done looping over the attributes for this element, now loop over
        // the set of children nodes.

        log.debug("");
        log.debug("************************************************");
        log.debug("Processing direct-descendances for node: [" + iNode.getNamespaceURI() + "] "
                + iNode.getLocalName());

        NodeList children = iNode.getChildNodes();
        if (children != null) {
            // Loop over set of children elements for this element, remove
            // any elements that are extensions
            log.debug("Processing " + children.getLength() + " elements");
            for (int z = 0; z < children.getLength(); z++) {
                Node childNode = children.item(z);

                if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                    log.debug("Processing element: [" + childNode + "]");
                    log.debug("Elements Namespace: [" + childNode.getNamespaceURI() + "]");
                    log.debug("Elements Parent Node: [" + iNode.getLocalName() + "]");
                    log.debug("Parent Nodes Namespace: [" + iNode.getNamespaceURI() + "]");

                    if (!(DOMTreeUtility.isSCORMAppProfileNode(children.item(z),
                            children.item(z).getParentNode()))) {
                        // Before we remove the element see if the elemen
                        // contains any xsi:schemaLocations.  We need
                        // to add them to the list of schema locations for 
                        // parsing
                        checkForSchemaLocations(childNode, iXMLFileName);

                        log.debug("Extension Element Found, removing from DOM Tree ");

                        // Remove the Element Node from the DOM
                        children.item(z).getParentNode().removeChild(children.item(z));
                        z--;
                        mExtensionsFound = true;
                    } else {
                        log.debug("ADL SCORM Element Found, leaving " + "element in DOM Tree");
                        pruneTree(children.item(z), iXMLFileName);
                    }
                } // end if NodeType == ELEMENT_NODE

                if (childNode instanceof TextImpl) {
                    value = children.item(z).getNodeValue().trim();

                    if (((TextImpl) children.item(z)).isIgnorableWhitespace()) {
                        iNode.removeChild(children.item(z));
                        z--;
                    } else if (value.length() == 0) {
                        iNode.removeChild(children.item(z));
                        z--;
                    }
                } else if (children.item(z).getNodeType() == Node.COMMENT_NODE) {
                    iNode.removeChild(children.item(z));
                    z--;
                }
            } // end looping over children nodes
        } // end if there are children

        log.debug("Done processing direct-descendants for node: [" + iNode.getNamespaceURI() + "] "
                + iNode.getLocalName());
        log.debug("**************************************************");

        break;

    }

    // handle entity reference nodes
    case Node.ENTITY_REFERENCE_NODE: {

        NodeList children = iNode.getChildNodes();
        if (children != null) {
            int len = children.getLength();
            for (int i = 0; i < len; i++) {
                pruneTree(children.item(i), iXMLFileName);
            }
        }
        break;
    }

    // text
    case Node.COMMENT_NODE: {
        break;
    }
    case Node.CDATA_SECTION_NODE: {
        break;
    }
    case Node.TEXT_NODE: {
        break;
    }
    default: {
        break;
    }
    }
}

From source file:org.apache.cayenne.xml.XMLUtil.java

/**
 * Moves all children of the oldParent to the newParent
 *//*w ww. ja va2s . co m*/
static List<Element> replaceParent(Node oldParent, Node newParent) {

    List<Element> children = XMLUtil.getChildren(oldParent);
    for (Node child : children) {
        oldParent.removeChild(child);
        newParent.appendChild(child);
    }

    return children;
}

From source file:org.apache.cocoon.xml.dom.DOMUtil.java

/**
 * Set the value of the DOM node.// www.j  av  a  2s.com
 * All current children of the node are removed and a new text node
 * with the value is appended.
 */
public static void setValueOfNode(Node node, String value) {
    if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        node.setNodeValue(value);
    } else {
        while (node.hasChildNodes() == true) {
            node.removeChild(node.getFirstChild());
        }
        node.appendChild(node.getOwnerDocument().createTextNode(value));
    }
}

From source file:org.apache.cocoon.xml.dom.DOMUtil.java

/**
 * Get a document fragment from a <code>Reader</code>.
 * The reader must provide valid XML, but it is allowed that the XML
 * has more than one root node. This xml is parsed by the
 * specified parser instance and a DOM DocumentFragment is created.
 *///  ww  w  . java  2  s.c  o  m
public static DocumentFragment getDocumentFragment(SAXParser parser, Reader stream) throws ProcessingException {
    DocumentFragment frag = null;

    Writer writer;
    Reader reader;
    boolean removeRoot = true;

    try {
        // create a writer,
        // write the root element, then the input from the
        // reader
        writer = new StringWriter();

        writer.write(XML_ROOT_DEFINITION);
        char[] cbuf = new char[16384];
        int len;
        do {
            len = stream.read(cbuf, 0, 16384);
            if (len != -1) {
                writer.write(cbuf, 0, len);
            }
        } while (len != -1);
        writer.write("</root>");

        // now test if xml input start with <?xml
        String xml = writer.toString();
        String searchString = XML_ROOT_DEFINITION + "<?xml ";
        if (xml.startsWith(searchString) == true) {
            // now remove the surrounding root element
            xml = xml.substring(XML_ROOT_DEFINITION.length(), xml.length() - 7);
            removeRoot = false;
        }

        reader = new StringReader(xml);

        InputSource input = new InputSource(reader);

        DOMBuilder builder = new DOMBuilder();
        builder.startDocument();
        builder.startElement("", "root", "root", XMLUtils.EMPTY_ATTRIBUTES);

        IncludeXMLConsumer filter = new IncludeXMLConsumer(builder, builder);
        parser.parse(input, filter);

        builder.endElement("", "root", "root");
        builder.endDocument();

        // Create Document Fragment, remove <root>
        final Document doc = builder.getDocument();
        frag = doc.createDocumentFragment();
        final Node root = doc.getDocumentElement().getFirstChild();
        root.normalize();
        if (removeRoot == false) {
            root.getParentNode().removeChild(root);
            frag.appendChild(root);
        } else {
            Node child;
            while (root.hasChildNodes() == true) {
                child = root.getFirstChild();
                root.removeChild(child);
                frag.appendChild(child);
            }
        }
    } catch (SAXException sax) {
        throw new ProcessingException("SAXException: " + sax, sax);
    } catch (IOException ioe) {
        throw new ProcessingException("IOException: " + ioe, ioe);
    }
    return frag;
}

From source file:org.apache.ode.bpel.rtrep.v1.ASSIGN.java

/**
 * isInsert flag desginates this as an 'element' type insertion, which
 * requires insert the actual element value, rather than it's children
 *
 * @return// w  w w . j ava 2s .  com
 * @throws FaultException
 */
private Node replaceContent(Node lvalue, Node lvaluePtr, String rvalue) throws FaultException {
    Document d = lvaluePtr.getOwnerDocument();

    if (__log.isDebugEnabled()) {
        __log.debug("lvaluePtr type " + lvaluePtr.getNodeType());
        __log.debug("lvaluePtr " + DOMUtils.domToString(lvaluePtr));
        __log.debug("lvalue " + lvalue);
        __log.debug("rvalue " + rvalue);
    }

    switch (lvaluePtr.getNodeType()) {
    case Node.ELEMENT_NODE:

        // Remove all the children.
        while (lvaluePtr.hasChildNodes())
            lvaluePtr.removeChild(lvaluePtr.getFirstChild());

        // Append a new text node.
        lvaluePtr.appendChild(d.createTextNode(rvalue));

        // If lvalue is a text, removing all lvaluePtr children had just removed it
        // so we need to rebuild it as a child of lvaluePtr
        if (lvalue instanceof Text)
            lvalue = lvaluePtr.getFirstChild();
        break;

    case Node.TEXT_NODE:

        Node newval = d.createTextNode(rvalue);
        // Replace ourselves .
        lvaluePtr.getParentNode().replaceChild(newval, lvaluePtr);

        // A little kludge, let our caller know that the root element has changed.
        // (used for assignment to a simple typed variable)
        if (lvalue.getNodeType() == Node.ELEMENT_NODE) {
            // No children, adding an empty text children to point to
            if (lvalue.getFirstChild() == null) {
                Text txt = lvalue.getOwnerDocument().createTextNode("");
                lvalue.appendChild(txt);
            }
            if (lvalue.getFirstChild().getNodeType() == Node.TEXT_NODE)
                lvalue = lvalue.getFirstChild();
        }
        if (lvalue.getNodeType() == Node.TEXT_NODE
                && ((Text) lvalue).getWholeText().equals(((Text) lvaluePtr).getWholeText()))
            lvalue = lvaluePtr = newval;
        break;

    case Node.ATTRIBUTE_NODE:

        ((Attr) lvaluePtr).setValue(rvalue);
        break;

    default:
        // This could occur if the expression language selects something
        // like
        // a PI or a CDATA.
        String msg = __msgs.msgInvalidLValue();
        if (__log.isDebugEnabled())
            __log.debug(lvaluePtr + ": " + msg);
        throw new FaultException(getOAsssign().getOwner().constants.qnSelectionFailure, msg);
    }

    return lvalue;
}

From source file:org.apache.ode.bpel.rtrep.v2.AssignHelper.java

/**
 * isInsert flag desginates this as an 'element' type insertion, which
 * requires insert the actual element value, rather than it's children
 * (madars.vitolins _at gmail.com - 2009.04.17 - moved from ASSIGN here)
 * @return//from  w w  w . j  av  a  2 s. c o m
 * @throws FaultException
 */
public Node replaceContent(Node lvalue, Node lvaluePtr, String rvalue) throws FaultException {
    Document d = lvaluePtr.getOwnerDocument();

    if (__log.isDebugEnabled()) {
        __log.debug("lvaluePtr type " + lvaluePtr.getNodeType());
        __log.debug("lvaluePtr " + DOMUtils.domToString(lvaluePtr));
        __log.debug("lvalue " + lvalue);
        __log.debug("rvalue " + rvalue);
    }

    switch (lvaluePtr.getNodeType()) {
    case Node.ELEMENT_NODE:

        // Remove all the children.
        while (lvaluePtr.hasChildNodes())
            lvaluePtr.removeChild(lvaluePtr.getFirstChild());

        // Append a new text node.
        lvaluePtr.appendChild(d.createTextNode(rvalue));

        // If lvalue is a text, removing all lvaluePtr children had just removed it
        // so we need to rebuild it as a child of lvaluePtr
        if (lvalue instanceof Text)
            lvalue = lvaluePtr.getFirstChild();
        break;

    case Node.TEXT_NODE:

        Node newval = d.createTextNode(rvalue);
        // Replace ourselves .
        lvaluePtr.getParentNode().replaceChild(newval, lvaluePtr);

        // A little kludge, let our caller know that the root element has changed.
        // (used for assignment to a simple typed variable)
        if (lvalue.getNodeType() == Node.ELEMENT_NODE) {
            // No children, adding an empty text children to point to
            if (lvalue.getFirstChild() == null) {
                Text txt = lvalue.getOwnerDocument().createTextNode("");
                lvalue.appendChild(txt);
            }
            if (lvalue.getFirstChild().getNodeType() == Node.TEXT_NODE)
                lvalue = lvalue.getFirstChild();
        }
        if (lvalue.getNodeType() == Node.TEXT_NODE
                && ((Text) lvalue).getWholeText().equals(((Text) lvaluePtr).getWholeText()))
            lvalue = lvaluePtr = newval;
        break;

    case Node.ATTRIBUTE_NODE:

        ((Attr) lvaluePtr).setValue(rvalue);
        break;

    default:
        // This could occur if the expression language selects something
        // like
        // a PI or a CDATA.
        String msg = __msgs.msgInvalidLValue();
        if (__log.isDebugEnabled())
            __log.debug(lvaluePtr + ": " + msg);
        throw new FaultException(getOActivity().getOwner().constants.qnSelectionFailure, msg);
    }

    return lvalue;
}