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:com.bluexml.side.Integration.alfresco.xforms.webscript.XmlParser.java

public Map<String, Object> parse(Element element) throws Exception {
    Map<String, Object> objectModel = new HashMap<String, Object>();

    String qualifiedName = getQualifiedName(element);
    objectModel.put("dataType", qualifiedName);

    // collect attributes
    Element attributeContainer = DOMUtil.getChild(element, "attributes");
    Map<String, Object> attrs = new HashMap<String, Object>();
    if (attributeContainer != null) {
        List<Element> attributes = DOMUtil.getChildren(attributeContainer, "attribute");
        for (Element e : attributes) {
            // only legitimate attributes should find their way into the attributes map
            if (StringUtils.trimToNull(e.getAttribute("skipMe")) == null) {
                String attributeName = getQualifiedName(e);
                List<Element> value = DOMUtil.getChildren(e, "value");

                if (value.size() == 1) {
                    String stringValue = value.get(0).getTextContent();
                    attrs.put(attributeName, stringValue);
                } else if (value.size() > 1) {
                    List<String> values = new ArrayList<String>(value.size());
                    for (Element valueElement : value) {
                        String stringValue = StringUtils.trimToEmpty(valueElement.getTextContent());
                        values.add(stringValue);
                    }/* w  ww  . j a v a  2  s  . com*/
                    attrs.put(attributeName, values);
                }
            }
        }
    }
    objectModel.put("attributes", attrs);

    // collect associations
    Element associationsContener = DOMUtil.getChild(element, "associations");

    List<AssociationBean> assos = new ArrayList<AssociationBean>();
    if (associationsContener != null) {
        String associationsAction = associationsContener.getAttribute("action");
        if (StringUtils.trimToNull(associationsAction) != null) {
            objectModel.put("associationsAction", associationsAction);
        }
        List<Element> associations = DOMUtil.getChildren(associationsContener, "association");
        for (Element e : associations) {
            AssociationBean association = new AssociationBean();
            association.setAssociationName(getQualifiedName(e));
            Element target = DOMUtil.getChild(e, "target");
            String action = e.getAttribute("action");
            if (StringUtils.trimToNull(action) != null) {
                association.setAction(AssociationBean.Actions.valueOf(action));
            }
            if (target != null) {
                String targetRef = target.getTextContent();
                String targetQualifiedName = getQualifiedName(target);
                association.setTargetQualifiedName(targetQualifiedName);
                association.setTargetId(targetRef);
            }
            assos.add(association);
        }
    }
    objectModel.put("associations", assos);

    return objectModel;
}

From source file:com.twinsoft.convertigo.engine.AttachmentManager.java

static public AttachmentDetails getAttachment(Element eAttachment) {
    try {//  ww  w  .j a  va 2  s .c  o m
        if ("attachment".equals(eAttachment.getTagName())
                && "attachment".equals(eAttachment.getAttribute("type"))) {
            String attr;
            final String name = eAttachment.getAttribute("name");
            final String contentType = eAttachment.getAttribute("content-type");
            final byte[][] data = new byte[1][];
            if ((attr = eAttachment.getAttribute("local-url")) != null && attr.length() > 0) {
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(attr);
                    fis.read(data[0] = new byte[fis.available()]);
                } finally {
                    if (fis != null)
                        fis.close();
                }

            } else if ((attr = eAttachment.getAttribute("encoding")) != null && attr.length() > 0) {
                if ("base64".equals(attr)) {
                    data[0] = Base64.decodeBase64(eAttachment.getTextContent());
                }
            }
            if (data[0] != null) {
                return new AttachmentDetails() {
                    public byte[] getData() {
                        return data[0];
                    }

                    public String getName() {
                        return name;
                    }

                    public String getContentType() {
                        return contentType;
                    }
                };
            }
        }
    } catch (Exception e) {
        Engine.logEngine.error("failed to make AttachmentDetails", e);
    }
    return null;
}

From source file:de.codesourcery.eve.apiclient.utils.XMLParseHelper.java

public static String getChildValue(Element node, String childName) {

    final NodeList l = node.getChildNodes();
    Element result = null;
    for (int i = 0; i < l.getLength(); i++) {
        final Node n = l.item(i);
        if (n instanceof Element && n.getNodeName().equals(childName)) {
            if (result != null) {
                throw new UnparseableResponseException("Found more than one child element " + " named '"
                        + childName + "' " + "below node '" + node.getNodeName() + "' , expected exactly one");
            }/*from  www  .  ja  va 2  s.co m*/
            result = (Element) n;
        }
    }
    if (result == null) {
        throw new UnparseableResponseException("Expected child element " + " '" + childName + "' "
                + " not found below node '" + node.getNodeName());
    }

    final String value = result.getTextContent();
    if (StringUtils.isBlank(value)) {
        throw new UnparseableResponseException("Child element " + " '" + childName + "' " + " below node '"
                + node.getNodeName() + " has no/blank value ?");
    }
    return value;
}

From source file:com.evolveum.midpoint.model.common.expression.functions.BasicExpressionFunctionsXPath.java

public String determineLdapSingleAttributeValue(Collection<String> dns, String attributeName,
        Element valueElement) throws NamingException {
    // Trivial case: the value is a single element therefore it has a single value.
    return valueElement.getTextContent();
}

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

/**
 * Parses the public key from the credential configuration.
 * //from  w  ww  .j ava2s  . co  m
 * @param configChildren children of the credential element
 * @param builder credential build
 */
protected void parsePublicKey(Map<QName, List<Element>> configChildren, BeanDefinitionBuilder builder) {
    List<Element> keyElems = configChildren.get(new QName(SecurityNamespaceHandler.NAMESPACE, "PublicKey"));
    if (keyElems == null || keyElems.isEmpty()) {
        return;
    }

    log.debug("Parsing credential public key");
    Element pubKeyElem = keyElems.get(0);
    byte[] encodedKey = getEncodedPublicKey(DatatypeHelper.safeTrimOrNullString(pubKeyElem.getTextContent()));
    String keyPassword = DatatypeHelper.safeTrimOrNullString(pubKeyElem.getAttributeNS(null, "password"));
    char[] keyPasswordCharArray = null;
    if (keyPassword != null) {
        keyPasswordCharArray = keyPassword.toCharArray();
    }
    try {
        PublicKey pubKey = SecurityHelper.decodePublicKey(encodedKey, keyPasswordCharArray);
        builder.addPropertyValue("publicKey", pubKey);
    } catch (KeyException e) {
        throw new FatalBeanException("Unable to create credential, unable to parse public key", e);
    }
}

From source file:com.msopentech.odatajclient.engine.data.json.JSONPropertySerializer.java

/**
 * {@inheritDoc }//  w  w  w.  ja v  a 2s  .c  o m
 */
@Override
public void serialize(final JSONProperty property, final JsonGenerator jgen, final SerializerProvider provider)
        throws IOException, JsonProcessingException {

    jgen.writeStartObject();

    if (property.getMetadata() != null) {
        jgen.writeStringField(ODataConstants.JSON_METADATA, property.getMetadata().toASCIIString());
    }

    final Element content = property.getContent();
    if (XMLUtils.hasOnlyTextChildNodes(content)) {
        jgen.writeStringField(ODataConstants.JSON_VALUE, content.getTextContent());
    } else {
        try {
            final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder();
            final Document document = builder.newDocument();
            final Element wrapper = document.createElement(ODataConstants.ELEM_PROPERTY);

            if (XMLUtils.hasElementsChildNode(content)) {
                wrapper.appendChild(document.renameNode(document.importNode(content, true), null,
                        ODataConstants.JSON_VALUE));

                DOMTreeUtils.writeSubtree(jgen, wrapper);
            } else if (EdmSimpleType.isGeospatial(content.getAttribute(ODataConstants.ATTR_M_TYPE))) {
                wrapper.appendChild(document.renameNode(document.importNode(content, true), null,
                        ODataConstants.JSON_VALUE));

                DOMTreeUtils.writeSubtree(jgen, wrapper, true);
            } else {
                DOMTreeUtils.writeSubtree(jgen, content);
            }
        } catch (Exception e) {
            throw new JsonParseException("Cannot serialize property", JsonLocation.NA, e);
        }
    }

    jgen.writeEndObject();
}

From source file:mk.finki.ranggo.aggregator.ContentsAggregatorImpl.java

private static void fetchPersonDetailsFromDbpedia(Person person) {
    String url = person.getDbpediaUrl();
    url = url.replace("http://dbpedia.org/resource/", "http://dbpedia.org/data/")
            .replace("http://dbpedia.org/page/", "http://dbpedia.org/data/");
    url += ".xml";

    try {/*from   w w w  .  j  a  v  a  2  s  . com*/
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(url);
        //System.out.println(getStringFromDocument(document));

        //extract abstract (short biography)
        NodeList abstracts = document.getElementsByTagName("dbo:abstract");
        for (int i = 0; i < abstracts.getLength(); i++) {
            Element entity = (Element) abstracts.item(i);
            if (entity.hasAttribute("xml:lang") && entity.getAttribute("xml:lang").equals("en")) {
                String dbAbstract = entity.getTextContent().replaceAll("&#39;", "'").replaceAll("&lt;", "<")
                        .replaceAll("&gt;", ">").replaceAll("&amp;", "&").replaceAll("", "-");
                person.setShortBio(dbAbstract);
            }
        }

        //extract thumbnail (picture url)
        NodeList thumbnails = document.getElementsByTagName("dbo:thumbnail");
        for (int i = 0; i < thumbnails.getLength(); i++) {
            Element entity = (Element) thumbnails.item(i);
            if (entity.hasAttribute("rdf:resource")) {
                String dbThumbnail = entity.getAttribute("rdf:resource");
                person.setPictureUrl(dbThumbnail);
            }
        }
    } catch (ParserConfigurationException exception) {
    } catch (SAXException exception) {
    } catch (IOException exception) {
    }
}

From source file:org.onesun.atomator.adaptors.AdaptorFactory.java

private void parseDocument(Document document) {
    Element element = document.getDocumentElement();

    NodeList updates = element.getElementsByTagName("entry");
    if (updates != null && updates.getLength() > 0) {
        logger.info("Reading adaptors.xml : loading #" + updates.getLength() + " adaptors");
        for (int index = 0; index < updates.getLength(); index++) {
            Element item = (Element) updates.item(index);

            try {
                String identity = XMLUtils.getValue(item, "identity");
                String adaptorName = XMLUtils.getValue(item, "adaptor");

                NodeList feedUrls = item.getElementsByTagName("feedURL");
                if (feedUrls != null && feedUrls.getLength() > 0) {
                    Set<String> uriSet = null;

                    uriSet = urlEntries.get(identity);
                    if (uriSet == null) {
                        uriSet = new HashSet<String>();
                    }//  w ww . j a va  2s.c  o  m

                    for (int findex = 0; findex < feedUrls.getLength(); findex++) {
                        Element feedURL = (Element) feedUrls.item(findex);

                        uriSet.add(feedURL.getTextContent());
                    }

                    urlEntries.put(identity, uriSet);
                }

                Class<?> clazz = (Class<?>) Class.forName(adaptorName);
                logger.info("Loaded class for adaptor: " + adaptorName);

                adaptors.put(identity, clazz);
            } catch (ClassNotFoundException e) {
                logger.error("Class Not Found Exception while loading adaptors : " + e.getMessage());
            }
        }
    }
}

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

@Override
public List<X509CRL> getCRLsFromSignature() {
    List<X509CRL> list = new ArrayList<X509CRL>();

    try {//  w ww  .  j ava  2 s  .  c  o m
        NodeList nodeList = (NodeList) XMLUtils.getNodeList(signatureElement, CRL_XPATH);
        for (int i = 0; i < nodeList.getLength(); i++) {
            Element certEl = (Element) nodeList.item(i);
            CertificateFactory factory = CertificateFactory.getInstance("X509");
            byte[] derEncoded = Base64.decodeBase64(certEl.getTextContent());
            X509CRL cert = (X509CRL) factory.generateCRL(new ByteArrayInputStream(derEncoded));
            list.add(cert);
        }
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    } catch (CRLException e) {
        throw new RuntimeException(e);
    }

    return list;
}

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

/**
 * Parses the private key from the credential configuration.
 * /*from  w  w  w  . j  a  v a  2 s  . c  o m*/
 * @param configChildren children of the credential element
 * @param builder credential build
 */
protected void parsePrivateKey(Map<QName, List<Element>> configChildren, BeanDefinitionBuilder builder) {
    List<Element> keyElems = configChildren.get(new QName(SecurityNamespaceHandler.NAMESPACE, "PrivateKey"));
    if (keyElems == null || keyElems.isEmpty()) {
        return;
    }

    log.debug("Parsing credential private key");
    Element privKeyElem = keyElems.get(0);
    byte[] encodedKey = getEncodedPrivateKey(DatatypeHelper.safeTrimOrNullString(privKeyElem.getTextContent()));
    String keyPassword = DatatypeHelper.safeTrimOrNullString(privKeyElem.getAttributeNS(null, "password"));
    char[] keyPasswordCharArray = null;
    if (keyPassword != null) {
        keyPasswordCharArray = keyPassword.toCharArray();
    }
    try {
        PrivateKey privKey = SecurityHelper.decodePrivateKey(encodedKey, keyPasswordCharArray);
        builder.addPropertyValue("privateKey", privKey);
    } catch (KeyException e) {
        throw new FatalBeanException("Unable to create credential, unable to parse private key", e);
    }
}