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.persistent.cloudninja.service.impl.RunningInstancesJSONDataServiceImpl.java

/**
 * Parse the response from deployment monitoring and get role name, instance name and instance status.
 * @param response The XML response of deployment monitoring task.
 * @return List of InstanceHealthRoleInstanceEntity
 * @throws ParserConfigurationException/*from  w w w  .j  av a 2 s .c  o m*/
 * @throws SAXException
 * @throws IOException
 * @throws XPathExpressionException
 */
private List<InstanceHealthRoleInstanceEntity> parseResponse(StringBuffer response)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    DocumentBuilder documentBuilder = null;
    Document document = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setIgnoringElementContentWhitespace(true);
    documentBuilder = documentBuilderFactory.newDocumentBuilder();
    document = documentBuilder.parse(new InputSource(new StringReader(response.toString())));

    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    NodeList roleNameList = (NodeList) xPath.evaluate("/Deployment/RoleInstanceList/RoleInstance/RoleName",
            document, XPathConstants.NODESET);
    NodeList instanceNameList = (NodeList) xPath.evaluate(
            "/Deployment/RoleInstanceList/RoleInstance/InstanceName", document, XPathConstants.NODESET);
    NodeList instanceStatusList = (NodeList) xPath.evaluate(
            "/Deployment/RoleInstanceList/RoleInstance/InstanceStatus", document, XPathConstants.NODESET);

    List<InstanceHealthRoleInstanceEntity> list = new ArrayList<InstanceHealthRoleInstanceEntity>();
    for (int index = 0; index < roleNameList.getLength(); index++) {
        Element roleElement = (Element) roleNameList.item(index);
        Element instanceElement = (Element) instanceNameList.item(index);
        Element statusElement = (Element) instanceStatusList.item(index);

        InstanceHealthRoleInstanceEntity roleInstanceEntity = new InstanceHealthRoleInstanceEntity();
        roleInstanceEntity.setRoleName(roleElement.getTextContent());
        roleInstanceEntity.setInstanceName(instanceElement.getTextContent());
        roleInstanceEntity.setInstanceStatus(statusElement.getTextContent());
        list.add(roleInstanceEntity);
    }
    return list;
}

From source file:com.google.publicalerts.cap.CapJsonBuilder.java

private void toJsonObjectInner(Element element, JSONObject object, Map<String, Set<String>> repeatedFieldsMap)
        throws JSONException {
    NodeList nl = element.getChildNodes();
    Set<String> repeatedFields = repeatedFieldsMap.get(element.getNodeName());
    for (int i = 0; i < nl.getLength(); i++) {
        Element child = (Element) nl.item(i);
        int gcLength = child.getChildNodes().getLength();
        if (gcLength == 0) {
            continue;
        }//from  w ww  .  j av a2  s. c o  m
        String nodeName = child.getNodeName();
        if (repeatedFields != null && repeatedFields.contains(nodeName)) {
            if (gcLength == 1 && child.getChildNodes().item(0).getNodeType() == Node.TEXT_NODE) {
                object.append(nodeName, child.getTextContent());
            } else {
                JSONObject childObj = new JSONObject();
                toJsonObjectInner(child, childObj, repeatedFieldsMap);
                object.append(nodeName, childObj);
            }
        } else {
            if (gcLength == 1 && child.getChildNodes().item(0).getNodeType() == Node.TEXT_NODE) {
                object.put(child.getNodeName(), child.getTextContent());
            } else {
                JSONObject childObj = new JSONObject();
                toJsonObjectInner(child, childObj, repeatedFieldsMap);
                object.put(child.getNodeName(), childObj);
            }
        }
    }
}

From source file:greenfoot.export.mygame.MyGameClient.java

private void parseScenarioXml(ScenarioInfo info, InputStream xmlStream) throws IOException {
    try {//from www  .j av  a  2 s. co m
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder dbuilder = dbf.newDocumentBuilder();

        Document doc = dbuilder.parse(xmlStream);
        Element root = doc.getDocumentElement();
        if (root == null || !root.getTagName().equals("scenario")) {
            return;
        }

        NodeList children = root.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node childNode = children.item(i);
            if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) childNode;
                if (element.getTagName().equals("shortdescription")) {
                    info.setShortDescription(element.getTextContent());
                } else if (element.getTagName().equals("longdescription")) {
                    info.setLongDescription(element.getTextContent());
                } else if (element.getTagName().equals("taglist")) {
                    info.setTags(parseTagListXmlElement(element));
                } else if (element.getTagName().equals("webpage")) {
                    info.setUrl(element.getTextContent());
                } else if (element.getTagName().equals("hassource")) {
                    info.setHasSource(element.getTextContent().equals("true"));
                }
            }
        }
    } catch (ParserConfigurationException pce) {
        // what the heck do we do with this?
    } catch (SAXException saxe) {

    }
}

From source file:com.fujitsu.dc.test.jersey.box.ServiceSourceTest.java

/**
 * PROPPATCH????.//from www . jav a  2  s  .c om
 * @param doc ??XML
 * @param resorce PROPPATCH??
 * @param map ???KeyValue
 *        Key?Value????????
 *        Valuenull???Key??????remove????
 */
private void checkProppatchResponse(Element doc, String resorce, Map<String, String> map) {
    NodeList response = doc.getElementsByTagName("response");
    assertEquals(1, response.getLength());
    Element node = (Element) response.item(0);
    assertEquals(
            resorce,
            node.getElementsByTagName("href").item(0).getFirstChild().getNodeValue());
    assertEquals(
            "HTTP/1.1 200 OK",
            node.getElementsByTagName("status").item(0).getFirstChild().getNodeValue());

    for (Iterator<String> it = map.keySet().iterator(); it.hasNext();) {
        Object key = it.next();
        Object value = map.get(key);
        String textContext = null;
        NodeList tmp = node.getElementsByTagName("prop").item(0).getChildNodes();
        for (int i = 0; i < tmp.getLength(); i++) {
            Node child = tmp.item(i);
            if (child instanceof Element) {
                Element childElement = (Element) child;
                if (childElement.getLocalName().equals(key)) {
                    textContext = childElement.getTextContent();
                    break;
                }
            }
        }
        assertEquals(value, textContext);
    }
}

From source file:com.evolveum.midpoint.schema.processor.MidPointSchemaDefinitionFactory.java

private PrismPropertyDefinition createResourceAttributeDefinition(QName elementName, QName typeName,
        PrismContext prismContext, XSAnnotation annotation) throws SchemaException {
    ResourceAttributeDefinition attrDef = new ResourceAttributeDefinition(elementName, typeName, prismContext);

    // nativeAttributeName
    Element nativeAttrElement = SchemaProcessorUtil.getAnnotationElement(annotation,
            MidPointConstants.RA_NATIVE_ATTRIBUTE_NAME);
    String nativeAttributeName = nativeAttrElement == null ? null : nativeAttrElement.getTextContent();
    if (!StringUtils.isEmpty(nativeAttributeName)) {
        attrDef.setNativeAttributeName(nativeAttributeName);
    }//from   www .j  a v a2 s.c o m

    // frameworkAttributeName
    Element frameworkAttrElement = SchemaProcessorUtil.getAnnotationElement(annotation,
            MidPointConstants.RA_FRAMEWORK_ATTRIBUTE_NAME);
    String frameworkAttributeName = frameworkAttrElement == null ? null : frameworkAttrElement.getTextContent();
    if (!StringUtils.isEmpty(frameworkAttributeName)) {
        attrDef.setFrameworkAttributeName(frameworkAttributeName);
    }

    // returnedByDefault
    attrDef.setReturnedByDefault(SchemaProcessorUtil.getAnnotationBoolean(annotation,
            MidPointConstants.RA_RETURNED_BY_DEFAULT_NAME));

    return attrDef;
}

From source file:de.eorganization.hoopla.server.servlets.TemplateImportServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    DecisionTemplate newDecisionTemplate = new DecisionTemplate();
    DecisionTemplate decisionTemplate = null;
    try {/*from w  w w  .ja va2s  . co m*/

        ServletFileUpload upload = new ServletFileUpload();
        resp.setContentType("text/plain");

        FileItemIterator itemIterator = upload.getItemIterator(req);
        while (itemIterator.hasNext()) {
            FileItemStream item = itemIterator.next();
            if (item.isFormField() && "substituteTemplateId".equals(item.getFieldName())) {
                log.warning("Got a form field: " + item.getFieldName());

                String itemContent = IOUtils.toString(item.openStream());
                try {
                    decisionTemplate = new HooplaServiceImpl()
                            .getDecisionTemplate(new Long(itemContent).longValue());
                    new HooplaServiceImpl().deleteDecisionTemplate(decisionTemplate);
                } catch (Exception e) {
                    log.log(Level.WARNING, e.getLocalizedMessage(), e);
                }
                if (decisionTemplate == null)
                    newDecisionTemplate.setKeyId(new Long(itemContent).longValue());
                else
                    newDecisionTemplate.setKeyId(decisionTemplate.getKeyId());
            } else {
                InputStream stream = item.openStream();

                log.info("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName());

                Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(stream);

                // doc.getDocumentElement().normalize();

                Element decisionElement = doc.getDocumentElement();
                String rootName = decisionElement.getNodeName();
                if (rootName.equals("decision")) {
                    isDecisionTemplate = false;
                } else if (rootName.equals("decisionTemplate")) {
                    isDecisionTemplate = true;
                } else {
                    log.warning("This XML Document has a wrong RootElement: " + rootName
                            + ". It should be <decision> or <decisionTemplate>.");
                }

                NodeList decisionNodes = decisionElement.getChildNodes();
                for (int i = 0; i < decisionNodes.getLength(); i++) {
                    Node node = decisionNodes.item(i);

                    if (node instanceof Element) {
                        Element child = (Element) node;
                        if (child.getNodeName().equals("name") && !child.getTextContent().equals("")) {
                            newDecisionTemplate.setName(child.getTextContent());
                            log.info("Parsed decision name: " + newDecisionTemplate.getName());
                        }
                        if (child.getNodeName().equals("description") && !child.getTextContent().equals("")) {
                            newDecisionTemplate.setDescription(child.getTextContent());
                            log.info("Parsed decision description: " + newDecisionTemplate.getDescription());
                        }
                        if (isDecisionTemplate && child.getNodeName().equals("templateName")) {
                            newDecisionTemplate.setTemplateName(child.getTextContent());
                            log.info("Parsed decision TemplateName: " + newDecisionTemplate.getTemplateName());
                        }
                        if (child.getNodeName().equals("alternatives")) {
                            parseAlternatives(child.getChildNodes(), newDecisionTemplate);
                        }
                        if (child.getNodeName().equals("goals")) {
                            parseGoals(child.getChildNodes(), newDecisionTemplate);
                        }
                        if (child.getNodeName().equals("importanceGoals")) {
                            parseGoalImportances(child.getChildNodes(), newDecisionTemplate);
                        }
                    }
                }

                log.info("Fully parsed XML Upload: " + newDecisionTemplate.toString());

            }
        }

    } catch (Exception ex) {
        log.log(Level.WARNING, ex.getLocalizedMessage(), ex);
        resp.sendError(400);
        return;
    }

    try {
        new HooplaServiceImpl().storeDecisionTemplate(newDecisionTemplate);
    } catch (Exception e) {
        log.log(Level.WARNING, e.getLocalizedMessage(), e);
        resp.sendError(500);
        return;
    }

    log.info("returning to referer " + req.getHeader("referer"));
    resp.sendRedirect(
            req.getHeader("referer") != null && !"".equals(req.getHeader("referer")) ? req.getHeader("referer")
                    : "localhost:8088");
}

From source file:com.clustercontrol.infra.util.WinRs.java

public String openShell(int lifeTime, String workingDirectory) throws UnknownHostException, WsmanException {
    //lifetime: second
    WsmanConnection conn = createConnection();
    ManagedReference ref = conn.newReference(RESOURCE_URI_CMD);

    ManagedInstance shellInst = ref.createMethod(NAMESPACE_SHELL, "Shell");
    shellInst.addProperty("Lifetime", String.format("PT%dS", lifeTime));
    shellInst.addProperty("InputStreams", "stdin");
    shellInst.addProperty("OutputStreams", "stdout stderr");
    if (workingDirectory != null) {
        shellInst.addProperty("WorkingDirectory", workingDirectory);
    }//from   w  w  w . ja v a 2 s.c o  m

    ManagedInstance resp = ref.create(shellInst);
    NodeList nodeList = resp.getBody().getElementsByTagNameNS("http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd",
            "Selector");
    Element shellIdElement = null;
    for (int i = 0; i < nodeList.getLength(); i++) {
        Element node = (Element) nodeList.item(i);
        if ("ShellId".equals(node.getAttribute("Name"))) {
            shellIdElement = node;
            break;
        }
    }
    if (shellIdElement == null) {
        return null;
    }

    return shellIdElement.getTextContent();
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static boolean isEmpty(Element element) {
    if (element == null) {
        return true;
    }//from ww w .  j  a v a  2s . c o m
    if (hasChildElements(element)) {
        return false;
    }
    if (isNil(element)) {
        return true;
    }
    return StringUtils.isBlank(element.getTextContent());
}

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

public String determineLdapSingleAttributeValue(Element dnElement, String attributeName,
        Collection<String> values) throws NamingException {
    if (values == null || values.isEmpty()) {
        // Shortcut. This is maybe the most common case. We want to return quickly and we also need to avoid more checks later.
        return null;
    }/* ww  w.j av a 2 s . c o m*/
    if (dnElement == null) {
        throw new IllegalArgumentException("No dn argument specified");
    }
    return functions.determineLdapSingleAttributeValue(dnElement.getTextContent(), attributeName, values);
}

From source file:edu.lternet.pasta.datapackagemanager.LevelOneEMLFactory.java

/**
 * Boolean to determine whether this data package contains a
 * Level-1 contact element. If it does, we don't want to add
 * a duplicate element.//  www  . j a v  a 2  s .  c  o  m
 * 
  * @param   emlDocument  the Level-0 EML Document
 * @return  true if this data package has a Level-1 contact element,
 *          else false
 */
public boolean hasLevelOneContact(Document emlDocument) throws TransformerException {
    boolean hasLevelOneContact = false;
    CachedXPathAPI xpathapi = new CachedXPathAPI();

    // Parse the access elements
    NodeList datasetContacts = xpathapi.selectNodeList(emlDocument, CONTACT_PATH);
    if (datasetContacts != null) {
        for (int i = 0; i < datasetContacts.getLength(); i++) {
            boolean hasPositionName = false;
            boolean hasOrganizationName = false;
            Element contactElement = (Element) datasetContacts.item(i);

            NodeList positionNames = contactElement.getElementsByTagName("positionName");
            if (positionNames != null) {
                for (int j = 0; j < positionNames.getLength(); j++) {
                    Element positionNameElement = (Element) positionNames.item(j);
                    String positionName = positionNameElement.getTextContent();
                    if ("Information Manager".equals(positionName)) {
                        hasPositionName = true;
                    }
                }
            }

            NodeList organizationNames = contactElement.getElementsByTagName("organizationName");
            if (organizationNames != null) {
                for (int j = 0; j < organizationNames.getLength(); j++) {
                    Element organizationNameElement = (Element) organizationNames.item(j);
                    String organizationName = organizationNameElement.getTextContent();
                    if ("Environmental Data Initiative".equals(organizationName)) {
                        hasOrganizationName = true;
                    }
                }
            }

            hasLevelOneContact = hasLevelOneContact || (hasPositionName && hasOrganizationName);
        }
    }

    return hasLevelOneContact;
}