Example usage for org.w3c.dom Element getTextContent

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

Introduction

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

Prototype

public String getTextContent() throws DOMException;

Source Link

Document

This attribute returns the text content of this node and its descendants.

Usage

From source file:org.yamj.core.service.metadata.nfo.InfoReader.java

/**
 * Parse Actors from the XML NFO file./*www  .  j ava2s  . c o m*/
 *
 * @param nlElements
 * @param dto
 */
private static void parseActors(NodeList nlElements, InfoDTO dto) {
    // check if we have a node
    if (nlElements == null || nlElements.getLength() == 0) {
        return;
    }

    for (int actorLoop = 0; actorLoop < nlElements.getLength(); actorLoop++) {
        // Get all the name/role/thumb nodes
        Node nActors = nlElements.item(actorLoop);
        NodeList nlCast = nActors.getChildNodes();
        Node nElement;

        String aName = null;
        String aRole = null;
        String aThumb = null;
        Boolean firstActor = Boolean.TRUE;

        if (nlCast.getLength() > 1) {
            for (int looper = 0; looper < nlCast.getLength(); looper++) {
                nElement = nlCast.item(looper);
                if (nElement.getNodeType() == Node.ELEMENT_NODE) {
                    Element eCast = (Element) nElement;
                    if (eCast.getNodeName().equalsIgnoreCase("name")) {
                        if (firstActor) {
                            firstActor = Boolean.FALSE;
                        } else {
                            dto.addActor(aName, aRole, aThumb);
                        }
                        aName = eCast.getTextContent();
                        aRole = null;
                        aThumb = null;
                    } else if (eCast.getNodeName().equalsIgnoreCase("role")
                            && StringUtils.isNotBlank(eCast.getTextContent())) {
                        aRole = eCast.getTextContent();
                    } else if (eCast.getNodeName().equalsIgnoreCase("thumb")
                            && StringUtils.isNotBlank(eCast.getTextContent())) {
                        // thumb will be skipped if there's nothing in there
                        aThumb = eCast.getTextContent();
                    }
                    // There's a case where there might be a different node here that isn't name, role or thumb, but that will be ignored
                }
            }
        } else {
            // This looks like a Mede8er node in the "<actor>Actor Name</actor>" format, so just get the text element
            aName = nActors.getTextContent();
        }

        // after all add the last scraped actor
        dto.addActor(aName, aRole, aThumb);
    }
}

From source file:eu.europa.ec.markt.dss.validation.xades.XAdESCertificateSource.java

@Override
public List<X509Certificate> getCertificates() {
    List<X509Certificate> list = new ArrayList<X509Certificate>();

    try {//from w  w w . jav a 2 s . co  m
        CertificateFactory factory = CertificateFactory.getInstance("X509");

        NodeList nodeList2 = (NodeList) XMLUtils.getNodeList(signatureElement,
                "ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties/xades:CertificateValues/xades:EncapsulatedX509Certificate");
        for (int i = 0; i < nodeList2.getLength(); i++) {
            Element certEl = (Element) nodeList2.item(i);
            byte[] derEncoded = Base64.decodeBase64(certEl.getTextContent());
            X509Certificate cert = (X509Certificate) factory
                    .generateCertificate(new ByteArrayInputStream(derEncoded));
            if (!list.contains(cert)) {
                list.add(cert);
            }
        }

        if (!onlyExtended) {
            NodeList nodeList = (NodeList) XMLUtils.getNodeList(signatureElement,
                    "ds:KeyInfo/ds:X509Data/ds:X509Certificate");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Element certEl = (Element) nodeList.item(i);
                byte[] derEncoded = Base64.decodeBase64(certEl.getTextContent());
                X509Certificate cert = (X509Certificate) factory
                        .generateCertificate(new ByteArrayInputStream(derEncoded));
                if (!list.contains(cert)) {
                    list.add(cert);
                }
            }
        }

    } catch (CertificateException e) {
        throw new RuntimeException(e);
    }

    return list;
}

From source file:com.evolveum.midpoint.prism.lex.dom.DomLexicalProcessor.java

private static <T> T parsePrimitiveElementValue(Element element, QName typeName,
        XNodeProcessorEvaluationMode mode) throws SchemaException {
    try {/*from w ww . j a v  a 2s .c  om*/
        if (ItemPathType.COMPLEX_TYPE.equals(typeName)) {
            return (T) parsePath(element);
        } else if (DOMUtil.XSD_QNAME.equals(typeName)) {
            return (T) DOMUtil.getQNameValue(element);
        } else if (XmlTypeConverter.canConvert(typeName)) {
            return (T) XmlTypeConverter.toJavaValue(element, typeName);
        } else if (DOMUtil.XSD_ANYTYPE.equals(typeName)) {
            return (T) element.getTextContent(); // if parsing primitive as xsd:anyType, we can safely parse it as string
        } else {
            throw new SchemaException("Cannot convert element '" + element + "' to " + typeName);
        }
    } catch (IllegalArgumentException e) {
        return processIllegalArgumentException(element.getTextContent(), typeName, e, mode); // primitive way of ensuring compatibility mode
    }
}

From source file:edu.xjtu.qxcamerabridge.DescriptorXMLParser.java

/**
 * parse the xml device descriptor. extract the API service URL
 * @return the extracted URLs are stored in the map. The key is the api service name and the value is the dedicated url.
 * @throws ParserConfigurationException//w  w w .  j  av a2s  .  c  om
 * @throws SAXException
 * @throws IOException 
 */
public Map<String, String> parseXML() throws ParserConfigurationException, SAXException, IOException {
    Map<String, String> serviceMap = new HashMap();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(IOUtils.toInputStream(pageContent));
    Element root = document.getDocumentElement();
    Element device = (Element) root.getElementsByTagName("device").item(0);
    Element deviceName = (Element) device.getElementsByTagName("friendlyName").item(0);
    serviceMap.put("deviceName", deviceName.getTextContent());
    Element device_info = (Element) device.getElementsByTagName("av:X_ScalarWebAPI_DeviceInfo").item(0);
    Element serviceList = (Element) device_info.getElementsByTagName("av:X_ScalarWebAPI_ServiceList").item(0);
    // extract the servicelist

    for (int i = 0; i < serviceList.getChildNodes().getLength(); i++) {
        Element eachservice = (Element) serviceList.getElementsByTagName("av:X_ScalarWebAPI_Service").item(i);
        Element servicetype = (Element) eachservice.getElementsByTagName("av:X_ScalarWebAPI_ServiceType")
                .item(0);
        Element actionURL = (Element) eachservice.getElementsByTagName("av:X_ScalarWebAPI_ActionList_URL")
                .item(0);
        serviceMap.put(servicetype.getTextContent(), actionURL.getTextContent());

    }
    Element imagingDevice = (Element) device_info.getElementsByTagName("av:X_ScalarWebAPI_ImagingDevice")
            .item(0);
    Element liveviewURL = (Element) imagingDevice.getElementsByTagName("av:X_ScalarWebAPI_LiveView_URL")
            .item(0);
    serviceMap.put("liveViewURL", liveviewURL.getTextContent());

    return serviceMap;
}

From source file:edu.internet2.middleware.shibboleth.common.config.attribute.filtering.AttributeFilterPolicyBeanDefinitionParser.java

/** {@inheritDoc} */
protected void doParse(Element config, ParserContext parserContext, BeanDefinitionBuilder builder) {
    super.doParse(config, parserContext, builder);

    String policyId = DatatypeHelper.safeTrimOrNullString(config.getAttributeNS(null, "id"));
    log.info("Parsing configuration for attribute filter policy {}", policyId);
    builder.addPropertyValue("policyId", policyId);
    List<Element> children;
    Map<QName, List<Element>> childrenMap = XMLHelper.getChildElements(config);

    children = childrenMap.get(new QName(AttributeFilterNamespaceHandler.NAMESPACE, "PolicyRequirementRule"));
    if (children != null && children.size() > 0) {
        builder.addPropertyValue("policyRequirement",
                SpringConfigurationUtils.parseInnerCustomElement(children.get(0), parserContext));
    } else {/*from www .j a v  a  2  s . c o m*/
        children = childrenMap
                .get(new QName(AttributeFilterNamespaceHandler.NAMESPACE, "PolicyRequirementRuleReference"));
        String reference = getAbsoluteReference(config, "PolicyRequirementRule",
                children.get(0).getTextContent());
        builder.addPropertyReference("policyRequirement", reference);
    }

    ManagedList attributeRules = new ManagedList();
    children = childrenMap.get(new QName(AttributeFilterNamespaceHandler.NAMESPACE, "AttributeRule"));
    if (children != null && children.size() > 0) {
        attributeRules.addAll(SpringConfigurationUtils.parseInnerCustomElements(children, parserContext));
    }

    children = childrenMap.get(new QName(AttributeFilterNamespaceHandler.NAMESPACE, "AttributeRuleReference"));
    if (children != null && children.size() > 0) {
        String reference;
        for (Element child : children) {
            reference = getAbsoluteReference(config, "AttributeRule", child.getTextContent());
            attributeRules.add(new RuntimeBeanReference(reference));
        }
    }

    builder.addPropertyValue("attributeRules", attributeRules);
}

From source file:com.msopentech.odatajclient.engine.data.ODataBinder.java

private static ODataPrimitiveValue fromPrimitiveValueElement(final Element prop, final EdmType edmType) {
    final ODataPrimitiveValue value;
    if (edmType != null && edmType.getSimpleType().isGeospatial()) {
        final Element geoProp = ODataConstants.PREFIX_GML.equals(prop.getPrefix()) ? prop
                : (Element) XMLUtils.getChildNodes(prop, Node.ELEMENT_NODE).get(0);
        value = new ODataGeospatialValue.Builder().setType(edmType.getSimpleType()).setTree(geoProp).build();
    } else {//  www .ja  v  a2 s.co m
        value = new ODataPrimitiveValue.Builder().setType(edmType == null ? null : edmType.getSimpleType())
                .setText(prop.getTextContent()).build();
    }
    return value;
}

From source file:com.t2tierp.controller.nfe.StatusServico.java

public String verificaStatusServico(KeyStore ks, String alias, char[] senha) {
    try {/*from   ww  w .ja  va 2  s.  c  o m*/
        String codigoUf = "52";
        String ambiente = "2";
        String versaoDados = "3.10";
        String url = "https://homolog.sefaz.go.gov.br/nfe/services/v2/NfeStatusServico2?wsdl";

        //cria o xml de requisicao
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<consStatServ versao=\"" + versaoDados
                + "\" xmlns=\"http://www.portalfiscal.inf.br/nfe\">" + "<tpAmb>" + ambiente + "</tpAmb>"
                + "<cUF>" + codigoUf + "</cUF>" + "<xServ>STATUS</xServ>" + "</consStatServ>";

        //busca os dados do certificado digital
        X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
        PrivateKey privatekey = (PrivateKey) ks.getKey(alias, senha);
        SocketFactoryDinamico socketFactory = new SocketFactoryDinamico(certificate, privatekey);
        //arquivo que contm a cadeia de certificados do servio a ser consumido
        socketFactory
                .setFileCacerts(this.getClass().getResourceAsStream("/br/inf/portalfiscal/nfe/jssecacerts"));

        //define o protocolo a ser utilizado na conexao
        Protocol protocol = new Protocol("https", socketFactory, 443);
        Protocol.registerProtocol("https", protocol);

        //cria os dados da mensagem
        OMElement omeElement = AXIOMUtil.stringToOM(xml);
        NfeStatusServico2Stub.NfeDadosMsg nfeDadosMsg = new NfeStatusServico2Stub.NfeDadosMsg();
        nfeDadosMsg.setExtraElement(omeElement);

        //define os dados do cabecalho da mensagem
        NfeStatusServico2Stub.NfeCabecMsg nfeCabecMsg = new NfeStatusServico2Stub.NfeCabecMsg();
        nfeCabecMsg.setCUF(codigoUf);
        nfeCabecMsg.setVersaoDados(versaoDados);
        NfeStatusServico2Stub.NfeCabecMsgE nfeCabecMsgE = new NfeStatusServico2Stub.NfeCabecMsgE();
        nfeCabecMsgE.setNfeCabecMsg(nfeCabecMsg);

        //cria o servico
        NfeStatusServico2Stub stub = new NfeStatusServico2Stub(url);

        //busca o resutado
        NfeStatusServico2Stub.NfeStatusServicoNF2Result result = stub.nfeStatusServicoNF2(nfeDadosMsg,
                nfeCabecMsgE);

        //processa o resultado
        ByteArrayInputStream in = new ByteArrayInputStream(
                result.getExtraElement().toString().getBytes("UTF-8"));

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        Document doc = dbf.newDocumentBuilder().parse(in);

        NodeList nodeList = doc.getDocumentElement().getElementsByTagName("xMotivo");

        String retorno = "Status: ";
        for (int i = 0; i < nodeList.getLength(); i++) {
            Element element = (Element) nodeList.item(i);
            retorno += element.getTextContent();
        }

        return retorno;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return "Erro ao consultar o status do servio!";
}

From source file:edu.internet2.middleware.shibboleth.common.config.attribute.resolver.attributeDefinition.TemplateAttributeDefinitionBeanDefinitionParser.java

/** {@inheritDoc} */
protected void doParse(String pluginId, Element pluginConfig, Map<QName, List<Element>> pluginConfigChildren,
        BeanDefinitionBuilder pluginBuilder, ParserContext parserContext) {
    super.doParse(pluginId, pluginConfig, pluginConfigChildren, pluginBuilder, parserContext);

    if (pluginConfigChildren.containsKey(TEMPLATE_ELEMENT_NAME)) {
        Element templateElement = pluginConfigChildren.get(TEMPLATE_ELEMENT_NAME).get(0);
        String attributeTemplate = DatatypeHelper.safeTrimOrNullString(templateElement.getTextContent());
        pluginBuilder.addPropertyValue("attributeTemplate", attributeTemplate);
    }/* ww w . ja v a 2s . c  o m*/

    List<String> sourceAttributes = new ArrayList<String>();
    for (Element element : pluginConfigChildren.get(SOURCE_ATTRIBUTE_ELEMENT_NAME)) {
        sourceAttributes.add(DatatypeHelper.safeTrimOrNullString(element.getTextContent()));
    }
    pluginBuilder.addPropertyValue("sourceAttributes", sourceAttributes);

    String velocityEngineRef = pluginConfig.getAttributeNS(null, "velocityEngine");
    pluginBuilder.addPropertyReference("velocityEngine", velocityEngineRef);
}

From source file:edu.internet2.middleware.shibboleth.common.config.security.AbstractCredentialBeanDefinitionParser.java

/**
 * Parses the key names from the credential configuration.
 * /*w  ww .j  a  v  a  2s  .c  om*/
 * @param configChildren children of the credential element
 * @param builder credential build
 */
protected void parseKeyNames(Map<QName, List<Element>> configChildren, BeanDefinitionBuilder builder) {
    log.debug("Parsing credential key names");
    List<Element> keyNameElems = configChildren.get(new QName(SecurityNamespaceHandler.NAMESPACE, "KeyName"));
    if (keyNameElems == null || keyNameElems.isEmpty()) {
        return;
    }

    String keyName;
    ArrayList<String> keyNames = new ArrayList<String>();
    for (Element keyNameElem : keyNameElems) {
        keyName = DatatypeHelper.safeTrimOrNullString(keyNameElem.getTextContent());
        if (keyName != null) {
            keyNames.add(keyName);
        }
    }

    builder.addPropertyValue("keyNames", keyNames);
}

From source file:eu.eexcess.zbw.recommender.PartnerConnector.java

protected String getValueWithXPath(String xpath, Document orgPartnerResult) {
    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodes;// w w  w . j a v  a  2s  .co m
    try {
        nodes = (NodeList) xPath.evaluate(xpath, orgPartnerResult.getDocumentElement(), XPathConstants.NODESET);
        for (int i = 0; i < nodes.getLength();) {
            Element e = (Element) nodes.item(i);
            return e.getTextContent();
        }
    } catch (XPathExpressionException e1) {
        e1.printStackTrace();
    }
    return "";
}