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.roda.common.certification.ODFSignatureUtils.java

public static String runDigitalSignatureVerify(Path input) throws IOException, GeneralSecurityException {
    String result = "Passed";
    ZipFile zipFile = new ZipFile(input.toString());
    Enumeration<?> enumeration;
    for (enumeration = zipFile.entries(); enumeration.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) enumeration.nextElement();
        String entryName = entry.getName();
        if (META_INF_DOCUMENTSIGNATURES_XML.equalsIgnoreCase(entryName)) {
            InputStream zipStream = zipFile.getInputStream(entry);
            InputSource inputSource = new InputSource(zipStream);
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            try {
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document document = documentBuilder.parse(inputSource);
                NodeList signatureNodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
                for (int i = 0; i < signatureNodeList.getLength(); i++) {
                    Node signatureNode = signatureNodeList.item(i);
                    verifyCertificates(input, signatureNode);
                }/*from   w w w  .  ja v  a2  s  .  c om*/
            } catch (ParserConfigurationException | SAXException e) {
                result = "Signatures document can not be parsed";
            } catch (CertificateExpiredException e) {
                result = "Contains expired certificates";
            } catch (CertificateRevokedException e) {
                result = "Contains revoked certificates";
            } catch (CertificateNotYetValidException e) {
                result = "Contains certificates not yet valid";
            } catch (MarshalException | XMLSignatureException e) {
                result = "Digital signatures are not valid";
            }

            IOUtils.closeQuietly(zipStream);
        }
    }

    zipFile.close();
    return result;
}

From source file:org.roda.core.plugins.plugins.characterization.ODFSignatureUtils.java

public static String runDigitalSignatureVerify(Path input) throws IOException {
    String result = "Passed";
    try (ZipFile zipFile = new ZipFile(input.toString())) {
        ZipEntry documentSignatureEntry = null;
        Enumeration<?> enumeration;

        for (enumeration = zipFile.entries(); enumeration.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) enumeration.nextElement();
            if (META_INF_DOCUMENTSIGNATURES_XML.equalsIgnoreCase(entry.getName())) {
                documentSignatureEntry = entry;
                break;
            }//w  w w  .j av  a2  s  .co  m
        }

        if (documentSignatureEntry != null) {
            try (InputStream zipStream = zipFile.getInputStream(documentSignatureEntry)) {
                InputSource inputSource = new InputSource(zipStream);
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document document = documentBuilder.parse(inputSource);
                NodeList signatureNodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");

                for (int i = 0; i < signatureNodeList.getLength(); i++) {
                    Node signatureNode = signatureNodeList.item(i);
                    verifyCertificates(signatureNode);
                }
            } catch (ParserConfigurationException | SAXException e) {
                result = "Signatures document can not be parsed";
            } catch (CertificateExpiredException e) {
                result = "Contains expired certificates";
            } catch (CertificateRevokedException e) {
                result = "Contains revoked certificates";
            } catch (CertificateNotYetValidException e) {
                result = "Contains certificates not yet valid";
            } catch (MarshalException | XMLSignatureException e) {
                result = "Digital signatures are not valid";
            } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException e) {
                result = "Could not verify certificates";
            }
        } else {
            result = "Could not find " + META_INF_DOCUMENTSIGNATURES_XML;
        }

    }

    return result;

}

From source file:org.springframework.data.hadoop.admin.util.HadoopWorkflowDescriptorUtils.java

/**
 * replace the "property-placeholder" element in beans XML with absolute path 
 * where the uploaded file exist in the server.
 *  /*w w  w  .  j  a  va2  s  . c  om*/
 * @param workflowDescriptor spring's XML file
 * @param workflowProperty properties used in spring's XML file
 * 
 * @return whether "property-placeholder" appears in the beans XML. 
 *          true - it appears
 *          false - no
 * 
 * @throws SpringHadoopAdminWorkflowException
 */
public boolean replacePropertyPlaceHolder(File workflowDescriptor, File workflowProperty)
        throws SpringHadoopAdminWorkflowException {
    boolean result = false;
    String parentFolder = workflowDescriptor.getParentFile().getAbsolutePath();
    parentFolder = parentFolder + File.separator;
    try {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(workflowDescriptor));
        InputSource inputSource = new InputSource(bis);
        Document doc = this.documentLoader.loadDocument(inputSource, getEntityResolver(), this.errorHandler,
                XmlValidationModeDetector.VALIDATION_NONE, true);
        NodeList nodes = doc.getElementsByTagNameNS(springContextNameSpace, placePlaceHolderTagName);
        logger.debug("number of nodes:" + nodes.getLength());
        for (int i = 0, j = nodes.getLength(); i < j; i++) {
            Node node = nodes.item(i);
            if (node instanceof Element) {
                Element e = (Element) node;
                String newValue = workflowProperty.getAbsolutePath().replace("\\", "/");
                newValue = HadoopWorkflowUtils.fileURLPrefix + newValue;
                e.setAttribute("location", newValue);
                result = true;
                logger.debug("new location after replaced:" + newValue);
            }
        }
        if (result) {
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult out = new StreamResult(new File(workflowDescriptor.getAbsolutePath()));
            transformer.transform(source, out);
        }
    } catch (Exception e) {
        logger.warn(replacePropertyPlaceHolderFaiure);
        throw new SpringHadoopAdminWorkflowException(replacePropertyPlaceHolderFaiure, e);
    }
    return result;
}

From source file:org.wso2.carbon.discovery.cxf.listeners.TomcatCxfDiscoveryListener.java

/**
 * Get JAX-WS service info needed to send the WS-Discovery message
 * TODO: Read the service class from cxf-servlet.xml instead of traversing all the classes
 * for @WebService annotation./*from w  w  w  . j a  v a  2  s. c o m*/
 */
private CXFServiceInfo getServiceInfo(StandardContext context, String jaxServletMapping)
        throws DiscoveryException {
    CXFServiceInfo serviceInfo = new CXFServiceInfo();
    String contextPath = context.getServletContext().getContextPath();
    contextPath = contextPath.startsWith("/") ? contextPath.substring(1, contextPath.length()) : contextPath;

    serviceInfo.setServiceName(contextPath);
    serviceInfo.setType(getPortType(context));
    serviceInfo.setTenantDomain(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true));

    List<String> endpoints = new ArrayList<String>(5);
    try {
        InputStream configStream = getConfigLocation(context.getServletContext());
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder b = dbf.newDocumentBuilder();
        org.w3c.dom.Document doc = b.parse(configStream); //doc.getDomConfig().setParameter();

        NodeList endpointElements = doc.getElementsByTagNameNS("http://cxf.apache.org/jaxws", "endpoint");
        NodeList serverElements = doc.getElementsByTagNameNS("http://cxf.apache.org/jaxws", "server");

        for (int i = 0; i < endpointElements.getLength(); i++) {
            Node node = endpointElements.item(i);
            if (node instanceof Element) {
                Element endpointElement = (Element) node;
                String cxfEndpoint = endpointElement.getAttribute("address");
                endpoints.add(cxfEndpoint);
            }
        }

        for (int i = 0; i < serverElements.getLength(); i++) {
            Node node = serverElements.item(i);
            if (node instanceof Element) {
                Element serverElement = (Element) node;
                String cxfEndpoint = serverElement.getAttribute("address");
                endpoints.add(cxfEndpoint);
            }
        }
    } catch (ParserConfigurationException e) {
        log.error("Error processing CXF config file of " + contextPath, e);
    } catch (SAXException e) {
        log.error("Error processing CXF config file of " + contextPath, e);
    } catch (IOException e) {
        log.error("Error processing CXF config file of " + contextPath, e);
    }

    if (endpoints.isEmpty()) {
        return null;
    }

    serviceInfo.setWsdlURI(getWsdlUri(context, jaxServletMapping, endpoints));
    serviceInfo.setxAddrs(getxAddrs(context, jaxServletMapping, endpoints));

    return serviceInfo;

}

From source file:org.wso2.carbon.repository.core.config.RepositoryConfiguration.java

/**
 * Initialize the repository configuration with carbon.xml provided the carbon.xml path as
 * an argument./*from w ww.  j  av a 2 s . co  m*/
 *
 * @param carbonXMLPath the path of the carbon.xml
 *
 * @throws RepositoryException throws if the construction failed
 */
public RepositoryConfiguration(String carbonXMLPath) throws RepositoryException {
    try {
        File carbonXML = new File(carbonXMLPath);

        String carbonXMLNS = "http://wso2.org/projects/carbon/carbon.xml";

        DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
        Document doc = documentBuilder.parse(carbonXML);

        doc.getDocumentElement().normalize();
        NodeList nodeList = doc.getElementsByTagNameNS(carbonXMLNS, REGISTRY_CONFIG);

        int numberOfElements;
        if ((numberOfElements = nodeList.getLength()) > 0) {
            if (numberOfElements == 1) {
                Node node = nodeList.item(0);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    registryConfiguration.put(element.getNodeName(), element.getNodeValue());
                }
            } else {
                throw new RepositoryConfigurationException(
                        "Only one registry element should exist in carbon.xml");
            }
        }

        if (registryConfiguration.get(TYPE) == null) {
            registryConfiguration.put(TYPE, EMBEDDED_REGISTRY);
        }

        validate();
    } catch (Exception e) {
        throw new RepositoryConfigurationException("Error occurred while initialization on reading carbon.xml",
                e);
    }
}

From source file:oscar.oscarLab.ca.all.upload.handlers.IHAHandler.java

@Override
public String parse(String serviceName, String fileName, int fileId) {
    Document xmlDoc = getXML(fileName);
    Node node;/*w ww .j ava2  s.  co  m*/
    Element element;
    NamedNodeMap nnm = null;
    String msgId = null;
    String result = null;

    if (xmlDoc != null) {
        String hl7Body = null;
        String attrName = null;
        try {
            msgId = null;
            NodeList allNodes = xmlDoc.getElementsByTagNameNS("*", "*");
            for (int i = 1; i < allNodes.getLength(); i++) {
                try {
                    element = (Element) allNodes.item(i);
                    nnm = element.getAttributes();
                    if (nnm != null) {
                        for (int j = 0; j < nnm.getLength(); j++) {
                            node = nnm.item(j);
                            attrName = node.getNodeName();
                            if (attrName.equals("msgId")) {
                                msgId = node.getNodeValue();
                            }
                        }
                    }
                    hl7Body = allNodes.item(i).getFirstChild().getTextContent();
                    if (hl7Body != null && hl7Body.indexOf("\nPID|") > 0) {
                        logger.info("using xml HL7 Type " + getHl7Type());
                        MessageUploader.routeReport(serviceName, "IHA", hl7Body, fileId);
                        result += "success:" + msgId + ",";
                    }
                } catch (Exception e) {
                    result += "fail:" + msgId + ",";
                }
            }
        } catch (Exception e) {
            MessageUploader.clean(fileId);
            logger.error("ERROR:", e);
            return null;
        }
    }
    return (result);
}

From source file:pl.psnc.ep.rt.web.servlets.CollXMLServlet.java

private static Date findDate(Date best, SimpleDateFormat df, Document module, String tag, boolean latest) {
    if (module == null)
        return best;
    NodeList createdList = module.getElementsByTagNameNS(Namespace.MD.URI, tag);
    for (int j = 0; j < createdList.getLength(); j++) {
        String dateText = createdList.item(j).getTextContent();
        Date date;//w  w w .j a  v a 2s  .  c  o  m
        try {
            date = df.parse(dateText);
        } catch (ParseException e) {
            logger.warn("Could not parse date in file version (" + dateText + ")");
            continue;
        }
        if (best == null || (latest ? date.after(best) : date.before(best)))
            best = date;
    }
    return best;
}

From source file:ru.codeinside.gws.crypto.cryptopro.CryptoProvider.java

@Override
public String signElement(String sourceXML, String elementName, String namespace, boolean removeIdAttribute,
        boolean signatureAfterElement, boolean inclusive) throws Exception {
    loadCertificate();//from  w w  w.  j  av  a 2 s  . co m
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setCoalescing(true);
    dbf.setNamespaceAware(true);
    DocumentBuilder documentBuilder = dbf.newDocumentBuilder();

    InputSource is = new InputSource(new StringReader(sourceXML));
    Document doc = documentBuilder.parse(is);
    Element elementForSign = (Element) doc.getElementsByTagNameNS(namespace, elementName).item(0);

    Node parentNode = null;
    Element detachedElementForSign;
    Document detachedDocument;
    if (!elementForSign.isSameNode(doc.getDocumentElement())) {
        parentNode = elementForSign.getParentNode();
        parentNode.removeChild(elementForSign);

        detachedDocument = documentBuilder.newDocument();
        Node importedElementForSign = detachedDocument.importNode(elementForSign, true);
        detachedDocument.appendChild(importedElementForSign);
        detachedElementForSign = detachedDocument.getDocumentElement();
    } else {
        detachedElementForSign = elementForSign;
        detachedDocument = doc;
    }

    String signatureMethodUri = inclusive ? "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34102001-gostr3411"
            : "http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411";
    String canonicalizationMethodUri = inclusive ? "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
            : "http://www.w3.org/2001/10/xml-exc-c14n#";
    XMLSignature sig = new XMLSignature(detachedDocument, "", signatureMethodUri, canonicalizationMethodUri);
    if (!removeIdAttribute) {
        detachedElementForSign.setAttribute("Id", detachedElementForSign.getTagName());
    }
    if (signatureAfterElement)
        detachedElementForSign.insertBefore(sig.getElement(),
                detachedElementForSign.getLastChild().getNextSibling());
    else {
        detachedElementForSign.insertBefore(sig.getElement(), detachedElementForSign.getFirstChild());
    }
    Transforms transforms = new Transforms(detachedDocument);
    transforms.addTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature");
    transforms.addTransform(inclusive ? "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"
            : "http://www.w3.org/2001/10/xml-exc-c14n#");

    String digestURI = inclusive ? "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr3411"
            : "http://www.w3.org/2001/04/xmldsig-more#gostr3411";
    sig.addDocument(removeIdAttribute ? "" : "#" + detachedElementForSign.getTagName(), transforms, digestURI);
    sig.addKeyInfo(cert);
    sig.sign(privateKey);

    if ((!elementForSign.isSameNode(doc.getDocumentElement())) && (parentNode != null)) {
        Node signedNode = doc.importNode(detachedElementForSign, true);
        parentNode.appendChild(signedNode);
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer trans = tf.newTransformer();
    trans.setOutputProperty("omit-xml-declaration", "yes");
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    trans.transform(new DOMSource(doc), streamResult);
    return stringWriter.toString();
}

From source file:ru.codeinside.gws3572c.GMPClientSignTest.java

@Test
public void testSignForEntity() throws Exception {
    ClientRequest request = client.createClientRequest(createContext());
    InputSource is = new InputSource(new StringReader(request.appData));
    Document doc = documentBuilder.parse(is);

    Element elementForSign = (Element) doc.getElementsByTagNameNS(null, "Charge").item(0);

    Node parentNode;/*ww w  .  j ava  2  s .  co  m*/
    Document detachedDocument;
    if (!elementForSign.isSameNode(doc.getDocumentElement())) {
        parentNode = elementForSign.getParentNode();
        parentNode.removeChild(elementForSign);

        detachedDocument = documentBuilder.newDocument();
        Node importedElementForSign = detachedDocument.importNode(elementForSign, true);
        detachedDocument.appendChild(importedElementForSign);
    } else {
        detachedDocument = doc;
    }

    Element nscontext = detachedDocument.createElementNS(null, "namespaceContext");
    nscontext.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + "ds".trim(),
            "http://www.w3.org/2000/09/xmldsig#");

    Element certificateElement = (Element) XPathAPI.selectSingleNode(detachedDocument,
            "//ds:X509Certificate[1]", nscontext);
    Element sigElement = (Element) certificateElement.getParentNode().getParentNode().getParentNode();

    XMLSignature signature = new XMLSignature(sigElement, "");

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate certKey = (X509Certificate) cf.generateCertificate(
            new ByteArrayInputStream(Base64.decode(certificateElement.getTextContent().trim().getBytes())));

    Assert.assertNotNull("There are no information about public key. Verification couldn't be implemented",
            certKey);
    Assert.assertTrue("Signature is not valid", signature.checkSignatureValue(certKey));
}

From source file:test.be.fedict.eid.applet.model.XmlSignatureServiceBean.java

public void postSign(byte[] signatureValue, List<X509Certificate> signingCertificateChain) {
    LOG.debug("postSign");

    HttpServletRequest httpServletRequest;
    try {/*  www  . j  av a 2  s.c  o  m*/
        httpServletRequest = (HttpServletRequest) PolicyContext
                .getContext("javax.servlet.http.HttpServletRequest");
    } catch (PolicyContextException e) {
        throw new RuntimeException("JACC error: " + e.getMessage());
    }

    HttpSession session = httpServletRequest.getSession();
    String documentStr = (String) session.getAttribute("xmlDocument");

    Document document;
    try {
        document = getDocument(documentStr);
    } catch (Exception e) {
        throw new RuntimeException("DOM error: " + e.getMessage(), e);
    }

    // insert signature value
    NodeList signatureValueNodeList = document.getElementsByTagNameNS(javax.xml.crypto.dsig.XMLSignature.XMLNS,
            "SignatureValue");
    Element signatureValueElement = (Element) signatureValueNodeList.item(0);
    signatureValueElement.setTextContent(Base64.encode(signatureValue));

    try {
        documentStr = toString(document);
    } catch (Exception e) {
        throw new RuntimeException("DOM error: " + e.getMessage(), e);
    }

    session.setAttribute("xmlDocument", documentStr);
}