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:Main.java

/**
 * Extracts the element named <var>name</var> with the namespace
 * <var>elementNS</var> that is a descentant of the Document
 * <var>message</var>. This method returns null if the named elemens is not
 * a child of <var>message</var> or if <var>message</var> contains more than
 * one element named <var>name</var>
 * /*from   w w  w  . j  a  v a 2s.com*/
 * @param message
 *            Source Document that contains the element named
 *            <var>name</var>
 * @param elementNS
 *            Namespace of the element named <var>name</var>
 * @param name
 *            Name of the element to be extracted
 * @return Element named <var>name</var>, <br>
 *         or null if <var>message</var> contains zero or more than one
 *         element named <var>name</var>
 */
public static Element extractElement(Document message, String elementNS, String name, boolean strict) {
    NodeList list = message.getElementsByTagNameNS(elementNS, name);
    if (list == null || list.getLength() == 0 || (strict && list.getLength() > 1))
        return null;
    Element element = (Element) list.item(0);
    return element;
}

From source file:org.kitodo.sruimport.ResponseHandler.java

private static int extractNumberOfRecords(Document document) {
    NodeList numberOfRecordNodes = document.getElementsByTagNameNS(SRW_NAMESPACE, SRW_NUMBER_OF_RECORDS_TAG);
    assert numberOfRecordNodes.getLength() == 1;
    Element numberOfRecordsElement = (Element) numberOfRecordNodes.item(0);
    if (Objects.nonNull(numberOfRecordsElement)) {
        return Integer.parseInt(numberOfRecordsElement.getTextContent().trim());
    }//from  w ww  .j a  v  a2s  .c o  m
    return 0;
}

From source file:org.kitodo.sruimport.ResponseHandler.java

private static LinkedList<Record> extractHits(Document document) {
    LinkedList<Record> hits = new LinkedList<>();
    NodeList records = document.getElementsByTagNameNS(SRW_NAMESPACE, SRW_RECORD_TAG);
    for (int i = 0; i < records.getLength(); i++) {
        Element recordElement = (Element) records.item(i);
        hits.add(new Record(getRecordTitle(recordElement), getRecordID(recordElement)));
    }//w  ww  .  j av  a2s .c  o  m
    return hits;
}

From source file:be.fedict.eid.applet.service.signer.odf.ODFSignatureVerifier.java

/**
 * return list of signers for the document available via the given
 * URL.//from w  ww  .  ja  v a  2 s .com
 *
 * @param odfUrl
 * @return list of X509 certificates
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws MarshalException
 * @throws XMLSignatureException
 */
public static List<X509Certificate> getSigners(URL odfUrl) throws IOException, ParserConfigurationException,
        SAXException, MarshalException, XMLSignatureException {
    List<X509Certificate> signers = new LinkedList<X509Certificate>();
    if (null == odfUrl) {
        throw new IllegalArgumentException("odfUrl is null");
    }
    ZipInputStream odfZipInputStream = new ZipInputStream(odfUrl.openStream());
    ZipEntry zipEntry;

    while (null != (zipEntry = odfZipInputStream.getNextEntry())) {
        if (ODFUtil.isSignatureFile(zipEntry)) {
            Document documentSignatures = ODFUtil.loadDocument(odfZipInputStream);
            NodeList signatureNodeList = documentSignatures.getElementsByTagNameNS(XMLSignature.XMLNS,
                    "Signature");

            for (int idx = 0; idx < signatureNodeList.getLength(); idx++) {
                Node signatureNode = signatureNodeList.item(idx);
                X509Certificate signer = getVerifiedSignatureSigner(odfUrl, signatureNode);
                if (null == signer) {
                    LOG.debug("JSR105 says invalid signature");
                } else {
                    signers.add(signer);
                }
            }
            return signers;
        }
    }
    LOG.debug("no signature file present");
    return signers;
}

From source file:Main.java

/**
 * Searches for a node within a DOM document with a given node path expression.
 * Elements are separated by '.' characters.
 * Example: Foo.Bar.Poo//from   w  w  w .  j av  a2 s . co m
 * @param doc DOM Document to search for a node.
 * @param pathExpression dot separated path expression
 * @return Node element found in the DOM document.
 */
public static Node findNodeByName(Document doc, String pathExpression) {
    final StringTokenizer tok = new StringTokenizer(pathExpression, ".");
    final int numToks = tok.countTokens();
    NodeList elements;
    if (numToks == 1) {
        elements = doc.getElementsByTagNameNS("*", pathExpression);
        return elements.item(0);
    }

    String element = pathExpression.substring(pathExpression.lastIndexOf('.') + 1);
    elements = doc.getElementsByTagNameNS("*", element);

    String attributeName = null;
    if (elements.getLength() == 0) {
        //No element found, but maybe we are searching for an attribute
        attributeName = element;

        //cut off attributeName and set element to next token and continue
        Node found = findNodeByName(doc,
                pathExpression.substring(0, pathExpression.length() - attributeName.length() - 1));

        if (found != null) {
            return found.getAttributes().getNamedItem(attributeName);
        } else {
            return null;
        }
    }

    StringBuffer pathName;
    Node parent;
    for (int j = 0; j < elements.getLength(); j++) {
        int cnt = numToks - 1;
        pathName = new StringBuffer(element);
        parent = elements.item(j).getParentNode();
        do {
            if (parent != null) {
                pathName.insert(0, '.');
                pathName.insert(0, parent.getLocalName());//getNodeName());

                parent = parent.getParentNode();
            }
        } while (parent != null && --cnt > 0);
        if (pathName.toString().equals(pathExpression)) {
            return elements.item(j);
        }
    }

    return null;
}

From source file:no.digipost.api.xml.Marshalling.java

public static void trimNamespaces(final Document doc) {
    NamedNodeMap attributes = doc.getDocumentElement().getAttributes();
    List<Attr> attrsToRemove = new ArrayList<Attr>();
    for (int i = 0; i < attributes.getLength(); i++) {
        if (doc.getElementsByTagNameNS(attributes.item(i).getNodeValue(), "*").getLength() == 0) {
            attrsToRemove.add((Attr) attributes.item(i));
        }//  w w  w. ja v a  2s  .  c  o m
    }
    for (Attr a : attrsToRemove) {
        doc.getDocumentElement().removeAttributeNode(a);
    }
}

From source file:com.sun.tools.xjc.addon.xew.XmlElementWrapperPluginTest.java

/**
 * Return values of all {@code <jaxb:class ref="..." />} attributes.
 *//*from  w w w.  j a v  a  2 s .  c  om*/
private static Set<String> getClassReferencesFromEpisodeFile(String episodeFile) throws SAXException {
    DOMForest forest = new DOMForest(new XMLSchemaInternalizationLogic(), new Options());

    Document episodeDocument = forest.parse(new InputSource(episodeFile), true);

    NodeList nodeList = episodeDocument.getElementsByTagNameNS(Const.JAXB_NSURI, "class");
    Set<String> classReferences = new HashSet<String>();

    for (int i = 0, len = nodeList.getLength(); i < len; i++) {
        classReferences.add(((Element) nodeList.item(i)).getAttribute("ref"));
    }

    return classReferences;
}

From source file:be.e_contract.dssp.client.SignResponseVerifier.java

/**
 * Checks the signature on the SignResponse browser POST message.
 * //from  w  w  w  .j a va 2s  .c o  m
 * @param signResponseMessage
 *            the SignResponse message.
 * @param session
 *            the session object.
 * @return the verification result object.
 * @throws JAXBException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws MarshalException
 * @throws XMLSignatureException
 * @throws Base64DecodingException
 * @throws UserCancelException
 * @throws ClientRuntimeException
 * @throws SubjectNotAuthorizedException
 */
public static SignResponseVerificationResult checkSignResponse(String signResponseMessage,
        DigitalSignatureServiceSession session) throws JAXBException, ParserConfigurationException,
        SAXException, IOException, MarshalException, XMLSignatureException, Base64DecodingException,
        UserCancelException, ClientRuntimeException, SubjectNotAuthorizedException {
    if (null == session) {
        throw new IllegalArgumentException("missing session");
    }

    byte[] decodedSignResponseMessage;
    try {
        decodedSignResponseMessage = Base64.decode(signResponseMessage);
    } catch (Base64DecodingException e) {
        throw new SecurityException("no Base64");
    }
    // JAXB parsing
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class,
            be.e_contract.dssp.ws.jaxb.dss.async.ObjectFactory.class,
            be.e_contract.dssp.ws.jaxb.wsa.ObjectFactory.class,
            be.e_contract.dssp.ws.jaxb.wsu.ObjectFactory.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    SignResponse signResponse;
    try {
        signResponse = (SignResponse) unmarshaller
                .unmarshal(new ByteArrayInputStream(decodedSignResponseMessage));
    } catch (UnmarshalException e) {
        throw new SecurityException("no valid SignResponse XML");
    }

    // DOM parsing
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    InputStream signResponseInputStream = new ByteArrayInputStream(decodedSignResponseMessage);
    Document signResponseDocument = documentBuilder.parse(signResponseInputStream);

    // signature verification
    NodeList signatureNodeList = signResponseDocument
            .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Signature");
    if (signatureNodeList.getLength() != 1) {
        throw new SecurityException("requires 1 ds:Signature element");
    }
    Element signatureElement = (Element) signatureNodeList.item(0);
    SecurityTokenKeySelector keySelector = new SecurityTokenKeySelector(session.getKey());
    DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement);
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");
    XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
    boolean validSignature = xmlSignature.validate(domValidateContext);
    if (false == validSignature) {
        throw new SecurityException("invalid ds:Signature");
    }

    // verify content
    String responseId = null;
    RelatesToType relatesTo = null;
    AttributedURIType to = null;
    TimestampType timestamp = null;
    String signerIdentity = null;
    AnyType optionalOutputs = signResponse.getOptionalOutputs();
    List<Object> optionalOutputsList = optionalOutputs.getAny();
    for (Object optionalOutputObject : optionalOutputsList) {
        LOG.debug("optional output object type: " + optionalOutputObject.getClass().getName());
        if (optionalOutputObject instanceof JAXBElement) {
            JAXBElement optionalOutputElement = (JAXBElement) optionalOutputObject;
            LOG.debug("optional output name: " + optionalOutputElement.getName());
            LOG.debug("optional output value type: " + optionalOutputElement.getValue().getClass().getName());
            if (RESPONSE_ID_QNAME.equals(optionalOutputElement.getName())) {
                responseId = (String) optionalOutputElement.getValue();
            } else if (optionalOutputElement.getValue() instanceof RelatesToType) {
                relatesTo = (RelatesToType) optionalOutputElement.getValue();
            } else if (TO_QNAME.equals(optionalOutputElement.getName())) {
                to = (AttributedURIType) optionalOutputElement.getValue();
            } else if (optionalOutputElement.getValue() instanceof TimestampType) {
                timestamp = (TimestampType) optionalOutputElement.getValue();
            } else if (optionalOutputElement.getValue() instanceof NameIdentifierType) {
                NameIdentifierType nameIdentifier = (NameIdentifierType) optionalOutputElement.getValue();
                signerIdentity = nameIdentifier.getValue();
            }
        }
    }

    Result result = signResponse.getResult();
    LOG.debug("result major: " + result.getResultMajor());
    LOG.debug("result minor: " + result.getResultMinor());
    if (DigitalSignatureServiceConstants.REQUESTER_ERROR_RESULT_MAJOR.equals(result.getResultMajor())) {
        if (DigitalSignatureServiceConstants.USER_CANCEL_RESULT_MINOR.equals(result.getResultMinor())) {
            throw new UserCancelException();
        }
        if (DigitalSignatureServiceConstants.CLIENT_RUNTIME_RESULT_MINOR.equals(result.getResultMinor())) {
            throw new ClientRuntimeException();
        }
        if (DigitalSignatureServiceConstants.SUBJECT_NOT_AUTHORIZED_RESULT_MINOR
                .equals(result.getResultMinor())) {
            throw new SubjectNotAuthorizedException(signerIdentity);
        }
    }
    if (false == DigitalSignatureServiceConstants.PENDING_RESULT_MAJOR.equals(result.getResultMajor())) {
        throw new SecurityException("invalid dss:ResultMajor");
    }

    if (null == responseId) {
        throw new SecurityException("missing async:ResponseID");
    }
    if (false == responseId.equals(session.getResponseId())) {
        throw new SecurityException("invalid async:ResponseID");
    }

    if (null == relatesTo) {
        throw new SecurityException("missing wsa:RelatesTo");
    }
    if (false == session.getInResponseTo().equals(relatesTo.getValue())) {
        throw new SecurityException("invalid wsa:RelatesTo");
    }

    if (null == to) {
        throw new SecurityException("missing wsa:To");
    }
    if (false == session.getDestination().equals(to.getValue())) {
        throw new SecurityException("invalid wsa:To");
    }

    if (null == timestamp) {
        throw new SecurityException("missing wsu:Timestamp");
    }
    AttributedDateTime expires = timestamp.getExpires();
    if (null == expires) {
        throw new SecurityException("missing wsu:Timestamp/wsu:Expires");
    }
    DateTime expiresDateTime = new DateTime(expires.getValue());
    DateTime now = new DateTime();
    if (now.isAfter(expiresDateTime)) {
        throw new SecurityException("wsu:Timestamp expired");
    }

    session.setSignResponseVerified(true);

    SignResponseVerificationResult signResponseVerificationResult = new SignResponseVerificationResult(
            signerIdentity);
    return signResponseVerificationResult;
}

From source file:filehandling.FilePreprocessor.java

public static List<FileData> extractMDFilesFromXMLEmbedding(byte[] bytes, String basename, String extension) {

    List<FileData> returnList = new ArrayList<FileData>();
    try {/*  w  w  w. j a  v a2 s . c o  m*/
        FileUtils.writeByteArrayToFile(new File("/tmp/debugData/instreamBeforeExtraction.xml"), bytes);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder dBuilder = dbf.newDocumentBuilder();

        Document doc = dBuilder.parse(new InputSource(new ByteArrayInputStream(bytes)));

        if (Master.DEBUG_LEVEL > Master.LOW) {
            System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
        }

        NodeList entryElements = doc.getElementsByTagNameNS("http://www.w3.org/2005/Atom", "entry");
        for (int i = 0; i < entryElements.getLength(); i++) {
            Element entryElement = (Element) entryElements.item(i);
            FileData fd = null;
            /*
             * First try to find a <link> element pointing to Metadata as
             * this should be included by default
             */
            if (fd == null) {
                NodeList linkElements = entryElement.getElementsByTagNameNS("http://www.w3.org/2005/Atom",
                        "link");
                String iso19139Link = null;
                String iso19139_2Link = null;
                for (int j = 0; j < linkElements.getLength(); j++) {
                    Element linkElement = (Element) linkElements.item(j);
                    String relAttrValue = linkElement.getAttribute("rel");
                    String typeAttributeValue = linkElement.getAttribute("type");
                    if (relAttrValue != null && relAttrValue.equals("alternate")
                            && typeAttributeValue != null) {
                        switch (typeAttributeValue) {
                        case "application/vnd.iso.19139+xml":
                            iso19139Link = linkElement.getAttribute("href");
                            break;
                        case "application/vnd.iso.19139-2+xml":
                            iso19139_2Link = linkElement.getAttribute("href");
                            break;
                        }
                    }
                }
                /* iso19139-2 gets priority */
                String url = iso19139_2Link != null ? iso19139_2Link : iso19139Link;
                if (url != null) {
                    try (InputStream is = FileFetcher.fetchFileFromUrl(url)) {
                        Document doc2 = dBuilder.parse(new InputSource(is));
                        fd = processMDList(doc2.getDocumentElement(), extension, url);
                    }
                }
            }
            /*
             * Fallback to finding Metadata embedded directly in <entry>.
             * There will be either MI_Metadata or MD_Metadata, not both
             */
            if (fd == null) {
                fd = processMDList(entryElement.getElementsByTagName("gmi:MI_Metadata").item(0), extension,
                        null);
            }
            if (fd == null) {
                fd = processMDList(entryElement.getElementsByTagName("gmd:MD_Metadata").item(0), extension,
                        null);
            }

            if (fd != null) {
                returnList.add(fd);
            }
        }
    } catch (Exception e) {
        // TODO: handle exception

        if (Master.DEBUG_LEVEL > Master.LOW)
            System.out.println(e.getLocalizedMessage());
        GUIrefs.displayAlert("Error in FilePreprocessor.extractMDFilesFromXMLEmbedding"
                + StringUtilities.escapeQuotes(e.getMessage()));
    }
    return returnList;
}

From source file:com.helger.peppol.httpclient.SMPHttpResponseHandlerSigned.java

private static boolean _checkSignature(@Nonnull @WillClose final InputStream aEntityInputStream)
        throws Exception {
    try {//from w  w w .  j  a  v a 2s  .co m
        // Get response from servlet
        final Document aDocument = DOMReader.readXMLDOM(aEntityInputStream);

        // We make sure that the XML is a Signed. If not, we don't have to check
        // any certificates.

        // Find Signature element.
        final NodeList aNodeList = aDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (aNodeList == null || aNodeList.getLength() == 0)
            throw new IllegalArgumentException("Element <Signature> not found in SMP XML response");

        // Create a DOMValidateContext and specify a KeySelector
        // and document context.
        final X509KeySelector aKeySelector = new X509KeySelector();
        final DOMValidateContext aValidateContext = new DOMValidateContext(aKeySelector, aNodeList.item(0));
        final XMLSignatureFactory aSignatureFactory = XMLSignatureFactory.getInstance("DOM");

        // Unmarshal the XMLSignature.
        final XMLSignature aSignature = aSignatureFactory.unmarshalXMLSignature(aValidateContext);

        // Validate the XMLSignature.
        final boolean bCoreValid = aSignature.validate(aValidateContext);
        if (!bCoreValid) {
            // This code block is for debugging purposes only - it has no semantical
            // influence
            s_aLogger.info("Signature failed core validation");
            final boolean bSignatureValueValid = aSignature.getSignatureValue().validate(aValidateContext);
            s_aLogger.info("  Signature value valid: " + bSignatureValueValid);
            if (!bSignatureValueValid) {
                // Check the validation status of each Reference.
                int nIndex = 0;
                final Iterator<?> i = aSignature.getSignedInfo().getReferences().iterator();
                while (i.hasNext()) {
                    final boolean bRefValid = ((Reference) i.next()).validate(aValidateContext);
                    s_aLogger.info("  Reference[" + nIndex + "] validity status: "
                            + (bRefValid ? "valid" : "NOT valid!"));
                    ++nIndex;
                }
            }
        }
        return bCoreValid;
    } finally {
        // Close the input stream
        StreamHelper.close(aEntityInputStream);
    }
}