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.andyasprou.webcrawler.Utilities.GenericSiteMapParser.java

/**
 * <p>Parse XML that contains a Sitemap Index. Example Sitemap Index:</p>
 * <pre>/*ww w. ja v  a2s  . com*/
 * {@code
 * <?xml version="1.0" encoding="UTF-8"?> 
 *   <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
 *     <sitemap>
 *       <loc>http://www.example.com/sitemap1.xml.gz</loc>
 *       <lastmod>2004-10-01T18:23:17+00:00</lastmod>
 *     </sitemap>
 *     <sitemap>
 *       <loc>http://www.example.com/sitemap2.xml.gz</loc>
 *       <lastmod>2005-01-01</lastmod>
 *     </sitemap>
 *   </sitemapindex>
 * }
 * </pre>
 * @param url
 *            - URL of Sitemap Index
 * @param nodeList a {@link org.w3c.dom.NodeList} backing the sitemap
 * @return The site map index
 */
protected SiteMapIndex parseSitemapIndex(URL url, NodeList nodeList) {

    SiteMapIndex sitemapIndex = new SiteMapIndex(url);

    // Loop through the <sitemap>s
    for (int i = 0; i < nodeList.getLength() && i < MAX_URLS; i++) {

        Node firstNode = nodeList.item(i);

        if (firstNode.getNodeType() == Node.ELEMENT_NODE) {
            Element elem = (Element) firstNode;
            String loc = getElementValue(elem, "loc");

            // try the text content when no loc element
            // has been specified
            if (loc == null) {
                loc = elem.getTextContent().trim();
            }

            try {
                URL sitemapUrl = new URL(loc);
                String lastmod = getElementValue(elem, "lastmod");
                Date lastModified = SiteMap.convertToDate(lastmod);

                // Right now we are not worried about sitemapUrls that point
                // to different websites.

                SiteMap s = new SiteMap(sitemapUrl, lastModified);
            } catch (MalformedURLException e) {
                return sitemapIndex;
            }
        }
    }
    sitemapIndex.setProcessed(true);
    return sitemapIndex;
}

From source file:com.meidusa.amoeba.context.ProxyRuntimeContext.java

private void loadProxyConfig(Element current, ProxyServerConfig config) {
    NodeList children = current.getChildNodes();
    int childSize = children.getLength();
    Map<String, Object> map = new HashMap<String, Object>();
    for (int i = 0; i < childSize; i++) {
        Node childNode = children.item(i);
        if (childNode instanceof Element) {
            Element child = (Element) childNode;
            final String nodeName = child.getNodeName();
            if (nodeName.equals("property")) {
                String key = child.getAttribute("name");
                String value = child.getTextContent();
                map.put(key, value);// w w  w .  jav a 2 s .  c om
            } else if (nodeName.equals("service")) {
                BeanObjectEntityConfig server = DocumentUtil.loadBeanConfig(child);
                config.addServerConfig(server);
            } else if (nodeName.equals("runtime")) {
                BeanObjectEntityConfig runtime = DocumentUtil.loadBeanConfig(child);
                config.setRuntimeConfig(runtime);
            }
        }
    }
    ParameterMapping.mappingObject(config, map, null);
}

From source file:it.ciroppina.idol.generic.tunnel.IdolOEMTunnel.java

/**
 * Method return List<Map> when every map contains hit fields 
 * //from  w w w  . ja  va2s. c  o m
 * @return ArrayList<Hit> list of Hit, each containing a Map (of dreFileds)
 * 
 */
@WebMethod(operationName = "getQueryHitsMap")
public ArrayList<Hit> getQueryHitsMap(String xml) {
    ArrayList<Hit> result = new ArrayList<Hit>();
    Document document = getDocumentFrom(xml);

    NodeList temp = null;
    temp = document.getElementsByTagName("response");
    String response = (temp.getLength() > 0)
            ? document.getElementsByTagName("response").item(0).getTextContent()
            : "FAILURE";
    temp = document.getElementsByTagName("autn:numhits");
    String numHits = (temp.getLength() > 0)
            ? document.getElementsByTagName("autn:numhits").item(0).getTextContent()
            : "0";
    temp = document.getElementsByTagName("autn:totalhits");
    String totalHits = (temp.getLength() > 0)
            ? document.getElementsByTagName("autn:totalhits").item(0).getTextContent()
            : "0";

    NodeList hits = document.getElementsByTagName("autn:hit");
    //ERROR case detection
    if (hits.getLength() < 1 && response.toUpperCase().contains("ERROR")) {
        ErrorResponse er = new ErrorResponse(document);
        result.add(er);
        return result;
    }

    for (int i = 0; i < hits.getLength(); i++) {
        HashMap<String, String> map = new HashMap<String, String>();
        Node nodo = hits.item(i);
        NodeList hitChilds = nodo.getChildNodes();

        for (int j = 0; j < hitChilds.getLength(); j++) {
            Node n = hitChilds.item(j);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                Element e2 = (Element) n;
                if (!e2.getNodeName().equals("autn:content")) {
                    String value = "";
                    if (map.containsKey(e2.getNodeName())) {
                        value = map.get(e2.getNodeName()) + "," + e2.getTextContent();
                        map.put(e2.getNodeName(), value);
                    } else {
                        map.put(e2.getNodeName(), e2.getTextContent());
                    }

                } else {
                    NodeList content = e2.getElementsByTagName("DOCUMENT").item(0).getChildNodes();

                    for (int z = 0; z < content.getLength(); z++) {
                        Node d = content.item(z);
                        if (d.getNodeType() == Node.ELEMENT_NODE) {
                            Element el = (Element) d;
                            String value = "";
                            if (map.containsKey(el.getNodeName())) {
                                value = map.get(el.getNodeName()) + "," + el.getTextContent();
                                map.put(el.getNodeName(), value);
                            } else {
                                map.put(el.getNodeName(), el.getTextContent());
                            }
                        }
                    }
                }
            }
        }
        Hit hit = new Hit(map);
        hit.getDreFields().put("response", response);
        hit.getDreFields().put("numhits", numHits);
        hit.getDreFields().put("totalhits", totalHits);

        result.add(hit);
    }
    return result;
}

From source file:com.microsoft.windowsazure.management.compute.OperatingSystemOperationsImpl.java

/**
* The List OS Families operation lists the guest operating system families
* available in Azure, and also lists the operating system versions
* available for each family. Currently Azure supports two operating system
* families: the Azure guest operating system that is substantially
* compatible with Windows Server 2008 SP2, and the Azure guest operating
* system that is substantially compatible with Windows Server 2008 R2.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441291.aspx
* for more information)/*ww w. j ava 2  s. c om*/
*
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return The List Operating System Families operation response.
*/
@Override
public OperatingSystemListFamiliesResponse listFamilies()
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        CloudTracing.enter(invocationId, this, "listFamiliesAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/operatingsystemfamilies";
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpGet httpRequest = new HttpGet(url);

    // Set Headers
    httpRequest.setHeader("x-ms-version", "2015-04-01");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        OperatingSystemListFamiliesResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new OperatingSystemListFamiliesResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element operatingSystemFamiliesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "OperatingSystemFamilies");
            if (operatingSystemFamiliesSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(operatingSystemFamiliesSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "OperatingSystemFamily")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element operatingSystemFamiliesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(operatingSystemFamiliesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "OperatingSystemFamily")
                            .get(i1));
                    OperatingSystemListFamiliesResponse.OperatingSystemFamily operatingSystemFamilyInstance = new OperatingSystemListFamiliesResponse.OperatingSystemFamily();
                    result.getOperatingSystemFamilies().add(operatingSystemFamilyInstance);

                    Element nameElement = XmlUtility.getElementByTagNameNS(operatingSystemFamiliesElement,
                            "http://schemas.microsoft.com/windowsazure", "Name");
                    if (nameElement != null) {
                        int nameInstance;
                        nameInstance = DatatypeConverter.parseInt(nameElement.getTextContent());
                        operatingSystemFamilyInstance.setName(nameInstance);
                    }

                    Element labelElement = XmlUtility.getElementByTagNameNS(operatingSystemFamiliesElement,
                            "http://schemas.microsoft.com/windowsazure", "Label");
                    if (labelElement != null) {
                        String labelInstance;
                        labelInstance = labelElement.getTextContent() != null
                                ? new String(Base64.decode(labelElement.getTextContent()))
                                : null;
                        operatingSystemFamilyInstance.setLabel(labelInstance);
                    }

                    Element operatingSystemsSequenceElement = XmlUtility.getElementByTagNameNS(
                            operatingSystemFamiliesElement, "http://schemas.microsoft.com/windowsazure",
                            "OperatingSystems");
                    if (operatingSystemsSequenceElement != null) {
                        for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(operatingSystemsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "OperatingSystem")
                                .size(); i2 = i2 + 1) {
                            org.w3c.dom.Element operatingSystemsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(operatingSystemsSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "OperatingSystem")
                                    .get(i2));
                            OperatingSystemListFamiliesResponse.OperatingSystem operatingSystemInstance = new OperatingSystemListFamiliesResponse.OperatingSystem();
                            operatingSystemFamilyInstance.getOperatingSystems().add(operatingSystemInstance);

                            Element versionElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement,
                                    "http://schemas.microsoft.com/windowsazure", "Version");
                            if (versionElement != null) {
                                String versionInstance;
                                versionInstance = versionElement.getTextContent();
                                operatingSystemInstance.setVersion(versionInstance);
                            }

                            Element labelElement2 = XmlUtility.getElementByTagNameNS(operatingSystemsElement,
                                    "http://schemas.microsoft.com/windowsazure", "Label");
                            if (labelElement2 != null) {
                                String labelInstance2;
                                labelInstance2 = labelElement2.getTextContent() != null
                                        ? new String(Base64.decode(labelElement2.getTextContent()))
                                        : null;
                                operatingSystemInstance.setLabel(labelInstance2);
                            }

                            Element isDefaultElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement,
                                    "http://schemas.microsoft.com/windowsazure", "IsDefault");
                            if (isDefaultElement != null) {
                                boolean isDefaultInstance;
                                isDefaultInstance = DatatypeConverter
                                        .parseBoolean(isDefaultElement.getTextContent().toLowerCase());
                                operatingSystemInstance.setIsDefault(isDefaultInstance);
                            }

                            Element isActiveElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement,
                                    "http://schemas.microsoft.com/windowsazure", "IsActive");
                            if (isActiveElement != null) {
                                boolean isActiveInstance;
                                isActiveInstance = DatatypeConverter
                                        .parseBoolean(isActiveElement.getTextContent().toLowerCase());
                                operatingSystemInstance.setIsActive(isActiveInstance);
                            }
                        }
                    }
                }
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:com.ephesoft.dcma.ibm.IBMCMExporter.java

private void updateDocumentOffsetValue(final String batchInstanceID, final String filePath)
        throws DCMAApplicationException {
    try {/*from w  ww  .j  av a2 s . c o m*/
        org.w3c.dom.Document document = XMLUtil.createDocumentFrom(new File(filePath));
        NodeList documentList = document.getElementsByTagName(IBMCMConstant.DOCUMENT);
        for (int documentIndex = 0; documentIndex < documentList.getLength(); documentIndex++) {
            Element documentTag = (Element) documentList.item(documentIndex);
            Element docTag = (Element) documentTag.getElementsByTagName(IBMCMConstant.DOC_ID).item(0);
            Element offset = (Element) documentTag.getElementsByTagName(IBMCMConstant.OFFSET).item(0);
            String docIdentifier = docTag.getTextContent();
            if (docIdentifier != null & !docIdentifier.isEmpty()) {
                offset.setTextContent(String.valueOf(getOffsetValue(batchInstanceID, docIdentifier)));
            }
        }
        Source source = new DOMSource(document);
        File batchXmlFile = new File(filePath);
        OutputStream outputStream = new FileOutputStream(batchXmlFile);
        Result result = new StreamResult(outputStream);
        Transformer xformer = null;
        try {
            xformer = TransformerFactory.newInstance().newTransformer();
        } catch (TransformerConfigurationException e) {
            String msg = "Exception in transforming configuration file";
            LOGGER.error(msg + e.getMessage(), e);
            throw new DCMAApplicationException(msg + e.getMessage(), e);
        } catch (TransformerFactoryConfigurationError e) {
            String msg = "Exception in transforming factory file";
            LOGGER.error(msg + e.getMessage(), e);
            throw new DCMAApplicationException(msg + e.getMessage(), e);
        }
        try {
            xformer.transform(source, result);
        } catch (TransformerException e) {
            String msg = "Exception in transforming file";
            LOGGER.error(msg + e.getMessage(), e);
            throw new DCMAApplicationException(msg + e.getMessage(), e);
        }
    } catch (Exception e) {
        String msg = "Exception in updating offset into file";
        LOGGER.error(msg + e.getMessage(), e);
        throw new DCMAApplicationException(msg + e.getMessage(), e);
    }
}

From source file:com.evolveum.midpoint.testing.wstest.AbstractWebserviceTest.java

protected void assertAttribute(ShadowType shadow, QName attrName, String attrVal) {
    ShadowAttributesType attributes = shadow.getAttributes();
    for (Object any : attributes.getAny()) {
        if (any instanceof Element) {
            Element element = (Element) any;
            if (DOMUtil.getQName(element).equals(attrName)) {
                assertEquals("Wrong attribute " + attrName + " in shadow " + ModelClientUtil.toString(shadow),
                        attrVal, element.getTextContent());
            }//from   w w w . ja v a 2 s  . c o m
        } else if (any instanceof JAXBElement<?>) {
            JAXBElement<?> jaxbElement = (JAXBElement<?>) any;
            if (jaxbElement.getName().equals(attrName)) {
                assertEquals("Wrong attribute " + attrName + " in shadow " + ModelClientUtil.toString(shadow),
                        attrVal, jaxbElement.getValue().toString());
            }
        } else {
            AssertJUnit.fail("Unexpected thing " + any + " in shadow attributes");
        }
    }
}

From source file:com.cloud.test.regression.ApiCommand.java

public void setVerifyParam(HashMap<String, String> param) {
    NodeList returnLst = this.xmlCommand.getElementsByTagName("returnvalue");
    if (returnLst != null) {
        for (int m = 0; m < returnLst.getLength(); m++) {
            Element returnElement = (Element) returnLst.item(m);
            if (returnElement.getAttribute("list").equals("true")) {
                this.list = true;
                NodeList elementLst = returnElement.getElementsByTagName("element");
                this.listId = (Element) elementLst.item(0);
                NodeList elementName = returnElement.getElementsByTagName("name");
                this.listName = (Element) elementName.item(0);
            } else {
                this.list = false;
            }/* ww  w.  j a  v a 2  s .  c  om*/

            NodeList itemLst1 = returnElement.getElementsByTagName("item");
            if (itemLst1 != null) {
                for (int n = 0; n < itemLst1.getLength(); n++) {
                    Node item = itemLst1.item(n);
                    if (item.getNodeType() == Node.ELEMENT_NODE) {
                        Element itemElement = (Element) item;
                        // get parameter name
                        NodeList itemName = itemElement.getElementsByTagName("name");
                        Element itemNameElement = (Element) itemName.item(0);

                        // Get parameters for future use
                        if (itemElement.getAttribute("setparam").equals("true")) {
                            NodeList itemVariable = itemElement.getElementsByTagName("param");
                            Element itemVariableElement = (Element) itemVariable.item(0);
                            setParam.put(itemVariableElement.getTextContent(),
                                    itemNameElement.getTextContent());
                            this.required = true;
                        } else if (itemElement.getAttribute("getparam").equals("true")) {
                            NodeList itemVariable = itemElement.getElementsByTagName("param");
                            Element itemVariableElement = (Element) itemVariable.item(0);
                            this.verifyParam.put(itemNameElement.getTextContent(),
                                    param.get(itemVariableElement.getTextContent()));
                        } else if ((itemElement.getElementsByTagName("value") != null)
                                && (itemElement.getElementsByTagName("value").getLength() != 0)) {
                            NodeList itemVariable = itemElement.getElementsByTagName("value");
                            Element itemVariableElement = (Element) itemVariable.item(0);
                            this.verifyParam.put(itemNameElement.getTextContent(),
                                    itemVariableElement.getTextContent());
                        } else {
                            this.verifyParam.put(itemNameElement.getTextContent(), "no value");
                        }
                    }
                }
            }
        }
    }
}

From source file:com.inbravo.scribe.rest.service.crm.ms.MSCRMMessageFormatUtils.java

public static final String[] getRegardingObjectInfo(final ScribeObject cADbject) {

    /* Iterate on the Element list and create SOAP object */
    for (final Element element : cADbject.getXmlContent()) {

        if (logger.isDebugEnabled()) {
            logger.debug(/*from w  ww .j  ava  2  s .  c o m*/
                    "----Inside getRegardingObjectInfo: node: '" + element.getNodeName() + "' with value : '"
                            + element.getTextContent() + "' & Type: '" + element.getAttribute("type") + "'");
        }

        /* Check for regardingobjectid node */
        if (element.getNodeName().equalsIgnoreCase(regardingObjectidConst)) {

            String schema = null;

            /* Find schema */
            if (MSCRMObjectType.Account.toString().equalsIgnoreCase(element.getAttribute("type"))) {

                schema = MSCRMSchemaType.Account_Tasks.toString();

            } else if (MSCRMObjectType.Contact.toString().equalsIgnoreCase(element.getAttribute("type"))) {

                schema = MSCRMSchemaType.Contact_Tasks.toString();

            } else if (MSCRMObjectType.Lead.toString().equalsIgnoreCase(element.getAttribute("type"))) {

                schema = MSCRMSchemaType.Lead_Tasks.toString();

            } else if (MSCRMObjectType.Opportunity.toString().equalsIgnoreCase(element.getAttribute("type"))) {

                schema = MSCRMSchemaType.Opportunity_Tasks.toString();

            } else {
                /* Throw user error */
                throw new ScribeException(ScribeResponseCodes._1003
                        + "Following object type is not supported for object association by Scribe");
            }
            return new String[] { element.getTextContent(), element.getAttribute("type"), schema };

        } else {

            /* Ignore other elements */
            continue;
        }
    }

    return null;
}

From source file:com.evolveum.midpoint.testing.wstest.AbstractWebserviceTest.java

protected void assertNoAttribute(ShadowType shadow, QName attrName) {
    ShadowAttributesType attributes = shadow.getAttributes();
    for (Object any : attributes.getAny()) {
        if (any instanceof Element) {
            Element element = (Element) any;
            if (DOMUtil.getQName(element).equals(attrName)) {
                AssertJUnit.fail("Unexpected attribute " + attrName + " in shadow "
                        + ModelClientUtil.toString(shadow) + ": " + element.getTextContent());
            }/*from   ww w  . j a va  2s . c  o  m*/
        } else if (any instanceof JAXBElement<?>) {
            JAXBElement<?> jaxbElement = (JAXBElement<?>) any;
            if (jaxbElement.getName().equals(attrName)) {
                AssertJUnit.fail("Unexpected attribute " + attrName + " in shadow "
                        + ModelClientUtil.toString(shadow) + ": " + jaxbElement.getValue());
            }
        } else {
            AssertJUnit.fail("Unexpected thing " + any + " in shadow attributes");
        }
    }

}