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:net.di2e.ecdr.search.transform.atom.security.impl.XmlMetadataSecurityMarkingHandler.java

@Override
public SecurityData getSecurityData(Metacard metacard) {
    String metadata = metacard.getMetadata();
    if (StringUtils.isNotBlank(metadata)) {
        XPathHelper helper = new XPathHelper(metacard.getMetadata());
        Document document = helper.getDocument();
        NodeList nodeList = document.getElementsByTagNameNS("*", "security");
        if (nodeList != null && nodeList.getLength() > 0) {
            Element element = (Element) nodeList.item(0);
            NamedNodeMap nodeNameMap = element.getAttributes();
            int length = nodeNameMap.getLength();

            Map<String, List<String>> securityProps = new HashMap<String, List<String>>();
            String securityNamespace = null;
            for (int i = 0; i < length; i++) {
                Attr attr = (Attr) nodeNameMap.item(i);
                String value = attr.getValue();
                if (!attr.getName().startsWith(XMLNS_PREFIX) && StringUtils.isNotBlank(value)) {
                    securityProps.put(attr.getLocalName(), SecurityMarkingParser.getValues(value));
                    if (securityNamespace == null) {
                        securityNamespace = attr.getNamespaceURI();
                    }/*  ww  w . j ava  2s .  c  o  m*/
                }
            }
            if (!securityProps.isEmpty()) {
                return new SecurityDataImpl(securityProps, securityNamespace);
            }
        }
    }
    return null;
}

From source file:marytts.tests.junit4.EnvironmentTest.java

@Test
public void testXMLParserSupportsNamespaces() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//w  w  w  .  j  a v a 2s .  c om
    DocumentBuilder docBuilder = factory.newDocumentBuilder();
    Document document = docBuilder.parse(this.getClass().getResourceAsStream("test1.namespaces"));
    NodeList nl = document.getElementsByTagNameNS("http://www.w3.org/2001/10/synthesis", "*");
    assertNotNull(nl.item(0));
    assertTrue(nl.item(0).getNodeName().equals("ssml:emphasis"));
}

From source file:cz.muni.fi.mir.mathmlunificator.AbstractXMLTransformationTest.java

protected boolean isMathMLElementsDOMEqual(Document templateDoc, Document testedDoc) {
    return isDOMEqual(templateDoc, testedDoc) && (templateDoc
            .getElementsByTagNameNS(Constants.MATHML_NS, Constants.MATHML_ROOT_ELEM).getLength() == testedDoc
                    .getElementsByTagNameNS(Constants.MATHML_NS, Constants.MATHML_ROOT_ELEM).getLength());
}

From source file:com.cloud.bridge.auth.ec2.AuthenticationHandler.java

/**
 * For EC2 SOAP calls this function's goal is to extract the X509 certificate that is
 * part of the WS-Security wrapped SOAP request.   We need the cert in order to 
 * map it to the user's Cloud API key and Cloud Secret Key.
 *//*w w w . j a  va  2 s  .  c om*/
public InvocationResponse invoke(MessageContext msgContext) throws AxisFault {
    // -> the certificate we want is embedded into the soap header
    try {
        SOAPEnvelope soapEnvelope = msgContext.getEnvelope();
        String xmlHeader = soapEnvelope.toString();
        //System.out.println( "entire request: " + xmlHeader );

        InputStream is = new ByteArrayInputStream(xmlHeader.getBytes("UTF-8"));
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document request = db.parse(is);
        NodeList certs = request.getElementsByTagNameNS(
                "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                "BinarySecurityToken");
        if (0 < certs.getLength()) {
            Node item = certs.item(0);
            String result = new String(item.getFirstChild().getNodeValue());
            byte[] certBytes = Base64.decodeBase64(result.getBytes());

            Certificate userCert = null;
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            ByteArrayInputStream bs = new ByteArrayInputStream(certBytes);
            while (bs.available() > 0)
                userCert = cf.generateCertificate(bs);
            //System.out.println( "cert: " + userCert.toString());              
            String uniqueId = AuthenticationUtils.X509CertUniqueId(userCert);
            logger.debug("X509 cert's uniqueId: " + uniqueId);

            // -> find the Cloud API key and the secret key from the cert's uniqueId 
            /*               UserCredentialsDao credentialDao = new UserCredentialsDao();
                           UserCredentials cloudKeys = credentialDao.getByCertUniqueId( uniqueId );
            */
            UserCredentialsVO cloudKeys = ucDao.getByCertUniqueId(uniqueId);
            if (null == cloudKeys) {
                logger.error("Cert does not map to Cloud API keys: " + uniqueId);
                throw new AxisFault("User not properly registered: Certificate does not map to Cloud API Keys",
                        "Client.Blocked");
            } else
                UserContext.current().initContext(cloudKeys.getAccessKey(), cloudKeys.getSecretKey(),
                        cloudKeys.getAccessKey(), "SOAP Request", null);
            //System.out.println( "end of cert match: " + UserContext.current().getSecretKey());
        }
    } catch (AxisFault e) {
        throw e;
    } catch (Exception e) {
        logger.error("EC2 Authentication Handler: ", e);
        throw new AxisFault("An unknown error occurred.", "Server.InternalError");
    }
    return InvocationResponse.CONTINUE;
}

From source file:be.fedict.eid.pkira.xkmsws.util.XMLMarshallingUtil.java

public void removeSoapHeaders(Document document) {
    NodeList bodyNodes = document.getElementsByTagNameNS(NAMESPACE_SOAP, "Body");
    if (bodyNodes != null && bodyNodes.getLength() == 1) {
        Element body = (Element) bodyNodes.item(0);

        NodeList children = body.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            if (children.item(i) instanceof Element) {
                document.removeChild(document.getDocumentElement());
                document.appendChild(children.item(i));
                break;
            }/* w  w w.j  av  a 2  s  . com*/
        }
    }
}

From source file:ee.ria.xroad.proxy.serverproxy.ProxyMonitorServiceHandlerImpl.java

/**
 * Read requested monitoring parameter names from SOAP body. Returns empty list if no explicit metric names defined.
 *
 * @param proxyRequestMessage/*from  w ww . j  ava2 s .co  m*/
 * @return
 */
private List<String> getMetricNames(ProxyMessage proxyRequestMessage) throws Exception {
    List<String> metricNames = new ArrayList<>();

    Document doc = parse(proxyRequestMessage);
    NodeList nl = doc.getElementsByTagNameNS(NS_MONITORING, MONITOR_REQ_PARAM_NODE_NAME);

    for (int i = 0; i < nl.getLength(); i++) {
        metricNames.add(nl.item(i).getFirstChild().getNodeValue());
    }
    return metricNames;
}

From source file:eu.europa.esig.dss.xades.signature.EnvelopedSignatureBuilder.java

/**
 * Bob --> This method is not used anymore, but it can replace {@code NOT_ANCESTOR_OR_SELF_DS_SIGNATURE} transformation. Performance test should be performed!
 * In case of the enveloped signature the existing signatures are removed.
 *
 * @param domDoc {@code Document} containing the signatures to analyse
 *///from   w  w  w. j  a v a2 s.  c  o  m
protected void removeExistingSignatures(final Document domDoc) {

    final NodeList signatureNodeList = domDoc.getElementsByTagNameNS(XMLSignature.XMLNS,
            XPathQueryHolder.XMLE_SIGNATURE);
    for (int ii = signatureNodeList.getLength() - 1; ii >= 0; ii--) {
        final Element signatureDOM = (Element) signatureNodeList.item(ii);
        signatureDOM.getParentNode().removeChild(signatureDOM);
    }
}

From source file:esg.security.yadis.XrdsDoc.java

protected Map extractElementsByParent(String ns, String elem, Set parents, Document document) {
    Map result = new HashMap();
    NodeList nodes = document.getElementsByTagNameNS(ns, elem);
    Node node;//from  w w w.  j  a v a  2s .c o  m
    for (int i = 0; i < nodes.getLength(); i++) {
        node = nodes.item(i);
        if (node == null || !parents.contains(node.getParentNode()))
            continue;

        String localId = node.getFirstChild() != null && node.getFirstChild().getNodeType() == Node.TEXT_NODE
                ? node.getFirstChild().getNodeValue()
                : null;

        result.put(node.getParentNode(), localId);
    }
    return result;
}

From source file:be.fedict.eid.dss.document.odf.ODFDSSDocumentService.java

@Override
public List<SignatureInfo> verifySignatures(byte[] document, byte[] originalDocument) throws Exception {
    List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>();
    ZipInputStream odfZipInputStream = new ZipInputStream(new ByteArrayInputStream(document));
    ZipEntry zipEntry;/*from  w w  w. java2  s.co m*/
    while (null != (zipEntry = odfZipInputStream.getNextEntry())) {
        if (ODFUtil.isSignatureFile(zipEntry)) {
            Document documentSignatures = ODFUtil.loadDocument(odfZipInputStream);
            NodeList signatureNodeList = documentSignatures.getElementsByTagNameNS(XMLSignature.XMLNS,
                    "Signature");

            XAdESValidation xadesValidation = new XAdESValidation(this.documentContext);

            for (int idx = 0; idx < signatureNodeList.getLength(); idx++) {
                Element signatureElement = (Element) signatureNodeList.item(idx);

                //LOG.debug("signatureValue: "+signatureElement.getTextContent());

                xadesValidation.prepareDocument(signatureElement);
                KeyInfoKeySelector keySelector = new KeyInfoKeySelector();
                DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement);
                ODFURIDereferencer dereferencer = new ODFURIDereferencer(document);
                domValidateContext.setURIDereferencer(dereferencer);

                XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
                XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
                boolean valid = xmlSignature.validate(domValidateContext);
                if (!valid) {
                    LOG.debug("invalid signature");
                    continue;
                }

                checkIntegrity(xmlSignature, document, originalDocument);

                X509Certificate signingCertificate = keySelector.getCertificate();
                SignatureInfo signatureInfo = xadesValidation.validate(documentSignatures, xmlSignature,
                        signatureElement, signingCertificate);
                signatureInfos.add(signatureInfo);
            }
            return signatureInfos;
        }
    }
    return signatureInfos;
}

From source file:de.hsos.ecs.richwps.wpsmonitor.communication.wpsclient.defaultimpl.SimpleWpsClient.java

private Boolean isWpsException(final String responseBody) throws NoWpsResponse {
    try {/*from   w  w w . java2s. c  o m*/
        Document doc = getDocumentBuilder().parse(new InputSource(new StringReader(responseBody)));
        NodeList nl = doc.getElementsByTagNameNS("*", "ExceptionText");

        if (nl.getLength() > 0) {
            StringBuilder strBuilder = new StringBuilder();

            for (int i = 0; i < nl.getLength(); i++) {
                strBuilder.append(nl.item(i).getTextContent());
                strBuilder.append("\n----\n");
            }

            wpsExceptionMessage = strBuilder.toString();

            return true;
        } else {
            return false;
        }
    } catch (SAXException ex) {
        LOG.debug("SAX Exception occourd at parse WPS Response.", ex);
    } catch (IOException ex) {
        LOG.debug("I/O Exception occourd at parse WPS Response.", ex);
    } catch (ParserConfigurationException ex) {
        LOG.debug("Parse Exception occourd at parse WPS Response.", ex);
    } catch (DOMException ex) {
        LOG.debug("DOM Exception occourd at parse WPS Response.", ex);
    }

    LOG.debug("Exception occured while parsing the WpsResponse body. Interpreting as ConnectionError.");
    throw new NoWpsResponse();
}