Example usage for org.w3c.dom Node getTextContent

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

Introduction

In this page you can find the example usage for org.w3c.dom Node 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.espertech.esper.client.ConfigurationParser.java

private static void handleVariable(Configuration configuration, Element element) {
    String variableName = getRequiredAttribute(element, "name");
    String type = getRequiredAttribute(element, "type");

    Class variableType = JavaClassHelper.getClassForSimpleName(type);
    if (variableType == null) {
        throw new ConfigurationException(
                "Invalid variable type for variable '" + variableName + "', the type is not recognized");
    }/*from  w w w . j av a2  s.c  om*/

    Node initValueNode = element.getAttributes().getNamedItem("initialization-value");
    String initValue = null;
    if (initValueNode != null) {
        initValue = initValueNode.getTextContent();
    }

    boolean isConstant = false;
    if (getOptionalAttribute(element, "constant") != null) {
        isConstant = Boolean.parseBoolean(getOptionalAttribute(element, "constant"));
    }

    configuration.addVariable(variableName, variableType, initValue, isConstant);
}

From source file:com.wwpass.connection.WWPassConnection.java

private static InputStream getReplyData(final InputStream rawXMLInput)
        throws IOException, WWPassProtocolException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document dom;/*  w  ww  . j  av  a 2s.  co  m*/
    InputStream is = null;

    try {
        DocumentBuilder db = dbf.newDocumentBuilder();

        is = rawXMLInput;

        dom = db.parse(is);

        Element docEle = dom.getDocumentElement();

        Node result = docEle.getElementsByTagName("result").item(0);
        boolean res = result.getTextContent().equalsIgnoreCase("true");

        Element data = (Element) docEle.getElementsByTagName("data").item(0);
        String encoding = data.getAttributes().getNamedItem("encoding").getTextContent();
        String strData;
        byte[] bb;
        if ("base64".equalsIgnoreCase(encoding)) {
            bb = (new Base64()).decode(data.getTextContent());
            strData = new String(bb, Charset.forName("UTF-8"));
            if (!res) {
                throw new WWPassProtocolException("SPFE returned error: " + strData);
            }
            return new ByteArrayInputStream(bb);
        } else {
            strData = data.getTextContent();
            if (!res) {
                throw new WWPassProtocolException("SPFE returned error: " + strData);
            }
            return new ByteArrayInputStream(strData.getBytes());
        }

    } catch (ParserConfigurationException pce) {
        throw new WWPassProtocolException("Malformed SPFE reply: " + pce.getMessage());
    } catch (SAXException se) {
        throw new WWPassProtocolException("Malformed SPFE reply: " + se.getMessage());
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:edu.toronto.cs.cidb.ncbieutils.NCBIEUtilsAccessService.java

protected String getSummariesXML(List<String> idList) {
    // response example at
    // http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=omim&id=190685,605298,604829,602917,601088,602523,602259
    // response type: XML
    // return it/* w  ww .  jav  a 2s .co m*/
    String queryList = getSerializedList(idList);
    String url = composeURL(TERM_SUMMARY_QUERY_SCRIPT, TERM_SUMMARY_PARAM_NAME, queryList);
    try {
        Document response = readXML(url);
        NodeList nodes = response.getElementsByTagName("Item");
        // OMIM titles are all UPPERCASE, try to fix this
        for (int i = 0; i < nodes.getLength(); ++i) {
            Node n = nodes.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                if (n.getFirstChild() != null) {
                    n.replaceChild(response.createTextNode(fixCase(n.getTextContent())), n.getFirstChild());
                }
            }
        }
        Source source = new DOMSource(response);
        StringWriter stringWriter = new StringWriter();
        Result result = new StreamResult(stringWriter);
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.transform(source, result);
        return stringWriter.getBuffer().toString();
    } catch (Exception ex) {
        this.logger.error("Error while trying to retrieve summaries for ids " + idList + " "
                + ex.getClass().getName() + " " + ex.getMessage(), ex);
    }
    return "";
}

From source file:org.eclipse.lyo.testsuite.server.oslcv1tests.ServiceDescriptionTests.java

@Test
public void changeManagementServiceDescriptionHasValidCreationDialog() throws XPathException {
    //If ServiceDescription is oslc_cm, make sure it has a valid creation dialog child element
    Node cmRequest = (Node) OSLCUtils.getXPath().evaluate("//oslc_cm:changeRequests", doc, XPathConstants.NODE);
    if (cmRequest != null) {
        NodeList sD = (NodeList) OSLCUtils.getXPath()
                .evaluate("//oslc_cm:changeRequests/oslc_cm:creationDialog", doc, XPathConstants.NODESET);
        for (int i = 0; i < sD.getLength(); i++) {
            Node sQUrl = (Node) OSLCUtils.getXPath().evaluate(
                    "//oslc_cm:changeRequests/oslc_cm:creationDialog[" + (i + 1) + "]/oslc_cm:url", doc,
                    XPathConstants.NODE);
            assertNotNull(sQUrl);//ww w  .j a v a 2 s  . c  om
            Node sDtitle = (Node) OSLCUtils.getXPath().evaluate(
                    "//oslc_cm:changeRequests/oslc_cm:creationDialog[" + (i + 1) + "]/dc:title", doc,
                    XPathConstants.NODE);
            assertNotNull(sDtitle);
            assertFalse(sDtitle.getTextContent().isEmpty());
        }
    }
}

From source file:com.noelios.restlet.ext.jdbc.JdbcClientHelper.java

/**
 * Handles a call.// www  .  ja  v  a 2s .c o  m
 * 
 * @param request
 *            The request to handle.
 * @param response
 *            The response to update.
 */
@Override
public void handle(Request request, Response response) {
    Connection connection = null;

    if (request.getMethod().equals(Method.POST)) {
        try {
            // Parse the JDBC URI
            final String connectionURI = request.getResourceRef().toString();

            // Parse the request to extract necessary info
            final DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            final Document requestDoc = docBuilder.parse(request.getEntity().getStream());

            final Element rootElt = (Element) requestDoc.getElementsByTagName("request").item(0);
            final Element headerElt = (Element) rootElt.getElementsByTagName("header").item(0);
            final Element connectionElt = (Element) headerElt.getElementsByTagName("connection").item(0);

            // Read the connection pooling setting
            final Node usePoolingNode = connectionElt.getElementsByTagName("usePooling").item(0);
            final boolean usePooling = usePoolingNode.getTextContent().equals("true") ? true : false;

            // Read the connection properties
            final NodeList propertyNodes = connectionElt.getElementsByTagName("property");
            Node propertyNode = null;
            Properties properties = null;
            String name = null;
            String value = null;
            for (int i = 0; i < propertyNodes.getLength(); i++) {
                propertyNode = propertyNodes.item(i);

                if (properties == null) {
                    properties = new Properties();
                }
                name = propertyNode.getAttributes().getNamedItem("name").getTextContent();
                value = propertyNode.getTextContent();
                properties.setProperty(name, value);
            }

            final Node returnGeneratedKeysNode = headerElt.getElementsByTagName("returnGeneratedKeys").item(0);
            final boolean returnGeneratedKeys = returnGeneratedKeysNode.getTextContent().equals("true") ? true
                    : false;

            // Read the SQL body and get the list of sql statements
            final Element bodyElt = (Element) rootElt.getElementsByTagName("body").item(0);
            final NodeList statementNodes = bodyElt.getElementsByTagName("statement");
            final List<String> sqlRequests = new ArrayList<String>();
            for (int i = 0; i < statementNodes.getLength(); i++) {
                final String sqlRequest = statementNodes.item(i).getTextContent();
                sqlRequests.add(sqlRequest);
            }

            // Execute the List of SQL requests
            connection = getConnection(connectionURI, properties, usePooling);
            final JdbcResult result = handleSqlRequests(connection, returnGeneratedKeys, sqlRequests);
            response.setEntity(new RowSetRepresentation(result));

        } catch (SQLException se) {
            getLogger().log(Level.WARNING, "Error while processing the SQL request", se);
            response.setStatus(Status.SERVER_ERROR_INTERNAL, se);
        } catch (ParserConfigurationException pce) {
            getLogger().log(Level.WARNING, "Error with XML parser configuration", pce);
            response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST, pce);
        } catch (SAXException se) {
            getLogger().log(Level.WARNING, "Error while parsing the XML document", se);
            response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST, se);
        } catch (IOException ioe) {
            getLogger().log(Level.WARNING, "Input/Output exception", ioe);
            response.setStatus(Status.SERVER_ERROR_INTERNAL, ioe);
        }
    } else {
        throw new IllegalArgumentException("Only the POST method is supported");
    }
}

From source file:org.eclipse.lyo.testsuite.server.oslcv1tests.ServiceDescriptionTests.java

@Test
public void changeManagementServiceDescriptionHasValidSelectionDialog() throws XPathException {
    //If ServiceDescription is oslc_cm, make sure it has a valid selection dialog child element
    Node cmRequest = (Node) OSLCUtils.getXPath().evaluate("//oslc_cm:changeRequests", doc, XPathConstants.NODE);
    if (cmRequest != null) {
        NodeList sD = (NodeList) OSLCUtils.getXPath()
                .evaluate("//oslc_cm:changeRequests/oslc_cm:selectionDialog", doc, XPathConstants.NODESET);
        for (int i = 0; i < sD.getLength(); i++) {
            Node sQUrl = (Node) OSLCUtils.getXPath().evaluate(
                    "//oslc_cm:changeRequests/oslc_cm:selectionDialog[" + (i + 1) + "]/oslc_cm:url", doc,
                    XPathConstants.NODE);
            assertNotNull(sQUrl);//from   ww w.ja  va  2  s .c  o  m
            Node sDtitle = (Node) OSLCUtils.getXPath().evaluate(
                    "//oslc_cm:changeRequests/oslc_cm:selectionDialog[" + (i + 1) + "]/dc:title", doc,
                    XPathConstants.NODE);
            assertNotNull(sDtitle);
            assertFalse(sDtitle.getTextContent().isEmpty());
        }
    }
}

From source file:it.greenvulcano.gvesb.virtual.rest.RestCallOperation.java

private void readRestCallConfiguration(Node node) throws XMLConfigException {
    if (XMLConfig.exists(node, "./headers")) {
        fillMap(XMLConfig.getNodeList(node, "./headers/header"), headers);
    }/*  w w  w  .j a v a  2 s .  co  m*/

    if (XMLConfig.exists(node, "./parameters")) {
        fillMap(XMLConfig.getNodeList(node, "./parameters/param"), params);
    }

    Node bodyNode = XMLConfig.getNode(node, "./body");
    if (Objects.nonNull(bodyNode)) {

        sendGVBufferObject = Boolean.valueOf(XMLConfig.get(bodyNode, "@gvbuffer-object", "false"));

        body = bodyNode.getTextContent();
    } else {
        body = null;
    }
}

From source file:com.esri.gpt.server.openls.provider.services.geocode.GeocodeProvider.java

/**
 * Reads Address Information from request
 * @param reqParams/*from   w  ww. j av a2s. c  om*/
 * @param ndReq
 * @param xpath
 * @throws XPathExpressionException
 */
public void parseRequest(GeocodeParams reqParams, Node ndReq, XPath xpath) throws XPathExpressionException {
    NodeList ndAddresses = (NodeList) xpath.evaluate("xls:Address", ndReq, XPathConstants.NODESET);
    if (ndAddresses != null) {
        for (int i = 0; i < ndAddresses.getLength(); i++) {
            Node address = ndAddresses.item(i);
            if (address != null) {
                Address addr = new Address();
                Node ndStrAddr = (Node) xpath.evaluate("xls:StreetAddress", address, XPathConstants.NODE);
                if (ndStrAddr != null) {
                    Node ndStr = (Node) xpath.evaluate("xls:Street", ndStrAddr, XPathConstants.NODE);
                    if (ndStr != null) {
                        addr.setStreet(ndStr.getTextContent());
                    }
                }
                Node ndPostalCode = (Node) xpath.evaluate("xls:PostalCode", address, XPathConstants.NODE);
                if (ndPostalCode != null) {
                    addr.setPostalCode(ndPostalCode.getTextContent());
                }
                NodeList ndPlaces = (NodeList) xpath.evaluate("xls:Place", address, XPathConstants.NODESET);
                if (ndPlaces != null) {
                    for (int j = 0; j < ndPlaces.getLength(); j++) {
                        Node ndPlace = ndPlaces.item(j);
                        String type = Val
                                .chkStr((String) xpath.evaluate("@type", ndPlace, XPathConstants.STRING));
                        addr.setPlaceType(type);
                        if (type.equalsIgnoreCase("Municipality")) {
                            addr.setMunicipality(ndPlace.getTextContent());
                        } else if (type.equalsIgnoreCase("CountrySubdivision")) {
                            addr.setCountrySubdivision(ndPlace.getTextContent());
                        } else if (type.equalsIgnoreCase("BuildingNumber")) {
                            addr.setBuildingNumber(ndPlace.getTextContent());
                        } else if (type.equalsIgnoreCase("Intersection")) {
                            addr.setIntersection(ndPlace.getTextContent());
                        } else if (type.equalsIgnoreCase("StreetVec")) {
                            addr.setStreetVec(ndPlace.getTextContent());
                        }
                    }
                }
                reqParams.getAddresses().add(addr);
            }
        }
    }
}

From source file:MSUmpire.SpectrumParser.mzXMLReadUnit.java

public ScanData Parse() throws ParserConfigurationException, SAXException, IOException, DataFormatException {
    if (XMLtext.replaceFirst("</scan>", "").contains("</scan>")) {
        XMLtext = XMLtext.replaceFirst("</scan>", "");
    }//ww  w  . j a v  a2  s. com
    if (!XMLtext.contains("</scan>")) {
        XMLtext += "</scan>";
    }
    ScanData scan = new ScanData();
    final DocumentBuilder docBuilder = tls.get();
    docBuilder.reset();
    InputSource input = new InputSource(new StringReader(XMLtext));
    Document doc = null;
    try {
        doc = docBuilder.parse(input);
    } catch (Exception ex) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(ex));
        Logger.getRootLogger().error(XMLtext);
    }
    Node root = doc.getFirstChild();
    for (int i = 0; i < root.getAttributes().getLength(); i++) {
        switch (root.getAttributes().item(i).getNodeName()) {
        case ("num"):
            scan.ScanNum = Integer.parseInt(root.getAttributes().item(i).getNodeValue());
            break;
        case ("centroided"): {
            if ("1".equals(root.getAttributes().item(i).getNodeValue())) {
                scan.centroided = true;
            } else {
                scan.centroided = false;
            }
            break;
        }
        case ("msLevel"):
            scan.MsLevel = Integer.parseInt(root.getAttributes().item(i).getNodeValue());
            break;
        case ("scanType"):
            scan.scanType = root.getAttributes().item(i).getNodeValue();
            break;
        case ("peaksCount"):
            scan.PeaksCountString = Integer.parseInt(root.getAttributes().item(i).getNodeValue());
            break;
        case ("retentionTime"):
            scan.RetentionTime = Float.parseFloat(root.getAttributes().item(i).getNodeValue().substring(2,
                    root.getAttributes().item(i).getNodeValue().indexOf("S"))) / 60f;
            break;
        case ("lowMz"): {
            String value = root.getAttributes().item(i).getNodeValue();
            if ("inf".equals(value)) {
                value = String.valueOf(Float.MIN_VALUE);
            }
            scan.StartMz = Float.parseFloat(value);
            break;
        }
        case ("highMz"): {
            String value = root.getAttributes().item(i).getNodeValue();
            if ("inf".equals(value)) {
                value = String.valueOf(Float.MAX_VALUE);
            }
            scan.EndMz = Float.parseFloat(value);
            break;
        }
        case ("startMz"):
            scan.StartMz = Float.parseFloat(root.getAttributes().item(i).getNodeValue());
            break;
        case ("endMz"): {
            String value = root.getAttributes().item(i).getNodeValue();
            if ("inf".equals(value)) {
                value = String.valueOf(Float.MAX_VALUE);
            }
            scan.EndMz = Float.parseFloat(value);
            break;
        }
        case ("basePeakMz"): {
            String value = root.getAttributes().item(i).getNodeValue();
            if ("inf".equals(value)) {
                value = String.valueOf(Float.MAX_VALUE);
            }
            scan.BasePeakMz = Float.parseFloat(value);
            break;
        }
        case ("basePeakIntensity"):
            scan.BasePeakIntensity = Float.parseFloat(root.getAttributes().item(i).getNodeValue());
            break;
        case ("totIonCurrent"):
            scan.SetTotIonCurrent(Float.parseFloat(root.getAttributes().item(i).getNodeValue()));
            break;
        }
    }
    for (int i = 0; i < root.getChildNodes().getLength(); i++) {
        Node childNode = root.getChildNodes().item(i);
        switch (childNode.getNodeName()) {
        case ("precursorMz"): {
            scan.PrecursorMz = Float.parseFloat(childNode.getTextContent());
            for (int j = 0; j < childNode.getAttributes().getLength(); j++) {
                switch (childNode.getAttributes().item(j).getNodeName()) {
                case ("precursorScanNum"):
                    scan.precursorScanNum = Integer.parseInt(childNode.getAttributes().item(j).getNodeValue());
                    break;
                case ("precursorIntensity"):
                    scan.PrecursorIntensity = Float
                            .parseFloat(childNode.getAttributes().item(j).getNodeValue());
                    break;
                case ("precursorCharge"):
                    scan.PrecursorCharge = Integer.parseInt(childNode.getAttributes().item(j).getNodeValue());
                    break;
                case ("activationMethod"):
                    scan.ActivationMethod = childNode.getAttributes().item(j).getNodeValue();
                    break;
                case ("windowWideness"):
                    scan.windowWideness = Float.parseFloat(childNode.getAttributes().item(j).getNodeValue());
                    break;
                }
            }
            break;
        }
        case ("peaks"): {
            for (int j = 0; j < childNode.getAttributes().getLength(); j++) {
                switch (childNode.getAttributes().item(j).getNodeName()) {
                case ("compressionType"):
                    scan.compressionType = childNode.getAttributes().item(j).getNodeValue();
                    break;
                case ("precision"):
                    scan.precision = Integer.parseInt(childNode.getAttributes().item(j).getNodeValue());
                    break;
                }
            }
            ParsePeakString(scan, childNode.getTextContent());
            break;
        }
        }
        childNode = null;
    }
    if ("calibration".equals(scan.scanType)) {
        scan.MsLevel = -1;
    }
    XMLtext = null;
    scan.Data.Finalize();
    return scan;
}

From source file:org.openmrs.module.sync.SyncUtil.java

public static void setProperty(Object o, Node n, ArrayList<Field> allFields)
        throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    String propName = n.getNodeName();
    Object propVal = SyncUtil.valForField(propName, n.getTextContent(), allFields, n);

    log.debug("Trying to set value to " + propVal + " when propName is " + propName + " and context is "
            + n.getTextContent());/*from  www.  j  a  v  a 2s .  c om*/

    if (propVal != null) {
        SyncUtil.setProperty(o, propName, propVal);
        log.debug("Successfully called set" + SyncUtil.propCase(propName) + "(" + propVal + ")");
    }
}