Example usage for org.w3c.dom Element getElementsByTagNameNS

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

Introduction

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

Prototype

public NodeList getElementsByTagNameNS(String namespaceURI, String localName) throws DOMException;

Source Link

Document

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

Usage

From source file:it.pronetics.madstore.repository.jcr.impl.AbstractJcrRepository.java

protected final void postProcessEntryImport(Element entryElement, Node collectionContainerNode,
        Node entryContainerNode, Node entryNode) {
    try {//from  ww w. j  ava  2s . c o  m
        entryContainerNode.addMixin(MIX_REFERENCEABLE);
        entryContainerNode.setProperty(COLLECTION_REF, collectionContainerNode);
        org.w3c.dom.NodeList nodes = entryElement.getElementsByTagNameNS(AtomConstants.ATOM_NS,
                AtomConstants.ATOM_ENTRY_UPDATED);
        if (nodes.getLength() == 1) {
            org.w3c.dom.Node updated = nodes.item(0);
            entryNode.setProperty(JCR_LAST_MODIFIED, updated.getTextContent());
        }
    } catch (Exception ex) {
        throw new AtomRepositoryException(ex.getMessage(), ex);
    }
}

From source file:org.springmodules.validation.bean.conf.loader.xml.DefaultXmlBeanValidationConfigurationLoader.java

/**
 * Loads the validation configuration from the given document that was created from the given resource.
 *
 * @see AbstractXmlBeanValidationConfigurationLoader#loadConfigurations(org.w3c.dom.Document, String)
 *///from w ww.j  a  va2s.com
protected Map loadConfigurations(Document document, String resourceName) {
    Map configurations = new HashMap();
    Element validationDefinition = document.getDocumentElement();
    String packageName = validationDefinition.getAttribute(PACKAGE_ATTR);
    NodeList nodes = validationDefinition.getElementsByTagNameNS(DEFAULT_NAMESPACE_URL, CLASS_TAG);
    for (int i = 0; i < nodes.getLength(); i++) {
        Element classDefinition = (Element) nodes.item(i);
        String className = classDefinition.getAttribute(NAME_ATTR);
        className = (StringUtils.hasLength(packageName)) ? packageName + "." + className : className;
        Class clazz;
        try {
            clazz = ClassUtils.forName(className);
        } catch (ClassNotFoundException cnfe) {
            logger.error("Could not load class '" + className + "' as defined in '" + resourceName + "'", cnfe);
            continue;
        }
        configurations.put(clazz, handleClassDefinition(clazz, classDefinition));
    }
    return configurations;
}

From source file:io.fabric8.tooling.archetype.generator.ArchetypeHelper.java

/**
 * Extracts properties declared in "META-INF/maven/archetype-metadata.xml" file
 *
 * @param zip/*from  w ww. ja v a 2s.  c om*/
 * @param replaceProperties
 * @throws IOException
 */
protected void parseReplaceProperties(ZipInputStream zip, Map<String, String> replaceProperties)
        throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    copy(zip, bos);

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

    InputSource inputSource = new InputSource(new ByteArrayInputStream(bos.toByteArray()));
    Document document = db.parse(inputSource);

    XPath xpath = XPathFactory.newInstance().newXPath();
    SimpleNamespaceContext nsContext = new SimpleNamespaceContext();
    nsContext.registerMapping("ad", archetypeDescriptorUri);
    xpath.setNamespaceContext(nsContext);

    NodeList properties = (NodeList) xpath.evaluate(requiredPropertyXPath, document, XPathConstants.NODESET);

    for (int p = 0; p < properties.getLength(); p++) {
        Element requiredProperty = (Element) properties.item(p);

        String key = requiredProperty.getAttribute("key");
        NodeList children = requiredProperty.getElementsByTagNameNS(archetypeDescriptorUri, "defaultValue");
        String value = "";
        if (children.getLength() == 1 && children.item(0).hasChildNodes()) {
            value = children.item(0).getTextContent();
        } else {
            if ("name".equals(key) && value.isEmpty()) {
                value = "HelloWorld";
            }
        }
        replaceProperties.put(key, value);
    }
}

From source file:es.mityc.firmaJava.policy.FacturaeManager.java

/**
 * Comprueba los hashes de la policy del documento de firma
 * @param nodo/* w w  w .j a v a  2s.c  o  m*/
 * @return true si son validos
 */
protected boolean isValidPolicyHash(Element nodoFirma, final ResultadoValidacion rs, ConfigFacturae config) {
    XAdESSchemas schema = rs.getDatosFirma().getEsquema();
    if (schema == null)
        return false;
    String esquema = schema.getSchemaUri();

    // Nodo SignaturePolicyIdentifier
    NodeList signaturePolicyList = nodoFirma.getElementsByTagNameNS(esquema,
            ConstantesXADES.SIGNATURE_POLICY_IDENTIFIER);
    if (signaturePolicyList.getLength() != 1)
        return false;
    if (signaturePolicyList.item(0).getNodeType() != Node.ELEMENT_NODE)
        return false;

    try {
        SignaturePolicyIdentifier signaturePolicyIdentifier = new SignaturePolicyIdentifier(schema);
        if (!signaturePolicyIdentifier.isThisNode(signaturePolicyList.item(0)))
            throw new InvalidInfoNodeException("No se ha encontrado poltica");
        signaturePolicyIdentifier.load((Element) signaturePolicyList.item(0));

        if (signaturePolicyIdentifier.isImplied())
            throw new InvalidInfoNodeException("La poltica encontrada es implcita");

        DigestAlgAndValueType value = getDigestRelated(
                signaturePolicyIdentifier.getSignaturePolicyId().getSigPolicyHash().getMethod().getAlgorithm(),
                config);
        SignaturePolicyIdentifier comp = createPolicy(schema, config, value);

        if (!signaturePolicyIdentifier.equals(comp))
            return false;
    } catch (InvalidInfoNodeException ex) {
        if (logger.isDebugEnabled())
            logger.debug("Error obteniendo digest/value de la policy", ex);
        return false;
    }
    return true;
}

From source file:com.flozano.socialauth.provider.GoogleImpl.java

/**
 * Gets the list of contacts of the user and their email.
 * /*w w w  .  ja  va 2s  .  c o m*/
 * @return List of contact objects representing Contacts. Only name and
 *         email will be available
 * 
 * @throws Exception
 */
@Override
public List<Contact> getContactList() throws Exception {
    LOG.info("Fetching contacts from " + CONTACTS_FEED_URL);
    if (Permission.AUTHENTICATE_ONLY.equals(this.scope)) {
        throw new SocialAuthException("You have not set Permission to get contacts.");
    }
    Response serviceResponse = null;
    try {
        serviceResponse = authenticationStrategy.executeFeed(CONTACTS_FEED_URL);
    } catch (Exception ie) {
        throw new SocialAuthException("Failed to retrieve the contacts from " + CONTACTS_FEED_URL, ie);
    }
    List<Contact> plist = new ArrayList<Contact>();
    Element root;

    try {
        root = XMLParseUtil.loadXmlResource(serviceResponse.getInputStream());
    } catch (Exception e) {
        throw new ServerDataException("Failed to parse the contacts from response." + CONTACTS_FEED_URL, e);
    }
    NodeList contactsList = root.getElementsByTagName("entry");
    if (contactsList != null && contactsList.getLength() > 0) {
        LOG.debug("Found contacts : " + contactsList.getLength());
        for (int i = 0; i < contactsList.getLength(); i++) {
            Element contact = (Element) contactsList.item(i);
            String fname = "";
            NodeList l = contact.getElementsByTagNameNS(CONTACT_NAMESPACE, "email");
            String address = null;
            String emailArr[] = null;
            if (l != null && l.getLength() > 0) {
                Element el = (Element) l.item(0);
                if (el != null) {
                    address = el.getAttribute("address");
                }
                if (l.getLength() > 1) {
                    emailArr = new String[l.getLength() - 1];
                    for (int k = 1; k < l.getLength(); k++) {
                        Element e = (Element) l.item(k);
                        if (e != null) {
                            emailArr[k - 1] = e.getAttribute("address");
                        }
                    }
                }
            }
            String lname = "";
            String dispName = XMLParseUtil.getElementData(contact, "title");
            if (dispName != null) {
                String sarr[] = dispName.split(" ");
                if (sarr.length > 0) {
                    if (sarr.length >= 1) {
                        fname = sarr[0];
                    }
                    if (sarr.length >= 2) {
                        StringBuilder sb = new StringBuilder();
                        for (int k = 1; k < sarr.length; k++) {
                            sb.append(sarr[k]).append(" ");
                        }
                        lname = sb.toString();
                    }
                }
            }
            String id = XMLParseUtil.getElementData(contact, "id");

            if (address != null && address.length() > 0) {
                Contact p = new Contact();
                p.setFirstName(fname);
                p.setLastName(lname);
                p.setEmail(address);
                p.setDisplayName(dispName);
                p.setOtherEmails(emailArr);
                p.setId(id);
                plist.add(p);
            }
        }
    } else {
        LOG.debug("No contacts were obtained from the feed : " + CONTACTS_FEED_URL);
    }
    return plist;
}

From source file:com.nominanuda.springmvc.MvcFrontControllerBeanDefinitionParser.java

protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
    if (plugins == null) {
        try {/*from   ww  w .j a v a2  s .c  o  m*/
            initPlugins(parserContext);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
    BeanDefinitionBuilder bdBuilder = BeanDefinitionBuilder.rootBeanDefinition(HandlerMatcherMapping.class);

    String pattern = ((Element) element.getElementsByTagNameNS(ns, "pattern").item(0)).getTextContent();

    String uriSpec = getUriSpec(pattern);
    BeanDefinitionBuilder matchBuilder = BeanDefinitionBuilder.genericBeanDefinition(URISpecMatcher.class);
    matchBuilder.addPropertyValue("spec", pattern);
    String matchId = uuid();
    parserContext.getRegistry().registerBeanDefinition(matchId, matchBuilder.getBeanDefinition());
    bdBuilder.addPropertyReference("handlerMatcher", matchId);
    String handlerId = generateHandler(element, parserContext, uriSpec);
    matchBuilder.addPropertyReference("handler", handlerId);
    List<BeanMetadataElement> filters = generateFilterList(element, parserContext, uriSpec);
    if (filters != null) {
        matchBuilder.addPropertyValue("handlerFilters", filters);
    }
    AbstractBeanDefinition abd = bdBuilder.getBeanDefinition();
    abd.setAutowireCandidate(false);
    return abd;
}

From source file:com.castlemock.web.mock.soap.model.project.service.CreateSoapPortsService.java

/**
 * The method provides the functionality to extract SOAP operation from a document
 * @param document The document which will be parsed
 * @param soapPortBinding The SOAP port binding which the operations belongs to
 * @param soapOperationAddress The address that will be assigned as the default address to the operations
 * @param soapVersion The SOAP operation version (SOAP 11 or SOAP 12)
 * @param generateResponse Boolean value determining if a response should be generated for each extracted
 *                         operation./* w  w  w .j a va  2  s.c o  m*/
 * @return A list of extracted SOAP operations
 */
private List<SoapOperationDto> getSoapOperations(final Document document, final String soapPortBinding,
        final String soapOperationAddress, final SoapVersion soapVersion, final boolean generateResponse) {
    final List<SoapOperationDto> soapOperations = new LinkedList<SoapOperationDto>();
    final Element bindingElement = findElement(document, WSDL_NAMESPACE, "binding", soapPortBinding);
    if (bindingElement == null) {
        return soapOperations;
    }
    final String bindingType = getAttribute(bindingElement, "type");

    if (bindingType == null) {
        return soapOperations;
    }

    final Element portTypeElement = findElement(document, WSDL_NAMESPACE, "portType", bindingType);

    if (portTypeElement == null) {
        return soapOperations;
    }

    final NodeList operationNodeList = portTypeElement.getElementsByTagNameNS(WSDL_NAMESPACE, "operation");
    for (int operationIndex = 0; operationIndex < operationNodeList.getLength(); operationIndex++) {
        final Node operationNode = operationNodeList.item(operationIndex);
        if (operationNode.getNodeType() == Node.ELEMENT_NODE) {
            final Element operationElement = (Element) operationNode;
            final String operationName = getAttribute(operationElement, "name");
            final SoapOperationDto soapOperation = new SoapOperationDto();
            final String defaultBody = generateDefaultBody(operationName, operationElement.getNamespaceURI());
            final String inputMessageName = getInputMessageName(operationElement);
            final String identifier = inputMessageName != null && !inputMessageName.isEmpty() ? inputMessageName
                    : operationName;

            soapOperation.setName(operationName);
            soapOperation.setIdentifier(identifier);
            soapOperation.setHttpMethod(HttpMethod.POST);
            soapOperation.setStatus(SoapOperationStatus.MOCKED);
            soapOperation.setResponseStrategy(SoapResponseStrategy.RANDOM);
            soapOperation.setForwardedEndpoint(soapOperationAddress);
            soapOperation.setOriginalEndpoint(soapOperationAddress);
            soapOperation.setSoapVersion(soapVersion);
            soapOperation.setMockResponses(new ArrayList<SoapMockResponseDto>());
            soapOperation.setDefaultBody(defaultBody);
            soapOperation.setCurrentResponseSequenceIndex(DEFAULT_RESPONSE_SEQUENCE_INDEX);
            if (generateResponse) {
                final SoapMockResponseDto mockResponse = new SoapMockResponseDto();
                mockResponse.setBody(soapOperation.getDefaultBody());
                mockResponse.setStatus(SoapMockResponseStatus.ENABLED);
                mockResponse.setName(AUTO_GENERATED_MOCK_RESPONSE_DEFAULT_NAME);
                mockResponse.setHttpStatusCode(DEFAULT_HTTP_STATUS_CODE);
                soapOperation.getMockResponses().add(mockResponse);
            }

            soapOperations.add(soapOperation);
        }
    }
    return soapOperations;
}

From source file:com.flozano.socialauth.provider.GooglePlusImpl.java

@Override
public List<Contact> getContactList() throws Exception {
    LOG.info("Fetching contacts from " + CONTACTS_FEED_URL);
    if (Permission.AUTHENTICATE_ONLY.equals(this.scope)) {
        throw new SocialAuthException("You have not set Permission to get contacts.");
    }/*from   w w w.  j a v a  2 s  .c o m*/
    Response serviceResponse = null;
    try {
        Map<String, String> map = new HashMap<String, String>();
        map.put("Authorization", "Bearer " + getAccessGrant().getKey());
        serviceResponse = authenticationStrategy.executeFeed(CONTACTS_FEED_URL, null, null, map, null);
    } catch (Exception ie) {
        throw new SocialAuthException("Failed to retrieve the contacts from " + CONTACTS_FEED_URL, ie);
    }
    List<Contact> plist = new ArrayList<Contact>();
    Element root;

    try {
        root = XMLParseUtil.loadXmlResource(serviceResponse.getInputStream());
    } catch (Exception e) {
        throw new ServerDataException("Failed to parse the contacts from response." + CONTACTS_FEED_URL, e);
    }
    NodeList contactsList = root.getElementsByTagName("entry");
    if (contactsList != null && contactsList.getLength() > 0) {
        LOG.debug("Found contacts : " + contactsList.getLength());
        for (int i = 0; i < contactsList.getLength(); i++) {
            Element contact = (Element) contactsList.item(i);
            String fname = "";
            NodeList l = contact.getElementsByTagNameNS(CONTACT_NAMESPACE, "email");
            String address = null;
            String emailArr[] = null;
            if (l != null && l.getLength() > 0) {
                Element el = (Element) l.item(0);
                if (el != null) {
                    address = el.getAttribute("address");
                }
                if (l.getLength() > 1) {
                    emailArr = new String[l.getLength() - 1];
                    for (int k = 1; k < l.getLength(); k++) {
                        Element e = (Element) l.item(k);
                        if (e != null) {
                            emailArr[k - 1] = e.getAttribute("address");
                        }
                    }
                }
            }
            String lname = "";
            String dispName = XMLParseUtil.getElementData(contact, "title");
            if (dispName != null) {
                String sarr[] = dispName.split(" ");
                if (sarr.length > 0) {
                    if (sarr.length >= 1) {
                        fname = sarr[0];
                    }
                    if (sarr.length >= 2) {
                        StringBuilder sb = new StringBuilder();
                        for (int k = 1; k < sarr.length; k++) {
                            sb.append(sarr[k]).append(" ");
                        }
                        lname = sb.toString();
                    }
                }
            }
            String id = XMLParseUtil.getElementData(contact, "id");

            if (address != null && address.length() > 0) {
                Contact p = new Contact();
                p.setFirstName(fname);
                p.setLastName(lname);
                p.setEmail(address);
                p.setDisplayName(dispName);
                p.setOtherEmails(emailArr);
                p.setId(id);
                plist.add(p);
            }
        }
    } else {
        LOG.debug("No contacts were obtained from the feed : " + CONTACTS_FEED_URL);
    }
    return plist;
}

From source file:be.fedict.eid.applet.service.signer.facets.KeyInfoSignatureFacet.java

public void postSign(Element signatureElement, List<X509Certificate> signingCertificateChain) {
    LOG.debug("postSign");

    String signatureNamespacePrefix = signatureElement.getPrefix();

    /*//from  ww  w  . j  a va  2s  .  c o m
     * Make sure we insert right after the ds:SignatureValue element, just
     * before the first ds:Object element.
     */
    Node nextSibling;
    NodeList objectNodeList = signatureElement.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#",
            "Object");
    if (0 == objectNodeList.getLength()) {
        nextSibling = null;
    } else {
        nextSibling = objectNodeList.item(0);
    }

    /*
     * Construct the ds:KeyInfo element using JSR 105.
     */
    KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI());
    List<Object> x509DataObjects = new LinkedList<Object>();
    X509Certificate signingCertificate = signingCertificateChain.get(0);

    List<Object> keyInfoContent = new LinkedList<Object>();

    if (this.includeKeyValue) {
        KeyValue keyValue;
        try {
            keyValue = keyInfoFactory.newKeyValue(signingCertificate.getPublicKey());
        } catch (KeyException e) {
            throw new RuntimeException("key exception: " + e.getMessage(), e);
        }
        keyInfoContent.add(keyValue);
    }

    if (this.includeIssuerSerial) {
        x509DataObjects.add(keyInfoFactory.newX509IssuerSerial(
                signingCertificate.getIssuerX500Principal().toString(), signingCertificate.getSerialNumber()));
    }

    if (this.includeEntireCertificateChain) {
        for (X509Certificate certificate : signingCertificateChain) {
            x509DataObjects.add(certificate);
        }
    } else {
        x509DataObjects.add(signingCertificate);
    }

    if (false == x509DataObjects.isEmpty()) {
        X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects);
        keyInfoContent.add(x509Data);
    }
    KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent);
    DOMKeyInfo domKeyInfo = (DOMKeyInfo) keyInfo;

    Key key = new Key() {
        private static final long serialVersionUID = 1L;

        public String getAlgorithm() {
            return null;
        }

        public byte[] getEncoded() {
            return null;
        }

        public String getFormat() {
            return null;
        }
    };

    XMLSignContext xmlSignContext = new DOMSignContext(key, signatureElement);
    DOMCryptoContext domCryptoContext = (DOMCryptoContext) xmlSignContext;
    try {
        domKeyInfo.marshal(signatureElement, nextSibling, signatureNamespacePrefix, domCryptoContext);
    } catch (MarshalException e) {
        throw new RuntimeException("marshall error: " + e.getMessage(), e);
    }
}

From source file:be.fedict.eid.applet.service.signer.facets.XAdESSignatureFacet.java

private Node marshallQualifyingProperties(Document document, ObjectFactory xadesObjectFactory,
        QualifyingPropertiesType qualifyingProperties) {
    Node marshallNode = document.createElement("marshall-node");
    try {/* ww w.  j a v a2 s. c  o  m*/
        this.marshaller.marshal(xadesObjectFactory.createQualifyingProperties(qualifyingProperties),
                marshallNode);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }
    Element qualifyingPropertiesElement = (Element) marshallNode.getFirstChild();
    Element signedPropertiesElement = (Element) qualifyingPropertiesElement
            .getElementsByTagNameNS("http://uri.etsi.org/01903/v1.3.2#", "SignedProperties").item(0);
    signedPropertiesElement.setIdAttribute("Id", true);
    return qualifyingPropertiesElement;
}