Example usage for org.w3c.dom Node getParentNode

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

Introduction

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

Prototype

public Node getParentNode();

Source Link

Document

The parent of this node.

Usage

From source file:Main.java

@SuppressWarnings("null")
public static void copyInto(Node src, Node dest) throws DOMException {

    Document factory = dest.getOwnerDocument();

    //Node start = src;
    Node parent = null;
    Node place = src;//from w w w .  ja v  a2 s. c o m

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr) attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
                /*
                 if (domimpl && !attr.getSpecified()) {
                 ((Attr) element.getAttributeNode(attrName)).setSpecified(false);
                 }
                 */
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(), place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException(
                    "can't copy node type, " + type + " (" + node.getNodeName() + ')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place = place.getFirstChild();
            dest = node;
        } else if (parent == null) {
            place = null;
        } else {
            // advance
            place = place.getNextSibling();
            while (place == null && parent != null && dest != null) {
                place = parent.getNextSibling();
                parent = parent.getParentNode();
                dest = dest.getParentNode();
            }
        }

    }

}

From source file:com.amalto.core.history.accessor.ManyFieldAccessor.java

public void create() {
    parent.create();/*  w ww .  j a  va2 s  . c  o m*/

    // TODO Refactor this
    Document domDocument = document.asDOM();
    Node node = getCollectionItemNode();
    if (node == null) {
        Element parentNode = (Element) parent.getNode();
        NodeList children = parentNode.getElementsByTagName(fieldName);
        int currentCollectionSize = children.getLength();
        if (currentCollectionSize > 0) {
            Node refNode = children.item(currentCollectionSize - 1).getNextSibling();
            while (currentCollectionSize <= index) {
                node = domDocument.createElementNS(domDocument.getNamespaceURI(), fieldName);
                parentNode.insertBefore(node, refNode);
                currentCollectionSize++;
            }
        } else {
            // Collection is not present at all, append at the end of parent element.
            Node lastAccessedNode = document.getLastAccessedNode();
            if (lastAccessedNode != null) {
                Node refNode = lastAccessedNode.getNextSibling();
                while (refNode != null && !(refNode instanceof Element)) {
                    refNode = refNode.getNextSibling();
                }
                while (currentCollectionSize <= index) {
                    node = domDocument.createElementNS(domDocument.getNamespaceURI(), fieldName);
                    if (lastAccessedNode == parentNode) {
                        if (lastAccessedNode == document.asDOM().getDocumentElement()
                                && lastAccessedNode.getChildNodes().getLength() > 0)
                            parentNode.insertBefore(node, parentNode.getFirstChild());
                        else
                            parentNode.appendChild(node);
                    } else if (refNode != null && refNode.getParentNode() == parentNode) {
                        parentNode.insertBefore(node, refNode);
                    } else {
                        parentNode.appendChild(node);
                    }
                    currentCollectionSize++;
                }
            } else {
                while (currentCollectionSize <= index) {
                    node = domDocument.createElementNS(domDocument.getNamespaceURI(), fieldName);
                    parentNode.appendChild(node);
                    currentCollectionSize++;
                }
            }
        }
        document.setLastAccessedNode(node);
    } else if (node.getChildNodes().getLength() == 0) {
        // This accessor creates (n-1) empty elements when accessing first collection element at index n.
        // This setLastAccessedNode call allows all (n-1) elements to find their parent.
        if (!(node.getLocalName().equals(document.getLastAccessedNode().getLocalName())
                && document.getLastAccessedNode().getParentNode() == node.getParentNode())) {
            // if last accessed node is parallel with this node, can't modify last accessed node. eg, last accessed
            // node=/feature/vendor[2], this node=/feature/vendor[1], the last accessed is still /feature/vendor[2]
            document.setLastAccessedNode(node);
        }
    }
}

From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

/**
 * This method takes the SOAP request that come from the WSP and removes
 * the elements that need to be removed per the SAML Profiles spec.
 * /*from  www  .  jav  a  2s. co  m*/
 * @param samlSession
 * @param authnState 
 * @return true, if successful
 */
private boolean processSOAPRequest(SAMLSession samlSession, DelegatedSAMLAuthenticationState authnState) {
    this.logger.debug("Step 3 of 5: Process SOAP Request");
    try {
        String expression = "/S:Envelope/S:Header/paos:Request";
        Document dom = authnState.getSoapRequestDom();
        Node node = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE);

        if (node != null) {
            // Save the response consumer URL to samlSession
            String responseConsumerURL = node.getAttributes().getNamedItem("responseConsumerURL")
                    .getTextContent();
            logger.debug("Loaded response consumer URL {}", responseConsumerURL);
            authnState.setResponseConsumerURL(responseConsumerURL);
            // Save the PAOS MessageID, if present
            Node paosMessageID = node.getAttributes().getNamedItem("messageID");

            if (paosMessageID != null)
                authnState.setPaosMessageID(paosMessageID.getTextContent());
            else
                authnState.setPaosMessageID(null);

            // This removes the paos:Request node
            node.getParentNode().removeChild(node);

            // Retrieve the RelayState cookie for sending it back to the WSP with the SOAP Response
            expression = "/S:Envelope/S:Header/ecp:RelayState";
            node = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE);
            if (node != null) {
                Element relayStateElement = (Element) node;
                authnState.setRelayStateElement(relayStateElement);
                node.getParentNode().removeChild(node);
            }

            // On to the ecp:Request for removal
            expression = "/S:Envelope/S:Header/ecp:Request";
            node = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE);
            node.getParentNode().removeChild(node);

            // Now add some namespace bindings to the SOAP Header
            expression = "/S:Envelope/S:Header";
            Element soapHeader = EXPRESSION_POOL.evaluate(expression, dom, XPathConstants.NODE);

            // Add new elements to S:Header
            Element newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("sbf"), "sbf:Framework");
            newElement.setAttribute("version", "2.0");
            soapHeader.appendChild(newElement);
            newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("sb"), "sb:Sender");
            newElement.setAttribute("providerID", samlSession.getPortalEntityID());
            soapHeader.appendChild(newElement);
            newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("wsa"), "wsa:MessageID");
            String messageID = generateMessageID();
            newElement.setTextContent(messageID);
            soapHeader.appendChild(newElement);
            newElement = dom.createElementNS(NAMESPACE_CONTEXT.getNamespaceURI("wsa"), "wsa:Action");
            newElement.setTextContent("urn:liberty:ssos:2006-08:AuthnRequest");
            soapHeader.appendChild(newElement);

            // This is the wsse:Security element 
            Element securityElement = dom.createElementNS(
                    "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                    "wsse:Security");
            securityElement.setAttribute(soapHeader.getPrefix() + ":mustUnderstand", "1");
            Element createdElement = dom.createElement("wsu:Created");
            // The examples use Zulu time zone, not local
            TimeZone zuluTimeZone = TimeZone.getTimeZone("Zulu");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'");
            sdf.setTimeZone(zuluTimeZone);
            createdElement.setTextContent(sdf.format(new Date()));
            newElement = dom.createElementNS(
                    "http://www.docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd",
                    "wsu:Timestamp");
            newElement.appendChild(createdElement);
            securityElement.appendChild(newElement);
            // Finally, insert the original SAML assertion
            Node samlAssertionNode = dom.importNode(samlSession.getSamlAssertionDom().getDocumentElement(),
                    true);
            securityElement.appendChild(samlAssertionNode);
            soapHeader.appendChild(securityElement);

            // Store the modified SOAP Request in the SAML Session
            String modifiedSOAPRequest = writeDomToString(dom);
            authnState.setModifiedSOAPRequest(modifiedSOAPRequest);
            logger.debug("Completed processing of SOAP request");
            return true;
        }
        logger.debug("Failed to process SOAP request using expression {}", expression);
    } catch (XPathExpressionException ex) {
        logger.error("Programming error.  Invalid XPath expression.", ex);
        throw new DelegatedAuthenticationRuntimeException("Programming error.  Invalid XPath expression.", ex);
    }
    return false;
}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

/**
 * Thread-safety tested/*from  ww  w.  ja  va2s.c  om*/
 */
@Override
public Map<String, Object> deleteElementByPath(String path, final String originalXml)
        throws SAXException, IOException, XPathExpressionException {
    Assert.hasText(path);
    Assert.hasText(originalXml);

    Document originalDom = parse(originalXml);

    Document finalDom = originalDom;

    XPath xPath = getXPathInstance();

    // find all the nodes specified by xPathString in the finalDom, and
    // delete them all
    NodeList existingNodeList = (NodeList) (xPath.evaluate(path, finalDom, XPathConstants.NODESET));

    int el = existingNodeList.getLength();

    logger.trace("find '" + el + "' in originalDom using xPath: " + path);

    for (int i = 0; i < el; i++) {
        Node c = existingNodeList.item(i);

        Node cp = c.getParentNode();
        // remove this node from its parent...
        cp.removeChild(c);

        logger.trace("node has child : " + cp.getChildNodes().getLength() + ":" + cp.hasChildNodes());
    }

    logger.trace(DomUtils.elementToString(finalDom));

    Map<String, Object> resultMap = new HashMap<String, Object>(3);
    resultMap.put("finalXml", DomUtils.elementToString(finalDom));
    resultMap.put("isDeleted", true);
    return resultMap;

}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

@Override
public synchronized Map<String, Object> deleteElementByPathById(String path, final String originalXml,
        String elementId) throws SAXException, IOException, XPathExpressionException {
    Assert.hasText(path);/*from   w w w  .j a  v  a 2  s . com*/
    Assert.hasText(originalXml);
    Assert.hasText(elementId);

    Document originalDom = parse(originalXml);

    Document finalDom = originalDom;

    String xPathString = path + "[@id='" + elementId + "']";

    XPath xPath = getXPathInstance();

    // find all the nodes specified by xPathString in the finalDom, and
    // delete them all
    NodeList existingNodeList = (NodeList) (xPath.evaluate(xPathString, finalDom, XPathConstants.NODESET));

    int el = existingNodeList.getLength();

    logger.trace("find '" + el + "' in originalDom using xPath: " + xPathString);

    for (int i = 0; i < el; i++) {
        Node c = existingNodeList.item(i);

        Node cp = c.getParentNode();
        // remove this node from its parent...
        cp.removeChild(c);

        logger.trace("node has child : " + cp.getChildNodes().getLength() + ":" + cp.hasChildNodes());
    }

    logger.trace(DomUtils.elementToString(finalDom));

    Map<String, Object> resultMap = new HashMap<String, Object>(3);
    resultMap.put("finalXml", DomUtils.elementToString(finalDom));
    resultMap.put("isDeleted", true);
    return resultMap;

}

From source file:org.structr.web.entity.dom.DOMNode.java

protected void checkHierarchy(Node otherNode) throws DOMException {

    // we can only check DOMNodes
    if (otherNode instanceof DOMNode) {

        // verify that the other node is not this node
        if (isSameNode(otherNode)) {
            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, HIERARCHY_REQUEST_ERR_MESSAGE_SAME_NODE);
        }// w w w. j  a  v  a2  s  .  c om

        // verify that otherNode is not one of the
        // the ancestors of this node
        // (prevent circular relationships)
        Node _parent = getParentNode();
        while (_parent != null) {

            if (_parent.isSameNode(otherNode)) {
                throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
                        HIERARCHY_REQUEST_ERR_MESSAGE_ANCESTOR);
            }

            _parent = _parent.getParentNode();
        }

        // TODO: check hierarchy constraints imposed by the schema
        // validation sucessful
        return;
    }

    throw new DOMException(DOMException.NOT_SUPPORTED_ERR, NOT_SUPPORTED_ERR_MESSAGE);
}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

/**
 * replace elements in originalDom with modifiedDom according to listed
 * xPaths, if the originalDom has elements not listed in the xPath, it will
 * be kept untouched. in the HashMap<String, String> xPathPairs, the key is
 * the path in the source xml, and the value is the xpath for the final
 * note*: the if the xpath has attributes, it's not going to work... need to
 * do a custom implementation when that use case happened...
 * /*from w  ww  .ja  v  a  2s  .  c o  m*/
 * @param originalDom
 * @param modifiedDom
 * @param xPaths
 * @return
 * @throws XPathExpressionException
 */
private Document replaceByXPaths(final Document originalDom, final Document modifiedDom,
        Map<String, String> xPathPairs) throws XPathExpressionException {

    Document finalDom = originalDom;
    Element finalDomRoot = (Element) finalDom.getFirstChild();

    Element lastChild = null;

    for (Entry<String, String> xPathPair : xPathPairs.entrySet()) {

        /**
         * basically, this is to copy the element specified in srcXPath, and
         * replace/add it to the position pointed by destXPath...
         */
        String srcXPath = xPathPair.getKey();

        logger.debug("srcXPath: " + srcXPath);

        String destXPath = xPathPair.getValue();

        logger.debug("destXPath: " + destXPath);

        XPath xPath = getXPathInstance();
        // find all the nodes specified by destXPath in the originalDom, and
        // delete them all
        NodeList existingNodeList = (NodeList) (xPath.evaluate(destXPath, finalDom, XPathConstants.NODESET));

        int el = existingNodeList.getLength();

        logger.debug("find '" + el + "' in originalDom using xPath: " + destXPath);

        for (int i = 0; i < el; i++) {
            Node c = existingNodeList.item(i);
            // remove this node from its parent...
            c.getParentNode().removeChild(c);
        }

        // create the node structure first. and return the last child of the
        // path... the right most node...
        lastChild = createElementStructureByPath(finalDomRoot, destXPath);

        List<String> nodeNameList = getNodeList(destXPath);

        String lastNodeName = nodeNameList.get(nodeNameList.size() - 1);

        xPath.reset();
        // find all the nodes specified by srcXPath in the modifiedDom
        NodeList nodeList = (NodeList) (xPath.evaluate(srcXPath, modifiedDom, XPathConstants.NODESET));

        int l = nodeList.getLength();

        logger.debug("find '" + l + "' in modifiedXml using xPath: " + srcXPath);

        Node currentNode = null;
        for (int i = 0; i < l; i++) {
            currentNode = nodeList.item(i);

            // the name of the last node in srcXPath might not be the same
            // as the name of the last node in destXPath
            Element lastElement = finalDom.createElement(lastNodeName);

            // NodeList currentNodeChildNodes = currentNode.getChildNodes();
            // int s = currentNodeChildNodes.getLength();
            // for(int j = 0; j < s; j++){
            // lastElement.appendChild(finalDom.importNode(currentNodeChildNodes.item(j),
            // true));
            // }
            if (currentNode.hasAttributes()) {
                NamedNodeMap attributes = currentNode.getAttributes();

                for (int j = 0; j < attributes.getLength(); j++) {
                    String attribute_name = attributes.item(j).getNodeName();
                    String attribute_value = attributes.item(j).getNodeValue();

                    lastElement.setAttribute(attribute_name, attribute_value);
                }
            }

            while (currentNode.hasChildNodes()) {
                Node kid = currentNode.getFirstChild();
                currentNode.removeChild(kid);
                lastElement.appendChild(finalDom.importNode(kid, true));
            }

            lastChild.appendChild(lastElement);

        }

    }

    return finalDom;

}

From source file:org.dozer.eclipse.plugin.sourcepage.hyperlink.DozerClassHyperlinkDetector.java

public IHyperlink createHyperlink(String attrName, String target, Node node, Node parentNode,
        IDocument document, ITextViewer textViewer, IRegion hyperlinkRegion, IRegion cursor) {
    String nodeName = parentNode.getNodeName();
    IFile file = BeansEditorUtils.getFile(document);
    IType type = JdtUtils.getJavaType(file.getProject(), target);

    if ("class-a".equals(nodeName) || "class-b".equals(nodeName) || "a-hint".equals(attrName)
            || "b-hint".equals(attrName) || "a-deep-index-hint".equals(attrName)
            || "b-deep-index-hint".equals(attrName)) {
        //make a simple hyperlink to the class
        if (type != null) {
            return new JavaElementHyperlink(hyperlinkRegion, type);
        }//from  w w w  .  java2  s  . c  o  m
    } else if ("set-method".equals(attrName) || "get-method".equals(attrName)
            || "map-set-method".equals(attrName) || "map-get-method".equals(attrName)) {
        if ("field".equals(nodeName)) {
            String targetClassName = DozerPluginUtils.getMappingClassName(node);

            //get the first method that matches and make a hyperlink to that
            if (targetClassName != null) {
                IType targetClass = JdtUtils.getJavaType(file.getProject(), targetClassName);
                IMethod method = getMethodFromType(targetClass, target);
                if (method != null) {
                    return new JavaElementHyperlink(hyperlinkRegion, method);
                }
            }
        }
    } else if ("a-hint".equals(attrName) || "b-hint".equals(attrName)) {
        //make a simple hyperlink to the class
        if (parentNode.getParentNode() != null && "mapping".equals(parentNode.getParentNode().getNodeName())) {
            if (type != null) {
                return new JavaElementHyperlink(hyperlinkRegion, type);
            }
        }
    } else if ("custom-converter".equals(attrName)) {
        //make a simple hyperlink to the class
        if (type != null) {
            return new JavaElementHyperlink(hyperlinkRegion, type);
        }
    } else if ("custom-converter-id".equals(attrName)) {
        //search spring-bean that uses our mapping file and return the mapping
        //for the customconverter-id map-property
        ISourceModelElement modelElement = getModelElementForCustomConverter(BeansEditorUtils.getFile(document),
                target);

        if (modelElement != null) {
            return new SourceModelHyperlink(modelElement, hyperlinkRegion);
        }
    } else if ("a".equals(nodeName) || "b".equals(nodeName)) {
        String targetClassName = DozerPluginUtils.getMappingClassName(node.getParentNode());
        String property = node.getNodeValue();

        if (targetClassName != null) {
            IType targetClass = JdtUtils.getJavaType(file.getProject(), targetClassName);

            try {
                //if we are doing indexed property mapping, we remove the []
                property = property.replaceAll("\\[\\]", "");

                IMethod method = Introspector.getReadableProperty(targetClass, property);

                if (method != null)
                    return new JavaElementHyperlink(hyperlinkRegion, method);
            } catch (Throwable e) {
                Logger.logException(e);
            }
        }
    } else if ("bean-factory".equals(attrName)) {
        //make a simple hyperlink to the class
        if (type != null) {
            return new JavaElementHyperlink(hyperlinkRegion, type);
        }
    }

    return null;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.ClinicalDateObscurer.java

/**
 * This methods goes through the original XML document and obscure a few selected dates by changing the time reference
 * to a chosen Date element in the XML.//from  w  ww .  j  a v  a  2  s .com
 *
 * @param document the XML DOM Document
 * @param xpath an XPath instance
 * @param basisYear the new time reference year
 * @param basisMonth the new time reference month
 * @param basisDay the new time reference day
 * @param basisPrecision the time reference precision
 * @param ageAtBasisDate the age of the patient based on the new time reference
 * @param patientBirthYearAttributes the birth year attributes for the patient
 * @param bcrPatientOverCutoffAgeBarcodeList a list to store the barcode of patient whose age is over the cutoff age
 * @return the Document with the dates to be obscured replaced by an elapsed time since the new time reference
 * @throws ProcessorException
 */
private Document obscureElements(final Document document, final XPath xpath, final String basisYear,
        final String basisMonth, final String basisDay, final String basisPrecision, final long ageAtBasisDate,
        final Hashtable<String, String> patientBirthYearAttributes,
        final List<String> bcrPatientOverCutoffAgeBarcodeList) throws ProcessorException {

    //Iterate on the list of element's name suffixes to validate the different dates
    final Map<String, String> datesToObscure = getDatesToObscure(document, xpath);
    final Iterator<String> xpathSuffixIterator = datesToObscure.keySet().iterator();
    String xpathSuffix = null;
    while (xpathSuffixIterator.hasNext()) {

        xpathSuffix = xpathSuffixIterator.next();
        String elementNamePrefix = getElapsedElementBase();
        String elementNameSuffix = xpathSuffix;
        String namespacePrefix = null;
        int indexOfColon = xpathSuffix.indexOf(":");
        if (indexOfColon > 0) {
            elementNameSuffix = xpathSuffix.substring(indexOfColon + 1);
            namespacePrefix = xpathSuffix.substring(0, indexOfColon);
        }

        if (namespacePrefix == null || xpath.getNamespaceContext().getNamespaceURI(namespacePrefix) != null) {

            try {
                final String yearOfNodesAttributesExpression = getXPathExpressionIgnoringNamespace(yearOfPrefix,
                        xpathSuffix);
                final String monthOfNodesAttributesExpression = getXPathExpressionIgnoringNamespace(
                        monthOfPrefix, xpathSuffix);
                final String dayOfNodesAttributesExpression = getXPathExpressionIgnoringNamespace(dayOfPrefix,
                        xpathSuffix);

                final NodeList yearOfNodes = getNodeListFromXPathExpression(document, xpath,
                        yearOfNodesAttributesExpression);
                final NodeList monthOfNodes = getNodeListFromXPathExpression(document, xpath,
                        monthOfNodesAttributesExpression);
                final NodeList dayOfNodes = getNodeListFromXPathExpression(document, xpath,
                        dayOfNodesAttributesExpression);

                // must have the same number of year, month, and day nodes
                if (yearOfNodes.getLength() != monthOfNodes.getLength()) {
                    throw new ProcessorException(
                            getNodeListLengthMismatchErrorMessage(yearOfNodesAttributesExpression,
                                    monthOfNodesAttributesExpression, yearOfNodes, monthOfNodes));
                }

                if (yearOfNodes.getLength() != dayOfNodes.getLength()) {
                    throw new ProcessorException(
                            getNodeListLengthMismatchErrorMessage(yearOfNodesAttributesExpression,
                                    dayOfNodesAttributesExpression, yearOfNodes, dayOfNodes));
                }

                //Iterate through the selected element names that need to be obscured and obscure the dates
                for (int nodeIndex = 0; nodeIndex < yearOfNodes.getLength(); nodeIndex++) {

                    final Node yearOfNode = yearOfNodes.item(nodeIndex);
                    final Node monthOfNode = monthOfNodes.item(nodeIndex);
                    final Node dayOfNode = dayOfNodes.item(nodeIndex);
                    final Node parentNode = yearOfNode.getParentNode();

                    final String yearOf = yearOfNode.getTextContent().trim();
                    final String monthOf = monthOfNode.getTextContent().trim();
                    final String dayOf = dayOfNode.getTextContent().trim();

                    String monthOfProcurementStatus = null;
                    String yearOfOwner = null;
                    String yearOfProcurementStatus = null;

                    final Node yearOfProcurementStatusNode = yearOfNode.getAttributes()
                            .getNamedItem(PROCUREMENT_STATUS);
                    if (yearOfProcurementStatusNode != null) {
                        yearOfProcurementStatus = yearOfProcurementStatusNode.getTextContent().trim();
                    }

                    final Node yearOfOwnerNode = yearOfNode.getAttributes().getNamedItem(OWNER);
                    if (yearOfOwnerNode != null) {
                        yearOfOwner = yearOfOwnerNode.getTextContent().trim();
                    }

                    final Node monthOfProcurementStatusNode = monthOfNode.getAttributes()
                            .getNamedItem(PROCUREMENT_STATUS);
                    if (monthOfProcurementStatusNode != null) {
                        monthOfProcurementStatus = monthOfProcurementStatusNode.getTextContent().trim();
                    }

                    if (parentNode != null) {
                        // find the namespace from the yearOf node
                        String namespace = "";
                        String yearNodeName = yearOfNode.getNodeName();
                        if (yearNodeName.contains(":")) {
                            namespace = yearNodeName.substring(0, yearNodeName.indexOf(":") + 1); // include the ':'
                        }
                        //Update document

                        //Replace dayOfPrefix node by elapsedElementBase node

                        String elementValue = "";
                        String cdeAttributeValue = datesToObscure.get(xpathSuffix);
                        String ownerAttributeValue = yearOfOwner;

                        String elementPrecision = getPrecisionForElementDate(yearOf, monthOf, dayOf,
                                basisPrecision);
                        boolean elementValueFloored = false;
                        if (elementPrecision.equals(PRECISION_YEAR) || elementPrecision.equals("")) {
                            // set precision to empty since we are not going to do the calculation
                            elementPrecision = "";
                        } else {
                            Date elementDate = makeDateFromParts(yearOf, monthOf, dayOf, elementPrecision);
                            Date basisDate = makeDateFromParts(basisYear, basisMonth, basisDay,
                                    elementPrecision);
                            Long elapsedDays = calculateElapsedDaysBetween(elementDate, basisDate);

                            //The 'days to birth' value needs to be floored if it's lower than a lower bound
                            if (xpathSuffix.equals(getBirthDateName())
                                    && elapsedDays < getDaysToBirthLowerBound()) {
                                elapsedDays = getDaysToBirthLowerBound().longValue();
                                elementValueFloored = true;
                            }

                            elementValue = (elapsedDays == null ? null : String.valueOf(elapsedDays));
                        }

                        // Procurement status should be set to 'Completed' if the element has a non blank value,
                        // otherwise it should be set to the year of's procurement status
                        final String procurementStatusAttributeValue = StringUtils.isBlank(elementValue)
                                ? yearOfProcurementStatus
                                : ProcurementStatus.Completed.toString();
                        final Node yearOfNodeTierAttribute = yearOfNode.getAttributes().getNamedItem(TIER);
                        final String tierAttributeValue = (yearOfNodeTierAttribute != null
                                ? yearOfNodeTierAttribute.getTextContent().trim()
                                : null);

                        String xsdVerAttribute = getXsdVersionAttributeValue(yearOfNode);
                        final String precisionAttributeValue = elementPrecision;

                        Node daysToNode = createElementNode(document, namespace + elementNamePrefix,
                                elementNameSuffix, elementValue, cdeAttributeValue, ownerAttributeValue,
                                procurementStatusAttributeValue, tierAttributeValue, xsdVerAttribute,
                                precisionAttributeValue, elementValueFloored);

                        parentNode.replaceChild(daysToNode, dayOfNode);

                        //Remove monthOfPrefix node if <code>xpathSuffix</code> is different from <code>basisDateNameForClinical</code>,
                        //otherwise replace it by a new ageAtPrefix + <code>basisDateNameForClinical</code> Element
                        if (!xpathSuffix.equals(getBasisDateNameForClinical())) {

                            removeChildNode(parentNode, monthOfNode);
                        } else {

                            boolean ageAtBasisDateValueFloored = false;
                            String ageAtBasisDateValue = "";
                            if (ageAtBasisDate != -1) {

                                if (ageAtBasisDate > getCutoffAgeAtInitialDiagnosis()) {
                                    ageAtBasisDateValue = getCutoffAgeAtInitialDiagnosis().toString(); // the patient's age > cutoff age, floor it at the cutoff age
                                    ageAtBasisDateValueFloored = true;

                                    //add the patient barcode to the list of patient whose age is over the cutoff age
                                    bcrPatientOverCutoffAgeBarcodeList
                                            .add(getBcrPatientBarcode(document, xpath));

                                } else {
                                    ageAtBasisDateValue = String.valueOf(ageAtBasisDate);
                                }
                            }

                            final String ageAtOwnerAttributeValue = patientBirthYearAttributes.get(OWNER);
                            final String yearOfBirthProcurementStatus = patientBirthYearAttributes
                                    .get(PROCUREMENT_STATUS);

                            // Procurement status should be set to 'Completed' if the element has a non blank value,
                            // otherwise it should be set to the patient year of birth's procurement status
                            final String ageAtProcurementStatusAttributeValue = StringUtils
                                    .isBlank(ageAtBasisDateValue) ? yearOfBirthProcurementStatus
                                            : ProcurementStatus.Completed.toString();

                            final String ageAtTierAttributeValue = patientBirthYearAttributes.get(TIER);

                            final String monthOfNodeNamespace = getNamespaceFromNodeName(monthOfNode);

                            final Node ageAtNode = createElementNode(document,
                                    monthOfNodeNamespace + ageAtPrefix, elementNameSuffix, ageAtBasisDateValue,
                                    ageAtBasisDateCDE, ageAtOwnerAttributeValue,
                                    ageAtProcurementStatusAttributeValue, ageAtTierAttributeValue,
                                    xsdVerAttribute, null, ageAtBasisDateValueFloored);

                            parentNode.replaceChild(ageAtNode, monthOfNode);
                        }

                        //Remove yearOfPrefix node if:
                        // <code>xpathSuffix</code> is different from <code>basisDateNameForClinical</code>
                        if (!xpathSuffix.equals(getBasisDateNameForClinical())) {
                            removeChildNode(parentNode, yearOfNode);
                        }

                    } else {
                        final String xMsg = "The Parent Node is null for the XPath expression: " + yearOfPrefix
                                + xpathSuffix + "[" + nodeIndex + "]";
                        throw new ProcessorException(xMsg);
                    }
                }

            } catch (XPathExpressionException x) {
                throw new ProcessorException("Xpath Expression error", x);
            }
        } // else this date is in a namespace not in this document, so skip it, since it must not be in here (or would have failed validation)
    }

    return document;
}

From source file:org.keycloak.testsuite.adapter.servlet.SAMLServletAdapterTest.java

@Test
public void testNameIDUnset() throws Exception {
    new SamlClientBuilder().navigateTo(employee2ServletPage.toString()).processSamlResponse(Binding.POST)
            .build().login().user(bburkeUser).build().processSamlResponse(Binding.POST)
            .transformDocument(responseDoc -> {
                XPathFactory xPathfactory = XPathFactory.newInstance();
                XPath xpath = xPathfactory.newXPath();
                XPathExpression expr = xpath.compile("//*[local-name()='NameID']");

                NodeList nodeList = (NodeList) expr.evaluate(responseDoc, XPathConstants.NODESET);
                Assert.assertThat(nodeList.getLength(), is(1));

                final Node nameIdNode = nodeList.item(0);
                nameIdNode.getParentNode().removeChild(nameIdNode);

                return responseDoc;
            }).build()/*from ww w. j a  v a  2  s.com*/

            .navigateTo(employee2ServletPage.toString())

            .execute(r -> {
                Assert.assertThat(r, statusCodeIsHC(Response.Status.OK));
                Assert.assertThat(r, bodyHC(allOf(containsString("principal="), not(containsString("500")))));
            });
}