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.athena.chameleon.engine.core.analyzer.parser.PomXMLParser.java

/**
 * <pre>/*w w  w.  j  a v  a2 s  .  c o  m*/
 * 
 * </pre>
 * @param model
 * @param path
 * @return
 * @throws IOException 
 * @throws JAXBException 
 * @throws InvocationTargetException 
 * @throws IllegalAccessException 
 */
private Object checkDependency(Object model, String path)
        throws JAXBException, IOException, IllegalAccessException, InvocationTargetException {
    Dependencies dependencies = ((Model) model).getDependencies();
    List<Dependency> dependencyList = dependencies.getDependency();

    boolean isChanged = false;
    MavenDependency mavenDependency = null;
    for (Dependency dependency : dependencyList) {
        mavenDependency = new MavenDependency();
        BeanUtils.copyProperties(mavenDependency, dependency);

        if (mavenDependency.getVersion().startsWith("${") && mavenDependency.getVersion().endsWith("}")) {
            List<Element> elementList = ((Model) model).getProperties().getAny();

            for (Element element : elementList) {
                if (StringUtils.equals(
                        mavenDependency.getVersion().substring(2, mavenDependency.getVersion().length() - 1),
                        element.getNodeName())) {
                    mavenDependency.setVersion(element.getTextContent());
                    break;
                }
            }
        }

        analyzeDefinition.getMavenDependencyList().add(mavenDependency);

        if (dependency.getGroupId().equals("xerces") && dependency.getArtifactId().equals("xercesImpl")
                && !StringUtils.equals(dependency.getScope(), "provided")) {
            isChanged = true;
            dependency.setScope("provided");

            mavenDependency = new MavenDependency();
            BeanUtils.copyProperties(mavenDependency, dependency);
            analyzeDefinition.getModifiedMavenDependencyList().add(mavenDependency);
        } else if (dependency.getGroupId().equals("xml-apis") && dependency.getArtifactId().equals("xml-apis")
                && !StringUtils.equals(dependency.getScope(), "provided")) {
            isChanged = true;
            dependency.setScope("provided");

            mavenDependency = new MavenDependency();
            BeanUtils.copyProperties(mavenDependency, dependency);
            analyzeDefinition.getModifiedMavenDependencyList().add(mavenDependency);
        } else if (dependency.getGroupId().equals("xalan") && dependency.getArtifactId().equals("xalan")
                && !StringUtils.equals(dependency.getScope(), "provided")) {
            isChanged = true;
            dependency.setScope("provided");

            mavenDependency = new MavenDependency();
            BeanUtils.copyProperties(mavenDependency, dependency);
            analyzeDefinition.getModifiedMavenDependencyList().add(mavenDependency);
        }
    }

    if (isChanged) {
        // pom.xml 
        String xmlData = JaxbUtils.marshal(Model.class.getPackage().getName(), model,
                new String[] {
                        "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" },
                true);
        rewrite(new File(path, "pom.xml"), xmlData);
        logger.debug("pom.xml has been modified.\n{}", xmlData);

        CommonAnalyze commonAnalyze = null;
        commonAnalyze = new CommonAnalyze();
        commonAnalyze.setItem(analyzeDefinition.getMavenProjectList().get(0).getItem());
        commonAnalyze.setLocation(analyzeDefinition.getMavenProjectList().get(0).getLocation());
        commonAnalyze.setContents(xmlData);

        analyzeDefinition.getMavenProjectList().add(commonAnalyze);
    }

    return model;
}

From source file:com.k42b3.neodym.Services.java

private void request(String url) throws Exception {
    // request//from  w w  w. jav a2  s.c  om
    Document doc = http.requestXml(Http.GET, url);

    // parse services
    NodeList serviceList = doc.getElementsByTagName("Service");

    for (int i = 0; i < serviceList.getLength(); i++) {
        Node serviceNode = serviceList.item(i);
        Element serviceElement = (Element) serviceNode;

        NodeList typeElementList = serviceElement.getElementsByTagName("Type");
        Element uriElement = (Element) serviceElement.getElementsByTagName("URI").item(0);

        if (typeElementList.getLength() > 0 && uriElement != null) {
            ArrayList<String> types = new ArrayList<String>();

            for (int j = 0; j < typeElementList.getLength(); j++) {
                types.add(typeElementList.item(j).getTextContent());
            }

            String uri = uriElement.getTextContent();

            services.add(new ServiceItem(uri, types));
        }
    }

    logger.info("Found " + services.size() + " services");
}

From source file:org.openhmis.oauth2.OAuth2Utils.java

public void parseXMLDoc(Element element, Document doc, Map<String, String> oauthResponse) {
    NodeList child = null;/*from w w  w. j  a  va 2  s . com*/
    if (element == null) {
        child = doc.getChildNodes();

    } else {
        child = element.getChildNodes();
    }
    for (int j = 0; j < child.getLength(); j++) {
        if (child.item(j).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
            org.w3c.dom.Element childElement = (org.w3c.dom.Element) child.item(j);
            if (childElement.hasChildNodes()) {
                System.out.println(childElement.getTagName() + " : " + childElement.getTextContent());
                oauthResponse.put(childElement.getTagName(), childElement.getTextContent());
                parseXMLDoc(childElement, null, oauthResponse);
            }

        }
    }
}

From source file:at.ac.tuwien.big.testsuite.impl.validator.XhtmlValidator.java

@Override
public ValidationResult validate(File fileToValidate, String exerciseId) throws Exception {
    HttpPost request = new HttpPost(W3C_XHTML_VALIDATOR_URL);
    List<ValidationResultEntry> validationResultEntries = new ArrayList<>();

    try {//  www.  java 2  s.c  om
        MultipartEntity multipartEntity = new MultipartEntity();
        multipartEntity.addPart("uploaded_file", new FileBody(fileToValidate, "text/html"));
        multipartEntity.addPart("charset", new StringBody("(detect automatically)"));
        multipartEntity.addPart("doctype", new StringBody("Inline"));
        multipartEntity.addPart("group", new StringBody("0"));

        request.setEntity(multipartEntity);
        Document doc = httpClient.execute(request, new DomResponseHandler(httpClient, request));

        String doctype = DomUtils.textByXpath(doc.getDocumentElement(),
                "//form[@id='form']/table//tr[4]/td[1]");

        if (!"XHTML 1.1".equals(doctype.trim()) && !doctype.contains("XHTML+ARIA 1.0")) {
            validationResultEntries.add(new DefaultValidationResultEntry("Doctype Validation",
                    "The given document is not XHTML 1.1 compatible, instead the guessed doctype is '" + doctype
                            + "'",
                    ValidationResultEntryType.ERROR));
        }

        Document fileToValidateDocument = null;

        Element warningsContainer = DomUtils.byId(doc.getDocumentElement(), "warnings");

        if (warningsContainer != null) {
            for (Element warningChildElement : DomUtils.asList(warningsContainer.getChildNodes())) {
                if (IGNORED_MESSAGES.contains(warningChildElement.getAttribute("id"))) {
                    continue;
                }

                ValidationResultEntryType type = getEntryType(warningChildElement.getAttribute("class"));
                String title = getTitle(
                        DomUtils.firstByClass(warningChildElement.getElementsByTagName("span"), "msg"));
                StringBuilder descriptionSb = new StringBuilder();

                for (Element descriptionElement : DomUtils.listByXpath(warningChildElement,
                        ".//p[position()>1]")) {
                    descriptionSb.append(descriptionElement.getTextContent());
                }

                validationResultEntries
                        .add(new DefaultValidationResultEntry(title, descriptionSb.toString(), type));
            }
        }

        Element errorsContainer = DomUtils.byId(doc.getDocumentElement(), "error_loop");

        if (errorsContainer != null) {
            for (Element errorChildElement : DomUtils.asList(errorsContainer.getChildNodes())) {
                ValidationResultEntryType type = getEntryType(errorChildElement.getAttribute("class"));
                StringBuilder titleSb = new StringBuilder();
                NodeList errorEms = errorChildElement.getElementsByTagName("em");

                if (errorEms.getLength() > 0) {
                    titleSb.append(getTitle((Element) errorEms.item(0)));
                    titleSb.append(": ");
                }

                titleSb.append(
                        getTitle(DomUtils.firstByClass(errorChildElement.getElementsByTagName("span"), "msg")));
                StringBuilder descriptionSb = new StringBuilder();

                for (Element descriptionElement : DomUtils.listByXpath(errorChildElement, ".//div/p")) {
                    descriptionSb.append(descriptionElement.getTextContent());
                }

                String title = titleSb.toString();

                if (TestsuiteConstants.EX_ID_LAB3.equals(exerciseId)) {
                    // This is more a hack than anything else but we have to ignore the errors that were produced by JSF specific artifacts.
                    // We basically extract the line and column number from the reported errors and look for the 2 elements that match these
                    // numbers and check if they really are the input elements produced by forms that cant be wrapped by block containers.
                    // More specifically we check for inputs with type hidden, one is for the ViewState of JSF and the other is for recognition
                    // of the form that was submitted.
                    Matcher matcher = LINE_AND_COLUMN_NUMBER_PATTERN.matcher(title);

                    if (title.contains("document type does not allow element \"input\" here")
                            && matcher.matches()) {
                        if (fileToValidateDocument == null) {
                            fileToValidateDocument = DomUtils.createDocument(fileToValidate);
                        }

                        boolean excludeEntry = false;
                        int expectedLineNumber = Integer.parseInt(matcher.group(1));
                        int expectedColumnNumber = Integer.parseInt(matcher.group(2));

                        try (BufferedReader reader = new BufferedReader(
                                new InputStreamReader(new FileInputStream(fileToValidate)))) {
                            String line;

                            while ((line = reader.readLine()) != null) {
                                if (--expectedLineNumber == 0) {
                                    Matcher lineMatcher = HIDDEN_FORM_INPUT_PATTERN.matcher(line);

                                    if (lineMatcher.matches()) {
                                        MatchResult matchResult = lineMatcher.toMatchResult();
                                        if (matchResult.start(1) <= expectedColumnNumber
                                                && matchResult.end(1) >= expectedColumnNumber) {
                                            excludeEntry = true;
                                            break;
                                        }
                                    }

                                    lineMatcher = HIDDEN_VIEW_STATE_INPUT_PATTERN.matcher(line);

                                    if (lineMatcher.matches()) {
                                        MatchResult matchResult = lineMatcher.toMatchResult();
                                        if (matchResult.start(1) <= expectedColumnNumber
                                                && matchResult.end(1) >= expectedColumnNumber) {
                                            excludeEntry = true;
                                            break;
                                        }
                                    }

                                    System.out.println("Could not match potential wrong error.");

                                    break;
                                }
                            }
                        }

                        if (excludeEntry) {
                            continue;
                        }
                    }
                }

                validationResultEntries
                        .add(new DefaultValidationResultEntry(title, descriptionSb.toString(), type));
            }
        }
    } finally {
        request.releaseConnection();
    }

    return new DefaultValidationResult("XHTML Validation", fileToValidate.getName(),
            new DefaultValidationResultType("XHTML"), validationResultEntries);
}

From source file:importer.handler.post.stages.Discriminator.java

/**
 * Does this element only contain deleted text?
 * @param elem the element in question/*  w  ww  .  j ava2 s. c o  m*/
 * @return true if it is, else false
 */
boolean isDeleted(Element elem) {
    boolean result = true;
    String eName = elem.getNodeName();
    if (eName.equals(del))
        result = true;
    else {
        String text = elem.getTextContent();
        int textLen = (text != null) ? text.length() : 0;
        int childLen = 0;
        Element child = firstChild(elem);
        while (child != null && !result) {
            String childText = elem.getTextContent();
            if (isDeleted(child))
                childLen += (childText != null) ? childText.length() : 0;
            child = nextSibling(child, true);
        }
        result = childLen == textLen;
    }
    return result;
}

From source file:ws.argo.Responder.Responder.java

private ProbePayloadBean parseProbePayload(String payload) throws SAXException, IOException {

    ProbePayloadBean probePayload = new ProbePayloadBean();

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setCoalescing(false);
    DocumentBuilder builder = null;
    try {/* ww  w  . ja v a 2 s .  com*/
        builder = builderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }

    InputStream is = IOUtils.toInputStream(payload);
    Document document = builder.parse(is);

    Element probe = (Element) document.getElementsByTagName(PROBE).item(0);

    probePayload.probeID = probe.getAttribute("id");
    probePayload.contractID = probe.getAttribute("contractID");

    ArrayList<String> serviceContractIDs = new ArrayList<String>();

    NodeList serviceContractNodes = probe.getElementsByTagName("serviceContractID");

    probePayload.respondToURL = ((Element) probe.getElementsByTagName("respondTo").item(0)).getTextContent();
    probePayload.respondToPayloadType = ((Element) probe.getElementsByTagName("respondToPayloadType").item(0))
            .getTextContent();

    for (int i = 0; i < serviceContractNodes.getLength(); i++) {
        Element serviceContractID = (Element) serviceContractNodes.item(i);

        String contractID = serviceContractID.getTextContent();
        serviceContractIDs.add(contractID);

    }
    probePayload.serviceContractIDs = serviceContractIDs;

    return probePayload;

}

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

private WinRsCommandOutput getCommandOutputFromResponse(String commandId, ManagedInstance resp) {

    StringBuilder stdout = new StringBuilder();
    StringBuilder stderr = new StringBuilder();
    long exitCode = 0;
    WinRsCommandState state = WinRsCommandState.Running;

    NodeList nodeList = resp.getBody().getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Element node = (Element) nodeList.item(i);
        if (!commandId.equals(node.getAttribute("CommandId"))) {
            continue;
        }//from  w  w  w .ja va2 s.  c o  m

        if ("Stream".equals(node.getLocalName())) {
            if ("stdout".equals(node.getAttribute("Name"))) {
                stdout.append(new String(Base64.decodeBase64(node.getTextContent())));
            } else if ("stderr".equals(node.getAttribute("Name"))) {
                stderr.append(new String(Base64.decodeBase64(node.getTextContent())));
            }
        } else if ("CommandState".equals(node.getLocalName())) {
            if (node.getAttribute("State").endsWith("Done")) {
                exitCode = Long.parseLong(node.getChildNodes().item(0).getTextContent());
                state = WinRsCommandState.Done;
            } else if (node.getAttribute("State").endsWith("Running")) {
                state = WinRsCommandState.Running;
            } else {
                state = WinRsCommandState.Pending;
            }
        }
    }

    return new WinRsCommandOutput(stdout.toString(), stderr.toString(), exitCode, state);
}

From source file:eu.elf.license.LicenseParser.java

public static UserLicenses parseUserLicensesAsLicenseModelGroupList(String xml, String userid)
        throws Exception {
    UserLicenses userLicenses = new UserLicenses();

    try {//from  w  w w . jav a 2 s  .co  m
        Document xmlDoc = createXMLDocumentFromString(xml);

        Element ordersElement = (Element) xmlDoc
                .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "orders").item(0);
        NodeList orderList = ordersElement.getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "order");

        for (int i = 0; i < orderList.getLength(); i++) {
            UserLicense userLicense = new UserLicense();
            try {
                Element orderElement = (Element) orderList.item(i);
                Element productionElement = (Element) orderElement
                        .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "production").item(0);
                Element productionItemElement = (Element) productionElement
                        .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "productionItem").item(0);
                Element LicenseReferenceElement = (Element) productionItemElement
                        .getElementsByTagNameNS("http://www.52north.org/license/0.3.2", "LicenseReference")
                        .item(0);
                Element attributeStatementElement = (Element) LicenseReferenceElement
                        .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "AttributeStatement")
                        .item(0);

                NodeList attributeElementList = attributeStatementElement
                        .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Attribute");

                for (int j = 0; j < attributeElementList.getLength(); j++) {
                    Element attributeElement = (Element) attributeElementList.item(j);
                    Element AttributeValueElement = (Element) attributeElement
                            .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "AttributeValue")
                            .item(0);

                    NamedNodeMap attributeMap = attributeElement.getAttributes();
                    for (int k = 0; k < attributeMap.getLength(); k++) {
                        Attr attrs = (Attr) attributeMap.item(k);
                        if ("Name".equals(attrs.getNodeName())) {

                            if ("urn:opengeospatial:ows4:geodrm:NotOnOrAfter".equals(attrs.getNodeValue())) {
                                userLicense.setValidTo(AttributeValueElement.getTextContent());
                            }
                            if ("urn:opengeospatial:ows4:geodrm:LicenseID".equals(attrs.getNodeValue())) {
                                userLicense.setLicenseId(AttributeValueElement.getTextContent());
                            }
                        }
                    }
                    userLicense.setSecureServiceURL("/httpauth/licid-" + userLicense.getLicenseId());
                }

                Element orderContentElement = (Element) orderElement
                        .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "orderContent").item(0);
                Element catalogElement = (Element) orderContentElement
                        .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "catalog").item(0);
                NodeList productGroupElementList = catalogElement
                        .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "productGroup");

                // setup user license flags in models
                List<LicenseModelGroup> list = createLicenseModelGroupList(productGroupElementList);
                for (LicenseModelGroup group : list) {
                    group.setUserLicense(true);
                }
                userLicense.setLmgList(list);

                String WSS_URL = findWssUrlFromUserLicenseParamList(userLicense.getLmgList());

                //Remove WSS from the WSS-url string
                WSS_URL = WSS_URL.substring(0, WSS_URL.lastIndexOf("/"));

                userLicense.setSecureServiceURL(WSS_URL + userLicense.getSecureServiceURL());

                userLicenses.addUserLicense(userLicense);
            } catch (Exception e) {
                // Sometimes we get results without LicenseReference element: order/production/productionItem/LicenseReference
                // there might be valid results in the same response. Skipping the invalid ones.
                LOG.warn("Error while parsing user licenses");
            }

        }

        return userLicenses;

    } catch (Exception e) {
        throw e;
    }
}

From source file:net.sf.jabref.importer.fetcher.GVKParser.java

private String getSubfield(String a, Element datafield) {
    List<Element> liste = getChildren("subfield", datafield);

    for (Element subfield : liste) {
        if (subfield.getAttribute("code").equals(a)) {
            return (subfield.getTextContent());
        }/* ww w  . j  av  a2s.co  m*/
    }
    return null;
}

From source file:app.MainPanel.java

private HashMap readNodes(NodeList hList) {
    HashMap<String, Object> returnValue = new HashMap<>();

    for (int temp = 0; temp < hList.getLength(); temp++) {
        Node hNode = hList.item(temp);

        if (hNode.getNodeType() == Node.ELEMENT_NODE) {
            Element hElement = (Element) hNode;

            returnValue.put(hElement.getNodeName(), hElement.getTextContent());
        }/*from w  ww  .  ja va2 s.co  m*/
    }
    return returnValue;
}