Example usage for org.w3c.dom Document getElementsByTagNameNS

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

Introduction

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

Prototype

public NodeList getElementsByTagNameNS(String namespaceURI, String localName);

Source Link

Document

Returns a NodeList of all the Elements with a given local name and namespace URI in document order.

Usage

From source file:org.codice.ddf.security.claims.attributequery.common.AttributeQueryClient.java

/**
 * Retrieves the response and returns its SAML Assertion.
 *
 * @param requestDocument of the request.
 * @return Assertion of the response or null if the response is empty.
 * @throws AttributeQueryException//from  w ww.  ja va  2  s.  com
 */
private Assertion retrieveResponse(Document requestDocument) throws AttributeQueryException {
    Assertion assertion = null;
    try {
        Document responseDocument = sendRequest(requestDocument);
        if (responseDocument == null) {
            return null;
        }

        // Print Response
        if (LOGGER.isTraceEnabled()) {
            printXML("SAML Response:\n {}", responseDocument);
        }

        // Extract Response from Soap message.
        Node responseNode = responseDocument.getElementsByTagNameNS(SAML2_PROTOCOL, "Response").item(0);
        Element responseElement = (Element) responseNode;

        Unmarshaller unmarshaller = XMLObjectProviderRegistrySupport.getUnmarshallerFactory()
                .getUnmarshaller(responseElement);

        Response response = (Response) unmarshaller.unmarshall(responseElement);
        LOGGER.debug("Successfully marshalled Element to SAML Response.");
        if (response.getStatus().getStatusCode().getValue().equals(SAML2_SUCCESS)) {
            LOGGER.debug("Successful response, retrieved attributes.");
            // Should only have one assertion.
            assertion = response.getAssertions().get(0);

        } else {
            reportError(response.getStatus());
        }
        return assertion;
    } catch (UnmarshallingException e) {
        throw new AttributeQueryException("Unable to marshall Element to SAML Response.", e);
    }
}

From source file:org.forgerock.maven.plugins.LinkTester.java

private void processDocSource(DocSource docSource, DocumentBuilder db, XPathExpression expr) {
    DirectoryScanner scanner = new DirectoryScanner();

    File baseDir = docSource.getDirectory();
    if (baseDir == null) {
        baseDir = project.getBasedir();/* w ww. ja  v a  2 s  .c  om*/
    }
    scanner.setBasedir(baseDir);
    scanner.setIncludes(docSource.getIncludes());
    scanner.setExcludes(docSource.getExcludes());
    scanner.scan();

    String[] files = scanner.getIncludedFiles();
    for (String relativePath : files) {
        setCurrentPath(relativePath);
        try {
            Document doc = db.parse(new File(baseDir, relativePath));
            if (!skipOlinks) {
                extractXmlIds(expr, doc, relativePath);
            }
            NodeList nodes = doc.getElementsByTagNameNS(DOCBOOK_NS, "link");
            for (int i = 0; i < nodes.getLength(); i++) {
                Node node = nodes.item(i);
                NamedNodeMap attrs = node.getAttributes();
                String url = null;
                boolean isOlink = false;
                for (int j = 0; j < attrs.getLength(); j++) {
                    Node attr = attrs.item(j);
                    if (attr.getLocalName().equals("href")) {
                        url = attr.getNodeValue();
                    } else if (attr.getLocalName().equals("role")
                            && attr.getNodeValue().equalsIgnoreCase(OLINK_ROLE)) {
                        isOlink = true;
                    }
                }
                if (url != null) {
                    if (isOlink && !skipOlinks) {
                        olinks.put(relativePath, url);
                    } else if (!isOlink && !skipUrls) {
                        checkUrl(relativePath, url);
                    }
                }
            }
        } catch (Exception ex) {
            error("Error while processing file: " + relativePath + ". Error: " + ex.getMessage(), ex);
        }
    }
}

From source file:org.fusesource.cloudmix.agent.jbi.JBIInstallerAgent.java

private Element getElement(Document doc, String name) {
    NodeList nl = doc.getElementsByTagNameNS(JBI_NS, name);
    return (Element) nl.item(0);
}

From source file:org.geoserver.ows.Dispatcher.java

BufferedReader soapReader(HttpServletRequest httpRequest) throws IOException {
    //in order to pull out the payload we have to parse the entire request and then reencode it
    // not nice... but then again neither is using SOAP
    Document dom = null;
    try {/*w w  w  .j a v  a  2  s  .c o  m*/
        dom = db.parse(httpRequest.getInputStream());

    } catch (SAXException e) {
        throw new IOException("Error parsing SOAP request", e);
    }

    //find the soap:Body element
    NodeList list = dom.getElementsByTagNameNS(SOAP_NS, "Body");
    if (list.getLength() != 1) {
        throw new IOException("SOAP requests should specify a single Body element");
    }
    Element body = (Element) list.item(0);

    //pull out the first element child
    Element payload = null;
    for (int i = 0; payload == null && i < body.getChildNodes().getLength(); i++) {
        Node n = body.getChildNodes().item(i);
        if (n instanceof Element) {
            payload = (Element) n;
        }
    }

    if (payload == null) {
        throw new IOException("Could not find payload in SOAP request");
    }

    //transform the payload back into an input stream so we can parse it as usual
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    try {
        TransformerFactory.newInstance().newTransformer().transform(new DOMSource(payload),
                new StreamResult(bout));
    } catch (Exception e) {
        throw new IOException("Error encoding payload of SOAP request", e);
    }

    return RequestUtils.getBufferedXMLReader(new ByteArrayInputStream(bout.toByteArray()), XML_LOOKAHEAD);
}

From source file:org.kuali.coeus.propdev.impl.s2s.connect.OpportunitySchemaParserServiceImpl.java

/**
 * This method fetches all the forms required from a given schema of opportunity
 * //ww w. j ava  2s  .  co  m
 * @param schema {@link String}
 * @return {@link HashMap} containing all form information
 */
@Override
public List<S2sOppForms> getForms(String proposalNumber, String schema) throws S2sCommunicationException {
    if (StringUtils.isBlank(proposalNumber)) {
        throw new IllegalArgumentException("proposalNumber is blank");
    }

    if (StringUtils.isBlank(schema)) {
        throw new IllegalArgumentException("schema is blank");
    }

    boolean mandatory;
    boolean available;
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = null;
    ArrayList<S2sOppForms> schemaList = new ArrayList<S2sOppForms>();
    Document document;
    try {
        builder = domFactory.newDocumentBuilder();
        InputStream is = (InputStream) new URL(schema).getContent();
        document = builder.parse(is);
    } catch (ParserConfigurationException e) {
        throw new S2sCommunicationException(KeyConstants.ERROR_GRANTSGOV_FORM_PARSING, e.getMessage(), schema);
    } catch (SAXException e) {
        throw new S2sCommunicationException(KeyConstants.ERROR_GRANTSGOV_FORM_PARSING_SAXEXCEPTION,
                e.getMessage(), schema);
    } catch (IOException e) {
        throw new S2sCommunicationException(KeyConstants.ERROR_GRANTSGOV_FORM_SCHEMA_NOT_FOUND, e.getMessage(),
                schema);
    }

    Element schemaElement = document.getDocumentElement();
    NodeList importList = document.getElementsByTagNameNS(XSD_NS, IMPORT);
    Node allForms = document.getElementsByTagNameNS(XSD_NS, ALL).item(0);

    // If there is no "Forms" element, it's probably because this is an NIH complex project
    if (allForms == null) {
        Node topElementName = schemaElement.getElementsByTagNameNS(XSD_NS, ELEMENT).item(0).getAttributes()
                .item(0);
        if (topElementName.getNodeName().equals("name")
                && !topElementName.getNodeValue().equals("GrantApplication")) {
            throw new S2sCommunicationException(KeyConstants.ERROR_GRANTSGOV_NO_FORM_ELEMENT, "", "");
        }
    }

    NodeList formsList = ((Element) allForms).getElementsByTagNameNS(XSD_NS, ELEMENT);
    String[] formNames = new String[formsList.getLength()];

    for (int formIndex = 0; formIndex < formsList.getLength(); formIndex++) {
        Node form = formsList.item(formIndex);
        String fullFormName = ((Element) form).getAttribute(REF);
        String formName = fullFormName.substring(0, fullFormName.indexOf(CH_COLON));
        String minOccurs = ((Element) form).getAttribute(MIN_OCCURS);
        String nameSpace = schemaElement.getAttribute(XMLNS + formName);
        FormMappingInfo info = formMappingService.getFormInfo(nameSpace, proposalNumber);
        String displayFormName = info == null ? formName : info.getFormName();
        formNames[formIndex] = nameSpace;
        for (int impIndex = 0; impIndex < importList.getLength(); impIndex++) {
            Node importNode = importList.item(impIndex);
            if (((Element) importNode).getAttribute(NAMESPACE).equalsIgnoreCase(nameSpace)) {
                String schemaUrl = ((Element) importNode).getAttribute(SCHEMA_LOCATION);
                S2sOppForms oppForm = new S2sOppForms();
                oppForm.setFormName(displayFormName);
                S2sOppFormsId oppFormId = new S2sOppFormsId();
                oppFormId.setProposalNumber(proposalNumber);
                oppFormId.setOppNameSpace(nameSpace);
                oppForm.setS2sOppFormsId(oppFormId);
                oppForm.getS2sOppFormsId().setOppNameSpace(nameSpace);
                oppForm.setSchemaUrl(schemaUrl);
                mandatory = (minOccurs == null || minOccurs.trim().equals("")
                        || Integer.parseInt(minOccurs) > 0);
                oppForm.setMandatory(mandatory);
                if (info != null) {
                    available = true;
                    oppForm.setUserAttachedForm(info.getUserAttachedForm());
                } else {
                    available = false;
                }
                oppForm.setAvailable(available);
                oppForm.setInclude(mandatory && available);
                schemaList.add(oppForm);
            }
        }
    }
    return schemaList;
}

From source file:org.kuali.kra.s2s.validator.OpportunitySchemaParser.java

/**
 * This method fetches all the forms required from a given schema of opportunity
 * //from   ww  w .  j a  va 2  s  .  co  m
 * @param schema {@link String}
 * @return {@link HashMap} containing all form information
 */
public ArrayList<S2sOppForms> getForms(String schema) throws S2SException {
    boolean mandatory;
    boolean available;
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = null;
    ArrayList<S2sOppForms> schemaList = new ArrayList<S2sOppForms>();
    Document document;
    try {
        builder = domFactory.newDocumentBuilder();
        InputStream is = (InputStream) new URL(schema).getContent();
        document = builder.parse(is);
    } catch (ParserConfigurationException e) {
        LOG.error(S2SConstants.ERROR_MESSAGE, e);
        throw new S2SException(KeyConstants.ERROR_GRANTSGOV_FORM_PARSING, e.getMessage(), schema);
    } catch (SAXException e) {
        LOG.error(S2SConstants.ERROR_MESSAGE, e);
        throw new S2SException(KeyConstants.ERROR_GRANTSGOV_FORM_PARSING_SAXEXCEPTION, e.getMessage(), schema);
    } catch (IOException e) {
        LOG.error(S2SConstants.ERROR_MESSAGE, e);
        throw new S2SException(KeyConstants.ERROR_GRANTSGOV_FORM_SCHEMA_NOT_FOUND, e.getMessage(), schema);
    }

    Element schemaElement = document.getDocumentElement();
    NodeList importList = document.getElementsByTagNameNS(XSD_NS, IMPORT);
    Node allForms = document.getElementsByTagNameNS(XSD_NS, ALL).item(0);
    NodeList formsList = ((Element) allForms).getElementsByTagNameNS(XSD_NS, ELEMENT);
    String[] formNames = new String[formsList.getLength()];

    for (int formIndex = 0; formIndex < formsList.getLength(); formIndex++) {
        Node form = formsList.item(formIndex);
        String fullFormName = ((Element) form).getAttribute(REF);
        String formName = fullFormName.substring(0, fullFormName.indexOf(CH_COLON));
        String minOccurs = ((Element) form).getAttribute(MIN_OCCURS);
        String nameSpace = schemaElement.getAttribute(XMLNS + formName);
        FormMappingInfo info = null;
        try {
            info = new FormMappingLoader().getFormInfo(nameSpace);
        } catch (S2SGeneratorNotFoundException e) {
        }
        String displayFormName = info == null ? formName : info.getFormName();
        formNames[formIndex] = nameSpace;
        for (int impIndex = 0; impIndex < importList.getLength(); impIndex++) {
            Node importNode = importList.item(impIndex);
            if (((Element) importNode).getAttribute(NAMESPACE).equalsIgnoreCase(nameSpace)) {
                String schemaUrl = ((Element) importNode).getAttribute(SCHEMA_LOCATION);
                S2sOppForms oppForm = new S2sOppForms();
                oppForm.setFormName(displayFormName);
                oppForm.setOppNameSpace(nameSpace);
                oppForm.setSchemaUrl(schemaUrl);
                mandatory = (minOccurs == null || minOccurs.trim().equals("")
                        || Integer.parseInt(minOccurs) > 0);
                oppForm.setMandatory(mandatory);
                available = info != null;//isAvailable(nameSpace);
                oppForm.setAvailable(available);
                oppForm.setInclude(mandatory && available);
                schemaList.add(oppForm);
            }
        }
    }
    return schemaList;
}

From source file:org.ojbc.util.fedquery.entityResolution.EntityResolutionResponseHandlerAggregator.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public void aggregateMergedMessageWithErrorResponses(Exchange groupedExchange) throws Exception {
    //Get the grouped exchanged consisting of the aggregated search results and merged results
    List<Exchange> grouped = groupedExchange.getProperty(Exchange.GROUPED_EXCHANGE, List.class);

    boolean responseHasErrors = false;
    Document erResponseBodyDocument = null;
    Document psResultsBeforeER = null;

    for (Exchange exchange : grouped) {
        //This is the original exchange, it contains the aggregated response message before the Person Search to ER XSLT
        if (grouped.indexOf(exchange) == 0) {
            String messageID = (String) exchange.getIn().getHeader("federatedQueryRequestGUID");

            //The new grouped exchange does not get the message headers from the original exchange so we manually copy the message ID
            groupedExchange.getIn().setHeader("federatedQueryRequestGUID", messageID);

            //Get header to see if we have error nodes.  This is the exchange before calling ER so it has these headers, subsequent exchanges do not.
            String errorResponseNodeCountString = (String) exchange.getIn().getHeader("errorResponseNodeCount");

            Integer errorResponseNodeCount = null;

            if (errorResponseNodeCountString != null) {
                errorResponseNodeCount = Integer.valueOf(errorResponseNodeCountString);
            } else {
                errorResponseNodeCount = 0;
            }// ww  w.  ja va  2 s .c  o  m

            if (errorResponseNodeCount > 0) {
                responseHasErrors = true;

                if (exchange.getIn().getBody().getClass().equals("java.lang.String")) {
                    String aggregatedResponse = (String) exchange.getIn().getBody();

                    //Load up the aggregated results into a document
                    psResultsBeforeER = OJBUtils.loadXMLFromString(aggregatedResponse);

                }

                //Load up the aggregated results into a document
                psResultsBeforeER = exchange.getIn().getBody(Document.class);
            }

        }

        //This is the actual response from the ER service, it will always be exchange indexed at position 1
        else {
            //Uncomment the line below to see the individual aggregated message
            //log.debug("This is the body of the exchange in the exchange group: " + exchange.getIn().getBody());

            CxfPayload cxfPayload = (CxfPayload) exchange.getIn().getBody();
            List<Element> elementList = cxfPayload.getBody();

            erResponseBodyDocument = elementList.get(0).getOwnerDocument();
        }

    }

    //The ER service did not return with an actual response, it is down or has timed out.  Set a static error response and return.
    if (erResponseBodyDocument == null) {
        String returnMessage = MergeNotificationErrorProcessor
                .returnMergeNotificationErrorMessageEntityResolution();
        groupedExchange.getIn().setBody(returnMessage);
        return;
    }

    //If we have errors, splice them into the response
    if (responseHasErrors) {
        log.debug("Response has errors, splice them in here");

        NodeList list = psResultsBeforeER.getElementsByTagNameNS(
                "http://ojbc.org/IEPD/Extensions/SearchResultsMetadata/1.0", "SearchResultsMetadata");
        Element searchResultsMetadataElement = (Element) erResponseBodyDocument.importNode(list.item(0), true);

        Element searchResultsMetadataCollectionElement = erResponseBodyDocument.createElementNS(
                "http://nij.gov/IEPD/Exchange/EntityMergeResultMessage/1.0", "SearchResultsMetadataCollection");
        searchResultsMetadataCollectionElement.appendChild(searchResultsMetadataElement);

        erResponseBodyDocument.getFirstChild().appendChild(searchResultsMetadataCollectionElement);

    }

    //Set the response
    groupedExchange.getIn().setBody(erResponseBodyDocument);

}

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

/**
 * Checks whether or not the given Document contains a valid XML Signature
 * and if it has the exact same content as the original.
 * //from  w ww .  ja  v  a2s .  c om
 * @param cdaFile
 * @param originalCDA
 * @return
 */
public boolean isXMLSignatureValid(Document cdaFile, Document originalCDA) {

    boolean coreValidity = false;

    try {

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

        Document checkCDA = db.newDocument();

        Node copy = checkCDA.importNode(cdaFile.getDocumentElement(), true);
        checkCDA.appendChild(copy);

        if (!isCDAoriginal(checkCDA, originalCDA)) {
            return false;
        }

        // Find Signature element
        NodeList nl = cdaFile.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (nl.getLength() == 0) {
            return false;
        }

        // Create a DOM XMLSignatureFactory that will be used to unmarshal
        // the
        // document containing the XMLSignature
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

        // Create a DOMValidateContext and specify a KeyValue KeySelector
        // and document context
        DOMValidateContext valContext = new DOMValidateContext(new X509KeySelector(), nl.item(0));

        // unmarshal the XMLSignature
        XMLSignature signature = fac.unmarshalXMLSignature(valContext);

        // Validate the XMLSignature (generated above)
        coreValidity = signature.validate(valContext);

        // Check core validation status
        if (coreValidity) {
            return true;
        }
    } catch (Exception e) {
        Logger.getLogger(this.getClass()).error(e);
    }
    return coreValidity;
}

From source file:org.openmrs.projectbuendia.webservices.rest.XformResource.java

/**
 * Removes the relationship nodes added (unconditionally) by xforms. If
 * XFRM-189 is fixed, this method can go away.
 */// www . j  a va  2  s.  c  o  m
static String removeRelationshipNodes(String xml) throws IOException, SAXException {
    Document doc = XmlUtil.parse(xml);
    removeBinding(doc, "patient_relative");
    removeBinding(doc, "patient_relative.person");
    removeBinding(doc, "patient_relative.relationship");

    for (Element relative : toElementIterable(doc.getElementsByTagNameNS("", "patient_relative"))) {
        removeNode(relative);
    }

    // Remove every parent of a label element with a text of
    // "RELATIONSHIPS". (Easiest way to find the ones added...)
    for (Element label : toElementIterable(doc.getElementsByTagNameNS(XFORMS_NAMESPACE, "label"))) {
        Element parent = (Element) label.getParentNode();
        if (XFORMS_NAMESPACE.equals(parent.getNamespaceURI()) && parent.getLocalName().equals("group")
                && "RELATIONSHIPS".equals(label.getTextContent())) {
            removeNode(parent);
            // We don't need to find other labels now, especially if they
            // may already have been removed.
            break;
        }
    }
    return XformsUtil.doc2String(doc);
}

From source file:org.openmrs.projectbuendia.webservices.rest.XformResource.java

private static void removeBinding(Document doc, String id) {
    for (Element binding : toElementIterable(doc.getElementsByTagNameNS(XFORMS_NAMESPACE, "bind"))) {
        if (binding.getAttribute("id").equals(id)) {
            removeNode(binding);/*from  ww w  . j ava2  s.  c om*/
            return;
        }
    }
}