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:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandlerTest.java

@Test
public void testPerformEntityResolutionWithDetermFactors() throws Exception {
    XmlConverter converter = new XmlConverter();
    converter.getDocumentBuilderFactory().setNamespaceAware(true);
    InputStream attributeParametersStream = getClass()
            .getResourceAsStream("/xml/TestAttributeParametersWithDeterm.xml");
    entityResolutionMessageHandler.setAttributeParametersStream(attributeParametersStream);
    testRequestMessageInputStream = getClass()
            .getResourceAsStream("/xml/EntityMergeRequestMessageForDeterm.xml");
    Document testRequestMessage = converter.toDOMDocument(testRequestMessageInputStream);

    Node entityContainerNode = testRequestMessage
            .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "EntityContainer")
            .item(0);//from  w  w w .  j a va 2 s  .c  o m
    assertNotNull(entityContainerNode);
    Document resultDocument = entityResolutionMessageHandler.performEntityResolution(entityContainerNode, null,
            null);

    resultDocument.normalizeDocument();
    // LOG.info(converter.toString(resultDocument));
    XPath xp = XPathFactory.newInstance().newXPath();
    xp.setNamespaceContext(new EntityResolutionNamespaceContext());
    NodeList entityNodes = (NodeList) xp.evaluate("//merge-result:EntityContainer/merge-result-ext:Entity",
            resultDocument, XPathConstants.NODESET);
    assertEquals(2, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord", resultDocument,
            XPathConstants.NODESET);
    assertEquals(2, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:OriginalRecordReference", resultDocument,
            XPathConstants.NODESET);
    assertEquals(2, entityNodes.getLength());
    for (int i = 0; i < entityNodes.getLength(); i++) {
        Element e = (Element) entityNodes.item(i);
        String entityIdRef = e.getAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE, "ref");
        assertNotNull(entityIdRef);
        assertNotNull(xp.evaluate("//merge-result-ext:Entity[@s:id='" + entityIdRef + "']", resultDocument,
                XPathConstants.NODE));
    }
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandlerTest.java

@Test
public void testCreateRecords() throws Exception {
    XmlConverter converter = new XmlConverter();
    converter.getDocumentBuilderFactory().setNamespaceAware(true);
    Document testRequestMessage = converter.toDOMDocument(testRequestMessageInputStream);
    assertNotNull(testRequestMessage);//from w w w  .  j  ava2  s  .  c  o m

    Node entityContainerNode = testRequestMessage
            .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "EntityContainer")
            .item(0);
    NodeList entityNodeList = ((Element) entityContainerNode)
            .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "Entity");
    assertNotNull(entityContainerNode);
    assertNotNull(entityNodeList);

    List<ExternallyIdentifiableRecord> records = EntityResolutionConversionUtils.convertRecordWrappers(
            entityResolutionMessageHandler.createRecordsFromRequestMessage(entityNodeList, null));

    assertNotNull(records);
    assertEquals(6, records.size());
    boolean mickeyFound = false;
    boolean minnieFound = false;
    boolean minnyFound = false;
    for (ExternallyIdentifiableRecord record : records) {
        Attribute a = record.getAttribute("ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonGivenName");
        assertNotNull(a);
        assertEquals(1, a.getValuesCount());
        String value = a.iterator().next();
        if ("Mickey".equals(value)) {
            mickeyFound = true;
        } else if ("Minnie".equals(value)) {
            minnieFound = true;
        } else if ("Minny".equals(value)) {
            minnyFound = true;
        }
    }
    assertTrue(mickeyFound);
    assertTrue(minnieFound);
    assertTrue(minnyFound);
}

From source file:com.alvexcore.repo.SimpleKeySelectorResult.java

private LicenseInfo getLicenseInfo(InputStream lic) {
    Document licenseXML = null;
    try {/*from w  w  w.j a v a  2  s.com*/
        DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
        fact.setNamespaceAware(true);
        licenseXML = fact.newDocumentBuilder().parse(lic);
        NodeList nl = licenseXML.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        DOMValidateContext valContext = new DOMValidateContext(new AlvexKeySelector(), nl.item(0));
        XMLSignatureFactory sfac = XMLSignatureFactory.getInstance("DOM");
        XMLSignature sgn = sfac.unmarshalXMLSignature(valContext);
        if (!sgn.validate(valContext))
            return LicenseInfo.INVALID_LICENSE;
    } catch (Exception ex) {
        return LicenseInfo.INVALID_LICENSE;
    }
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    String id = licenseXML.getDocumentElement().getElementsByTagName("id").item(0).getTextContent();
    String product = licenseXML.getDocumentElement().getElementsByTagName("product").item(0).getTextContent();
    String owner = licenseXML.getDocumentElement().getElementsByTagName("owner").item(0).getTextContent();
    String edition = licenseXML.getDocumentElement().getElementsByTagName("edition").item(0).getTextContent();

    // We intentially have separate try/catch blocks. These tags may fail independently
    // and we'd like to prevent failed version tag from stopping dates parsing.
    String version = ANY_VERSION;
    try {
        version = licenseXML.getDocumentElement().getElementsByTagName("version").item(0).getTextContent();
    } catch (Exception e) {
    }

    Date issued = null;
    Date validThru = null;
    try {
        String expiresStr = licenseXML.getDocumentElement().getElementsByTagName("expires").item(0)
                .getTextContent();
        validThru = sdf.parse(expiresStr);
        String issuedStr = licenseXML.getDocumentElement().getElementsByTagName("issued").item(0)
                .getTextContent();
        issued = sdf.parse(issuedStr);
    } catch (Exception e) {
        String expiresStr = licenseXML.getDocumentElement().getElementsByTagName("expires").item(0)
                .getTextContent();
        String issuedStr = licenseXML.getDocumentElement().getElementsByTagName("issued").item(0)
                .getTextContent();
        logger.warn(
                "Can not parse license dates. " + "Issued: " + issuedStr + ". Expires: " + expiresStr + ".");
    }

    int cores = new Integer(
            licenseXML.getDocumentElement().getElementsByTagName("cores").item(0).getTextContent());
    int users = new Integer(
            licenseXML.getDocumentElement().getElementsByTagName("users").item(0).getTextContent());

    return new LicenseInfo(id, owner, product, edition, version, cores, users, issued, validThru, false);
}

From source file:kml.feature.Placemark.java

public void setDoc(Document doc) {
    this.doc = doc;
    boolean excludeStylesInPlacemark = true;
    this.style = new Styles(doc, excludeStylesInPlacemark);
    doc.getDocumentElement().normalize();
    // Get placemarks 
    NodeList nl = doc.getElementsByTagNameNS("*", "Placemark");
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);/*from   ww  w  . j  a  v  a 2  s.c o  m*/
        //System.out.println("Current Element [" + i + "] " + node.getNodeName());
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;
            this.setPlacemarkElement(element);
        } //node
    } //for nodes
}

From source file:eu.europa.ec.markt.dss.validation102853.tsl.TrustedListsCertificateSource.java

/**
 * Load a trusted list for the specified URL
 *
 * @param url// www .j av a 2 s  . co m
 * @param signerCert
 * @return
 * @throws IOException
 */
private TrustStatusList getTrustStatusList(String url, X509Certificate signerCert) {

    InputStream input = null;
    try {

        input = dataLoader.get(url);
        if (input == null) {

            throw new DSSNullReturnedException("The loader returned a null InputStream for: " + url);
        }
        if (url.toLowerCase().endsWith(".zip")) {

            input = getZippedData(input);
        }

        Document doc = DSSXMLUtils.buildDOM(input);

        boolean coreValidity = true;
        if (checkSignature) {

            coreValidity = false;
            if (signerCert != null) {

                final NodeList signatureNodeList = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
                if (signatureNodeList.getLength() == 0) {

                    throw new DSSException("Not ETSI compliant signature. The Xml is not signed.");
                }
                if (signatureNodeList.getLength() > 1) {

                    throw new DSSException("Not ETSI compliant signature. There is more than one signature.");
                }
                final Element signatureEl = (Element) signatureNodeList.item(0);

                final KeySelector keySelector = KeySelector.singletonKeySelector(signerCert.getPublicKey());
                final DOMValidateContext valContext = new DOMValidateContext(keySelector, signatureEl);
                final TSLURIDereferencer tsluriDereferencer = new TSLURIDereferencer(signatureEl);
                valContext.setURIDereferencer(tsluriDereferencer);
                final XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM");
                final XMLSignature signature = factory.unmarshalXMLSignature(valContext);
                coreValidity = signature.validate(valContext);
                LOG.info("The TSL signature validity: " + coreValidity);
            }
        }
        final TrustStatusList tsl = TrustServiceListFactory.newInstance(doc);
        tsl.setWellSigned(coreValidity);
        return tsl;
    } catch (DSSException e) {

        throw e;
    } catch (Exception e) {

        throw new DSSException(e);
    } finally {

        DSSUtils.closeQuietly(input);
    }
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandlerTest.java

@Test
public void testRecordLimit() throws Exception {

    XmlConverter converter = new XmlConverter();
    converter.getDocumentBuilderFactory().setNamespaceAware(true);
    Document testRequestMessage = converter.toDOMDocument(testRequestMessageInputStream);

    Node entityContainerNode = testRequestMessage
            .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "EntityContainer")
            .item(0);//from w  ww . j a v a  2s .  c o m
    assertNotNull(entityContainerNode);

    Node entityResolutionConfigurationNode = makeEntityResolutionConfigurationNode(
            String.valueOf(Integer.MAX_VALUE));

    Document resultDocument = entityResolutionMessageHandler.performEntityResolution(entityContainerNode, null,
            entityResolutionConfigurationNode);

    XPath xp = XPathFactory.newInstance().newXPath();
    xp.setNamespaceContext(new EntityResolutionNamespaceContext());
    NodeList entityNodes = (NodeList) xp.evaluate("//merge-result:EntityContainer/merge-result-ext:Entity",
            resultDocument, XPathConstants.NODESET);
    int inputEntityNodeCount = 6;
    assertEquals(inputEntityNodeCount, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord", resultDocument,
            XPathConstants.NODESET);
    assertEquals(3, entityNodes.getLength());
    String recordLimitExceeded = xp.evaluate(
            "/merge-result:EntityMergeResultMessage/merge-result:RecordLimitExceededIndicator", resultDocument);
    assertEquals("false", recordLimitExceeded);

    entityResolutionConfigurationNode = makeEntityResolutionConfigurationNode(6 + "");

    resultDocument = entityResolutionMessageHandler.performEntityResolution(entityContainerNode, null,
            entityResolutionConfigurationNode);

    xp.setNamespaceContext(new EntityResolutionNamespaceContext());
    entityNodes = (NodeList) xp.evaluate("//merge-result:EntityContainer/merge-result-ext:Entity",
            resultDocument, XPathConstants.NODESET);
    inputEntityNodeCount = 6;
    assertEquals(inputEntityNodeCount, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord", resultDocument,
            XPathConstants.NODESET);
    assertEquals(3, entityNodes.getLength());
    recordLimitExceeded = xp.evaluate(
            "/merge-result:EntityMergeResultMessage/merge-result:RecordLimitExceededIndicator", resultDocument);
    assertEquals("false", recordLimitExceeded);

    entityResolutionConfigurationNode = makeEntityResolutionConfigurationNode(null);

    resultDocument = entityResolutionMessageHandler.performEntityResolution(entityContainerNode, null,
            entityResolutionConfigurationNode);

    xp.setNamespaceContext(new EntityResolutionNamespaceContext());
    entityNodes = (NodeList) xp.evaluate("//merge-result:EntityContainer/merge-result-ext:Entity",
            resultDocument, XPathConstants.NODESET);
    inputEntityNodeCount = 6;
    assertEquals(inputEntityNodeCount, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord", resultDocument,
            XPathConstants.NODESET);
    assertEquals(3, entityNodes.getLength());
    recordLimitExceeded = xp.evaluate(
            "/merge-result:EntityMergeResultMessage/merge-result:RecordLimitExceededIndicator", resultDocument);
    assertEquals("false", recordLimitExceeded);

    entityResolutionConfigurationNode = makeEntityResolutionConfigurationNode("not an int");

    resultDocument = entityResolutionMessageHandler.performEntityResolution(entityContainerNode, null,
            entityResolutionConfigurationNode);

    xp.setNamespaceContext(new EntityResolutionNamespaceContext());
    entityNodes = (NodeList) xp.evaluate("//merge-result:EntityContainer/merge-result-ext:Entity",
            resultDocument, XPathConstants.NODESET);
    inputEntityNodeCount = 6;
    assertEquals(inputEntityNodeCount, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord", resultDocument,
            XPathConstants.NODESET);
    assertEquals(3, entityNodes.getLength());
    recordLimitExceeded = xp.evaluate(
            "/merge-result:EntityMergeResultMessage/merge-result:RecordLimitExceededIndicator", resultDocument);
    assertEquals("false", recordLimitExceeded);

    entityResolutionConfigurationNode = makeEntityResolutionConfigurationNode(2 + "");

    Document attributeParametersDocument = entityResolutionMessageHandler.getAttributeParametersDocument();
    resultDocument = entityResolutionMessageHandler.performEntityResolution(entityContainerNode,
            attributeParametersDocument.getDocumentElement(), entityResolutionConfigurationNode);

    xp.setNamespaceContext(new EntityResolutionNamespaceContext());
    entityNodes = (NodeList) xp.evaluate("//merge-result:EntityContainer/merge-result-ext:Entity",
            resultDocument, XPathConstants.NODESET);
    inputEntityNodeCount = 6;
    assertEquals(inputEntityNodeCount, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord", resultDocument,
            XPathConstants.NODESET);
    assertEquals(6, entityNodes.getLength());
    recordLimitExceeded = xp.evaluate(
            "/merge-result:EntityMergeResultMessage/merge-result:RecordLimitExceededIndicator", resultDocument);
    assertEquals("true", recordLimitExceeded);

    // LOG.info(new XmlConverter().toString(resultDocument));
    NodeList statNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord/merge-result-ext:MergeQuality",
            resultDocument, XPathConstants.NODESET);
    assertEquals(6, statNodes.getLength());
    statNodes = (NodeList) xp.evaluate(
            "//merge-result-ext:MergedRecord/merge-result-ext:MergeQuality/merge-result-ext:StringDistanceStatistics",
            resultDocument, XPathConstants.NODESET);
    assertEquals(12, statNodes.getLength());
    statNodes = (NodeList) xp.evaluate(
            "//merge-result-ext:MergedRecord/merge-result-ext:MergeQuality/merge-result-ext:StringDistanceStatistics/merge-result-ext:AttributeXPath",
            resultDocument, XPathConstants.NODESET);
    assertEquals(12, statNodes.getLength());
    statNodes = (NodeList) xp.evaluate(
            "//merge-result-ext:MergedRecord/merge-result-ext:MergeQuality/merge-result-ext:StringDistanceStatistics/merge-result-ext:StringDistanceMeanInRecord",
            resultDocument, XPathConstants.NODESET);
    assertEquals(12, statNodes.getLength());
    statNodes = (NodeList) xp.evaluate(
            "//merge-result-ext:MergedRecord/merge-result-ext:MergeQuality/merge-result-ext:StringDistanceStatistics/merge-result-ext:StringDistanceStandardDeviationInRecord",
            resultDocument, XPathConstants.NODESET);
    assertEquals(12, statNodes.getLength());
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandlerTest.java

/**
 * This unit test will read a entity merge request document that has given and sur names in mixed case.
 * It will then set an ER threshold of 3 and pass in six entities so ER is skipped.
 * However, the results should still be sorted and passed back in order.
 * /*from w w  w . j  a v  a  2 s. co m*/
 * @throws Exception
 */

@Test
public void testRecordLimitSorting() throws Exception {

    XmlConverter converter = new XmlConverter();
    converter.getDocumentBuilderFactory().setNamespaceAware(true);
    Document testRequestMessage = converter
            .toDOMDocument(getClass().getResourceAsStream("/xml/EntityMergeRequestMessageMixedCase.xml"));

    Node entityContainerNode = testRequestMessage
            .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "EntityContainer")
            .item(0);
    assertNotNull(entityContainerNode);

    Node entityResolutionConfigurationNode = makeEntityResolutionConfigurationNode("2");

    Document attributeParametersDocument = entityResolutionMessageHandler.getAttributeParametersDocument();

    Document resultDocument = entityResolutionMessageHandler.performEntityResolution(entityContainerNode,
            attributeParametersDocument.getDocumentElement(), entityResolutionConfigurationNode);

    XPath xp = XPathFactory.newInstance().newXPath();
    xp.setNamespaceContext(testNamespaceContext);
    NodeList entityNodes = (NodeList) xp.evaluate("//merge-result:EntityContainer/merge-result-ext:Entity",
            resultDocument, XPathConstants.NODESET);
    int inputEntityNodeCount = 6;
    assertEquals(inputEntityNodeCount, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord", resultDocument,
            XPathConstants.NODESET);
    assertEquals(6, entityNodes.getLength());
    String recordLimitExceeded = xp.evaluate(
            "/merge-result:EntityMergeResultMessage/merge-result:RecordLimitExceededIndicator", resultDocument);
    assertEquals("true", recordLimitExceeded);

    assertEquals("DUCK", xp.evaluate(
            "//merge-result:EntityContainer/merge-result-ext:Entity[1]/ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonSurName",
            resultDocument));
    assertEquals("Donald", xp.evaluate(
            "//merge-result:EntityContainer/merge-result-ext:Entity[1]/ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonGivenName",
            resultDocument));

    assertEquals("MOUSE", xp.evaluate(
            "//merge-result:EntityContainer/merge-result-ext:Entity[2]/ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonSurName",
            resultDocument));
    assertEquals("FRANK", xp.evaluate(
            "//merge-result:EntityContainer/merge-result-ext:Entity[2]/ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonGivenName",
            resultDocument));

    assertEquals("mouse", xp.evaluate(
            "//merge-result:EntityContainer/merge-result-ext:Entity[3]/ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonSurName",
            resultDocument));
    assertEquals("macky", xp.evaluate(
            "//merge-result:EntityContainer/merge-result-ext:Entity[3]/ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonGivenName",
            resultDocument));

    assertEquals("MouSe", xp.evaluate(
            "//merge-result:EntityContainer/merge-result-ext:Entity[4]/ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonSurName",
            resultDocument));
    assertEquals("Mickey", xp.evaluate(
            "//merge-result:EntityContainer/merge-result-ext:Entity[4]/ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonGivenName",
            resultDocument));

    assertEquals("MOUSE", xp.evaluate(
            "//merge-result:EntityContainer/merge-result-ext:Entity[5]/ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonSurName",
            resultDocument));
    assertEquals("Minn", xp.evaluate(
            "//merge-result:EntityContainer/merge-result-ext:Entity[5]/ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonGivenName",
            resultDocument));

    assertEquals("Mouse", xp.evaluate(
            "//merge-result:EntityContainer/merge-result-ext:Entity[6]/ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonSurName",
            resultDocument));
    assertEquals("MINNY", xp.evaluate(
            "//merge-result:EntityContainer/merge-result-ext:Entity[6]/ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonGivenName",
            resultDocument));

    //LOG.info(new XmlConverter().toString(resultDocument));

}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandlerTest.java

@Test
public void testPerformEntityResolution() throws Exception {

    XPath xp = XPathFactory.newInstance().newXPath();
    xp.setNamespaceContext(testNamespaceContext);

    XmlConverter converter = new XmlConverter();
    converter.getDocumentBuilderFactory().setNamespaceAware(true);
    Document testRequestMessage = converter.toDOMDocument(testRequestMessageInputStream);
    // LOG.info(converter.toString(testRequestMessage));

    Node entityContainerNode = testRequestMessage
            .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "EntityContainer")
            .item(0);/*from   w  w w.ja v  a2s .c  om*/
    assertNotNull(entityContainerNode);

    List<String> lastNames = new ArrayList<String>();
    List<String> firstNames = new ArrayList<String>();
    List<String> sids = new ArrayList<String>();

    NodeList inputEntityNodes = (NodeList) testRequestMessage
            .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "Entity");
    int inputEntityNodeCount = 6;
    assertEquals(inputEntityNodeCount, inputEntityNodes.getLength());

    for (int i = 0; i < inputEntityNodeCount; i++) {
        Node entityNode = inputEntityNodes.item(i);
        lastNames.add(
                xp.evaluate("ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonSurName", entityNode));
        firstNames.add(
                xp.evaluate("ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonGivenName", entityNode));
        sids.add(xp.evaluate(
                "ext:PersonSearchResult/ext:Person/jxdm:PersonAugmentation/jxdm:PersonStateFingerprintIdentification/nc:IdentificationID",
                entityNode));
    }

    Map<String, Integer> lastNameCountMap = new HashMap<String, Integer>();
    for (String lastName : lastNames) {
        Integer count = lastNameCountMap.get(lastName);
        if (count == null) {
            count = 0;
        }
        lastNameCountMap.put(lastName, ++count);
    }
    Map<String, Integer> firstNameCountMap = new HashMap<String, Integer>();
    for (String firstName : firstNames) {
        Integer count = firstNameCountMap.get(firstName);
        if (count == null) {
            count = 0;
        }
        firstNameCountMap.put(firstName, ++count);
    }
    Map<String, Integer> sidCountMap = new HashMap<String, Integer>();
    for (String sid : sids) {
        Integer count = sidCountMap.get(sid);
        if (count == null) {
            count = 0;
        }
        sidCountMap.put(sid, ++count);
    }

    Document resultDocument = entityResolutionMessageHandler.performEntityResolution(entityContainerNode, null,
            null);

    resultDocument.normalizeDocument();
    // LOG.info(converter.toString(resultDocument));
    NodeList entityNodes = (NodeList) xp.evaluate("//merge-result:EntityContainer/merge-result-ext:Entity",
            resultDocument, XPathConstants.NODESET);
    assertEquals(inputEntityNodeCount, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord", resultDocument,
            XPathConstants.NODESET);
    assertEquals(3, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:OriginalRecordReference", resultDocument,
            XPathConstants.NODESET);
    assertEquals(inputEntityNodeCount, entityNodes.getLength());
    for (int i = 0; i < entityNodes.getLength(); i++) {
        Element e = (Element) entityNodes.item(i);
        String entityIdRef = e.getAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE, "ref");
        assertNotNull(entityIdRef);
        assertNotNull(xp.evaluate("//merge-result-ext:Entity[@s:id='" + entityIdRef + "']", resultDocument,
                XPathConstants.NODE));
    }
    for (String lastName : lastNameCountMap.keySet()) {
        assertEquals(lastNameCountMap.get(lastName).intValue(), ((Number) xp.evaluate(
                "count(//merge-result-ext:Entity[ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonSurName='"
                        + lastName + "'])",
                resultDocument, XPathConstants.NUMBER)).intValue());
    }
    for (String firstName : firstNames) {
        assertEquals(firstNameCountMap.get(firstName).intValue(), ((Number) xp.evaluate(
                "count(//merge-result-ext:Entity[ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonGivenName='"
                        + firstName + "'])",
                resultDocument, XPathConstants.NUMBER)).intValue());
    }
    for (String sid : sids) {
        assertEquals(sidCountMap.get(sid).intValue(), ((Number) xp.evaluate(
                "count(//merge-result-ext:Entity[ext:PersonSearchResult/ext:Person/jxdm:PersonAugmentation/jxdm:PersonStateFingerprintIdentification/nc:IdentificationID='"
                        + sid + "'])",
                resultDocument, XPathConstants.NUMBER)).intValue());
    }

    String recordLimitExceeded = xp.evaluate(
            "/merge-result:EntityMergeResultMessage/merge-result:RecordLimitExceededIndicator", resultDocument);
    assertEquals("false", recordLimitExceeded);

}

From source file:module.signature.util.XAdESValidator.java

/**
 * @author joao.antunes@tagus.ist.utl.pt adapted it from {@link #validateXMLSignature(String)}
 * @param streamWithSignature//from   ww  w  .  j av a2  s. c o m
 *            the {@link InputStream} that has the signature content
 * @return true if it's valid, false otherwise
 */
public boolean validateXMLSignature(InputStream streamWithSignature) {
    try {

        // get the  xsd schema

        Validator validator = schemaXSD.newValidator();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder parser = dbf.newDocumentBuilder();

        ErrorHandler eh = new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                throw new UnsupportedOperationException("Not supported yet.", exception);
            }
        };

        // parse the document
        parser.setErrorHandler(eh);
        Document document = parser.parse(streamWithSignature);

        // XAdES extension
        NodeList nlObject = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Object");
        // XMLDSIG
        NodeList nlSignature = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#",
                "Signature");

        if (checkSchema) {
            if (nlObject.getLength() < 1) {
                return false;
            }
            if (nlSignature.getLength() < 1) {
                return false;
            }

            // parse the XML DOM tree againts the XSD schema
            validator.validate(new DOMSource(nlSignature.item(0)));
        }

        if (checkSignature) {
            // Validate Every Signature Element (including CounterSignatures)
            for (int i = 0; i < nlSignature.getLength(); i++) {

                Element signature = (Element) nlSignature.item(i);
                //          String baseURI = fileToValidate.toURL().toString();
                XMLSignature xmlSig = new XMLSignature(signature, null);

                KeyInfo ki = xmlSig.getKeyInfo();

                // If signature contains X509Data
                if (ki.containsX509Data()) {

                    NodeList nlSigningTime = signature.getElementsByTagNameNS(xadesNS, "SigningTime");
                    Date signingDate = null;

                    if (nlSigningTime.item(0) != null) {
                        StringBuilder xmlDate = new StringBuilder(nlSigningTime.item(0).getTextContent())
                                .deleteCharAt(22);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                        signingDate = simpleDateFormat.parse(xmlDate.toString());
                    }

                    //verificao OCSP
                    //TODO FENIX-189 joantune: na realidade acho que isto no verifica mesmo a revocao.. a no ser que a keystore indicada seja actualizada regularmente.
                    if (checkRevocation) {
                        //keystore certs cc, raiz estado

                        Security.setProperty("ocsp.enable", "true");
                        //System.setProperty("com.sun.security.enableCRLDP", "true");

                        CertificateFactory cf = CertificateFactory.getInstance("X.509");

                        CertPath certPath = cf
                                .generateCertPath(Collections.singletonList(ki.getX509Certificate()));
                        //             TrustAnchor trustA = new TrustAnchor(ki.getX509Certificate(), null);
                        //             Set trustAnchors = Collections.singleton(trustA);

                        PKIXParameters params = new PKIXParameters(cartaoCidadaoKeyStore);
                        params.setRevocationEnabled(true);

                        // validar o estado na data da assinatura
                        if (nlSigningTime.item(0) != null) {
                            params.setDate(signingDate);
                        }

                        try {
                            CertPathValidator cpValidator = CertPathValidator.getInstance("PKIX");
                            CertPathValidatorResult result = cpValidator.validate(certPath, params);
                            //TODO FENIX-196 probably one would want to send a notification here
                        } catch (CertPathValidatorException ex) {
                            return false;
                        } catch (InvalidAlgorithmParameterException ex) {
                            return false;
                        }
                    }

                    // verifica a validade do certificado no momento da assinatura
                    if (checkValidity) {

                        if (nlSigningTime.item(0) != null) { // continue if there is no SigningTime, if CounterSignature isn't XAdES
                            try {
                                ki.getX509Certificate().checkValidity(signingDate);
                            } catch (CertificateExpiredException ex) {
                                return false;
                            } catch (CertificateNotYetValidException ex) {
                                return false;
                            }
                        }
                    }

                    // validate against Certificate Public Key
                    boolean validSignature = xmlSig.checkSignatureValue(ki.getX509Certificate().getPublicKey());

                    if (!validSignature) {
                        return false;
                    }
                }

                // if signature includes KeyInfo KeyValue, also check against it
                if (ki.containsKeyValue()) {
                    boolean validSignature = xmlSig.checkSignatureValue(ki.getPublicKey());
                    if (!validSignature) {
                        return false;
                    }
                }

                //let's check the SignatureTimeStamp(s) joantune

                NodeList signatureTimeStamps = signature.getElementsByTagNameNS("*", "SignatureTimeStamp");
                Element signatureValue = null;
                if (signatureTimeStamps.getLength() > 0) {
                    signatureValue = (Element) signature.getElementsByTagNameNS("*", "SignatureValue").item(0);
                }
                for (int j = 0; j < signatureTimeStamps.getLength(); j++) {
                    logger.debug("Found a SignatureTimeStamp");
                    Element signatureTimeStamp = (Element) signatureTimeStamps.item(j);
                    //for now we are ignoring the XMLTimeStamp element, let's iterate through all of the EncapsulatedTimeStamp that we find
                    NodeList encapsulatedTimeStamps = signatureTimeStamp.getElementsByTagNameNS("*",
                            "EncapsulatedTimeStamp");
                    for (int k = 0; k < encapsulatedTimeStamps.getLength(); k++) {
                        logger.debug("Found an EncapsulatedTimeStamp");
                        Element encapsulatedTimeStamp = (Element) encapsulatedTimeStamps.item(k);
                        //let's check it
                        // note, we have the timestamptoken, not the whole response, that is, we don't have the status field

                        ASN1Sequence signedTimeStampToken = ASN1Sequence
                                .getInstance(Base64.decode(encapsulatedTimeStamp.getTextContent()));

                        CMSSignedData cmsSignedData = new CMSSignedData(
                                Base64.decode(encapsulatedTimeStamp.getTextContent()));

                        TimeStampToken timeStampToken = new TimeStampToken(cmsSignedData);

                        //let's construct the Request to make sure this is a valid response

                        //let's generate the digest
                        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
                        byte[] digest = sha1.digest(signatureValue.getTextContent().getBytes("UTF-8"));

                        //let's make sure the digests are the same
                        if (!Arrays.equals(digest,
                                timeStampToken.getTimeStampInfo().getMessageImprintDigest())) {
                            //TODO probably want to send an e-mail if this happens, as it's clearly a sign of tampering
                            //FENIX-196
                            logger.debug("Found a different digest in the timestamp!");
                            return false;
                        }

                        try {
                            //TODO for now we won't use the provided certificates that came with the TST
                            //            X509Store certificateStore = (X509Store) timeStampToken.getCertificates();
                            //            JcaDigestCalculatorProviderBuilder builder = new JcaDigestCalculatorProviderBuilder();
                            //            timeStampToken.validate(tsaCert, "BC");
                            //            timeStampToken.validate(new SignerInformationVerifier(new JcaContentVerifierProviderBuilder()
                            //               .build(tsaCert), builder.build()));
                            timeStampToken.validate(new SignerInformationVerifier(
                                    new JcaContentVerifierProviderBuilder().build(tsaCert),
                                    new BcDigestCalculatorProvider()));
                            //let's just verify that the timestamp was done in the past :) - let's give a tolerance of 5 mins :)
                            Date currentDatePlus5Minutes = new Date();
                            //let's make it go 5 minutes ahead
                            currentDatePlus5Minutes.setMinutes(currentDatePlus5Minutes.getMinutes() + 5);
                            if (!timeStampToken.getTimeStampInfo().getGenTime()
                                    .before(currentDatePlus5Minutes)) {
                                //FENIX-196 probably we want to log this!
                                //what the heck, timestamp is done in the future!! (clocks might be out of sync)
                                logger.warn("Found a timestamp in the future!");
                                return false;
                            }
                            logger.debug("Found a valid TimeStamp!");
                            //as we have no other timestamp elements in this signature, this means all is ok! :) 
                            //(point 5) of g.2.2.16.1.3 on the specs

                        } catch (TSPException exception) {
                            logger.debug("TimeStamp response did not validate", exception);
                            return false;
                        }

                    }
                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (SAXException ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (Exception ex) {
        Logger.getLogger(XAdESValidator.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
    return true;
}