Example usage for org.w3c.dom Element getNodeValue

List of usage examples for org.w3c.dom Element getNodeValue

Introduction

In this page you can find the example usage for org.w3c.dom Element getNodeValue.

Prototype

public String getNodeValue() throws DOMException;

Source Link

Document

The value of this node, depending on its type; see the table above.

Usage

From source file:Main.java

/**
 * Used for debuging//w  w w  . j  ava2s.co  m
 * 
 * @param parent
 *            Element
 * @param out
 *            PrintStream
 * @param deep
 *            boolean
 * @param prefix
 *            String
 */
public static void printChildElements(Element parent, PrintStream out, boolean deep, String prefix) {
    out.print(prefix + "<" + parent.getNodeName());
    NamedNodeMap attrs = parent.getAttributes();
    Node node;
    for (int i = 0; i < attrs.getLength(); i++) {
        node = attrs.item(i);
        out.print(" " + node.getNodeName() + "=\"" + node.getNodeValue() + "\"");
    }
    out.println(">");

    // String data = getElementTextValueDeprecated(parent);
    String data = parent.getNodeValue();
    if (data != null && data.trim().length() > 0) {
        out.println(prefix + "\t" + data);
    }

    data = getElementCDataValue(parent);
    if (data != null && data.trim().length() > 0) {
        out.println(prefix + "\t<![CDATA[" + data + "]]>");
    }

    NodeList nodes = parent.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
        node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (deep) {
                printChildElements((Element) node, out, deep, prefix + "\t");
            } else {
                out.println(prefix + node.getNodeName());
            }
        }
    }

    out.println(prefix + "</" + parent.getNodeName() + ">");
}

From source file:com.example.switchyard.sap.Transformers.java

@Transformer(from = "{urn:com.example.switchyard:switchyard-sap-jca:1.0}customerId")
public String unmarshalCustomerId(Element node) {
    return node.getNodeValue();
}

From source file:com.mirth.connect.model.converters.DICOMSerializer.java

@Override
public String fromXML(String source) throws SerializerException {
    if (source == null || source.length() == 0) {
        return StringUtils.EMPTY;
    }//from www. ja  v  a 2 s.c  om

    try {
        // re-parse the xml to Mirth format
        Document document = documentSerializer.fromXML(source);
        Element element = document.getDocumentElement();
        Node node = element.getChildNodes().item(0);

        // change back to <attr> tag for all tags under <dicom> tag
        while (node != null) {
            renameTagToAttr(document, node);
            node = node.getNextSibling();
        }

        NodeList items = document.getElementsByTagName("item");

        // change back to <attr> tag for all tags under <item> tags
        if (items != null) {
            for (int i = 0; i < items.getLength(); i++) {
                Node itemNode = items.item(i);

                if (itemNode.getChildNodes() != null) {
                    NodeList itemNodes = itemNode.getChildNodes();

                    for (int j = 0; j < itemNodes.getLength(); j++) {
                        Node nodeItem = itemNodes.item(j);
                        renameTagToAttr(document, nodeItem);
                    }
                }
            }
        }

        // find the charset
        String charset = null;
        Element charsetElement = (Element) document.getElementsByTagName("tag00080005").item(0);

        if (charsetElement != null) {
            charset = charsetElement.getNodeValue();
        } else {
            charset = "utf-8";
        }

        // parse the Document into a DicomObject
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        DicomObject dicomObject = new BasicDicomObject();
        ContentHandlerAdapter contentHandler = new ContentHandlerAdapter(dicomObject);
        byte[] documentBytes = documentSerializer.toXML(document).trim().getBytes(charset);
        parser.parse(new InputSource(new ByteArrayInputStream(documentBytes)), contentHandler);
        return new String(Base64.encodeBase64Chunked(DICOMUtil.dicomObjectToByteArray(dicomObject)));
    } catch (Exception e) {
        throw new SerializerException(e);
    }
}

From source file:com.mirth.connect.plugins.datatypes.dicom.DICOMSerializer.java

@Override
public String fromXML(String source) throws MessageSerializerException {
    if (source == null || source.length() == 0) {
        return org.apache.commons.lang3.StringUtils.EMPTY;
    }//  w ww  .  ja  v  a2 s  .  c om

    try {
        // re-parse the xml to Mirth format
        Document document = documentSerializer.fromXML(source);
        Element element = document.getDocumentElement();
        Node node = element.getChildNodes().item(0);

        // change back to <attr> tag for all tags under <dicom> tag
        while (node != null) {
            renameTagToAttr(document, node);
            node = node.getNextSibling();
        }

        NodeList items = document.getElementsByTagName("item");

        // change back to <attr> tag for all tags under <item> tags
        if (items != null) {
            for (int i = 0; i < items.getLength(); i++) {
                Node itemNode = items.item(i);

                if (itemNode.getChildNodes() != null) {
                    NodeList itemNodes = itemNode.getChildNodes();

                    for (int j = 0; j < itemNodes.getLength(); j++) {
                        Node nodeItem = itemNodes.item(j);
                        renameTagToAttr(document, nodeItem);
                    }
                }
            }
        }

        // find the charset
        String charset = null;
        Element charsetElement = (Element) document.getElementsByTagName("tag00080005").item(0);

        if (charsetElement != null) {
            charset = charsetElement.getNodeValue();
        } else {
            charset = "utf-8";
        }

        // parse the Document into a DicomObject
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        DicomObject dicomObject = new BasicDicomObject();
        ContentHandlerAdapter contentHandler = new ContentHandlerAdapter(dicomObject);
        byte[] documentBytes = documentSerializer.toXML(document).trim().getBytes(charset);
        parser.parse(new InputSource(new ByteArrayInputStream(documentBytes)), contentHandler);
        return StringUtils
                .newStringUsAscii(Base64Util.encodeBase64(DICOMConverter.dicomObjectToByteArray(dicomObject)));
    } catch (Exception e) {
        throw new MessageSerializerException("Error converting XML to DICOM", e, ErrorMessageBuilder
                .buildErrorMessage(this.getClass().getSimpleName(), "Error converting XML to DICOM", e));
    }
}

From source file:com.orient.lib.xbmc.addons.Addon.java

/**
 * Takes the ID of the addon and loads all properties from the corresponding
 * file structure./*w w w.j  a  v a2  s. com*/
 * 
 * @param id
 * @return
 */
private boolean loadPropsByAddonId(String id) {

    if (!Addon.exists(id))
        return false;

    String path = Addon.getAddonXmlPath(id);

    if (path != null && !loadXMLDocument(path))
        return false;

    AddonProps props = new AddonProps();

    // Addon element
    //      Settings settings = Settings.getInstance();
    //      File addonDir = settings.getAddonDir();

    Element addonEl = document.getDocumentElement();

    if (addonEl == null || !addonEl.getNodeName().equals("addon"))
        return false;

    props.path = FilenameUtils.separatorsToSystem(Settings.getInstance().getAddonDirPath() + "\\" + id);

    props.id = XMLUtils.getAttribute(addonEl, "id");
    props.name = XMLUtils.getAttribute(addonEl, "name");
    props.version = XMLUtils.getAttribute(addonEl, "version");
    props.author = XMLUtils.getAttribute(addonEl, "provider-name");

    // extension element
    Element extensionEl = XMLUtils.getFirstChildElement(addonEl, "extension");

    while (extensionEl != null) {
        String point = XMLUtils.getAttribute(extensionEl, "point");

        if (point.equals("xbmc.addon.metadata")) {
            Element licenseEl = XMLUtils.getFirstChildElement(extensionEl, "license");

            if (licenseEl != null)
                props.license = licenseEl.getNodeValue();

            // TODO add other meta data
        } else {
            props.libname = XMLUtils.getAttribute(extensionEl, "library");
            props.type = getTranslateType(point);
        }

        extensionEl = XMLUtils.getNextSiblingElement(extensionEl, "extension");
    }

    // dependencies element
    Element requiresEl = XMLUtils.getFirstChildElement(addonEl, "requires");
    Element importEl = XMLUtils.getFirstChildElement(requiresEl, "import");

    while (importEl != null) {

        String addon = XMLUtils.getAttribute(importEl, "addon");

        if (addon != null)
            props.dependencies.add(addon);

        importEl = XMLUtils.getNextSiblingElement(importEl, "import");
    }

    this.props = props;

    return true;
}

From source file:com.microsoft.exchange.impl.ExchangeResponseUtilsImpl.java

private String parseInnerResponse(ResponseMessageType responseMessage) {
    StringBuilder responseBuilder = new StringBuilder("Response[");

    ResponseCodeType responseCode = responseMessage.getResponseCode();
    if (null != responseCode) {
        responseBuilder.append("code=" + responseCode + ", ");
    }/*from  w w  w .  j a  v  a2 s.  c om*/
    ResponseClassType responseClass = responseMessage.getResponseClass();
    if (null != responseClass) {
        responseBuilder.append("class=" + responseClass + ", ");
    }
    String messageText = responseMessage.getMessageText();
    if (StringUtils.isNotBlank(messageText)) {
        responseBuilder.append("txt=" + messageText + ", ");
    }
    MessageXml messageXml = responseMessage.getMessageXml();
    if (null != messageXml) {
        StringBuilder xmlStringBuilder = new StringBuilder("messageXml=");
        List<Element> anies = messageXml.getAnies();
        if (!CollectionUtils.isEmpty(anies)) {
            for (Element element : anies) {
                String elementNameString = element.getNodeName();
                String elementValueString = element.getNodeValue();
                xmlStringBuilder.append(elementNameString + "=" + elementValueString + ";");

                if (null != element.getAttributes()) {
                    NamedNodeMap attributes = element.getAttributes();
                    for (int i = 0; i < attributes.getLength(); i++) {
                        Node item = attributes.item(i);
                        String nodeName = item.getNodeName();
                        String nodeValue = item.getNodeValue();
                        xmlStringBuilder.append(nodeName + "=" + nodeValue + ",");
                    }
                }
            }
        }
        responseBuilder.append("xml=" + xmlStringBuilder.toString() + ", ");
    }
    Integer descriptiveLinkKey = responseMessage.getDescriptiveLinkKey();
    if (null != descriptiveLinkKey) {
        responseBuilder.append("link=" + descriptiveLinkKey);
    }

    responseBuilder.append("]");
    return responseBuilder.toString();
}

From source file:net.chaosserver.timelord.swingui.Timelord.java

/**
 * Check if there is a newer version of the timelord application
 * available and if so, prompt the user to download the new version.
 * /* ww  w.jav a 2 s .  com*/
 * @return if the user wants to download a new version
 */
public boolean isUpgradeRequested() {
    boolean result = false;
    Properties appProperties = getAppProperties();

    if (appProperties != null) {
        String pomUrlString = appProperties.getProperty("pomurl");
        String appVersion = appProperties.getProperty("implementation.version");

        if (pomUrlString != null) {
            InputStream pomStream = null;

            try {
                URL pomUrl = new URL(pomUrlString);
                pomStream = pomUrl.openStream();

                if (log.isDebugEnabled()) {
                    log.debug("Opened URL [" + pomUrl + "] with result ["
                            + (pomStream != null ? pomStream.available() : "null") + "]");
                }

                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setNamespaceAware(true);
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(pomStream);

                if (log.isTraceEnabled()) {
                    log.trace("Loaded document: " + doc.getDocumentElement());
                }

                Element pomversionElement = doc.getElementById("pomversion");
                String pomVersion = "";
                if (pomversionElement != null) {
                    pomVersion = pomversionElement.getNodeValue();
                }

                if (appVersion == null) {
                    appVersion = "";
                }

                if (log.isDebugEnabled()) {
                    log.debug("Testinv version of app [" + appVersion + "] against version of pom ["
                            + pomVersion + "]");
                }

                if (!pomVersion.equals(appVersion)) {

                }

            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (pomStream != null) {
                    try {
                        pomStream.close();
                    } catch (IOException e) {
                        if (log.isInfoEnabled()) {
                            log.info("failed to close pomstream", e);
                        }
                    }
                }
            }

        } else {
            if (log.isWarnEnabled()) {
                log.warn("Got back blank pomurl, so not checking " + "for upgrade.");
            }
        }
    } else {
        if (log.isWarnEnabled()) {
            log.warn("Got back blank properties, so not checking " + "for upgrade.");
        }
    }

    return result;
}

From source file:org.weloveastrid.rmilk.api.Invoker.java

public Element invoke(boolean repeat, Param... params) throws ServiceException {
    long timeSinceLastInvocation = System.currentTimeMillis() - lastInvocation;
    if (timeSinceLastInvocation < INVOCATION_INTERVAL) {
        // In order not to invoke the RTM service too often
        try {//  ww  w.  j av  a 2  s  .c o m
            Thread.sleep(INVOCATION_INTERVAL - timeSinceLastInvocation);
        } catch (InterruptedException e) {
            return null;
        }
    }

    // We compute the URI
    final StringBuffer requestUri = computeRequestUri(params);
    HttpResponse response = null;

    final HttpGet request = new HttpGet("http://" //$NON-NLS-1$
            + ServiceImpl.SERVER_HOST_NAME + requestUri.toString());
    final String methodUri = request.getRequestLine().getUri();

    Element result;
    try {
        Log.i(TAG, "Executing the method:" + methodUri); //$NON-NLS-1$
        response = httpClient.execute(request);
        lastInvocation = System.currentTimeMillis();

        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            Log.e(TAG, "Method failed: " + response.getStatusLine()); //$NON-NLS-1$

            // Tim: HTTP error. Let's wait a little bit
            if (!repeat) {
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                    // ignore
                }
                response.getEntity().consumeContent();
                return invoke(true, params);
            }

            throw new ServiceInternalException("method failed: " + response.getStatusLine());
        }

        final Document responseDoc = builder.parse(response.getEntity().getContent());
        final Element wrapperElt = responseDoc.getDocumentElement();
        if (!wrapperElt.getNodeName().equals("rsp")) {
            throw new ServiceInternalException(
                    "unexpected response returned by RTM service: " + wrapperElt.getNodeName());
        } else {
            String stat = wrapperElt.getAttribute("stat");
            if (stat.equals("fail")) {
                Node errElt = wrapperElt.getFirstChild();
                while (errElt != null
                        && (errElt.getNodeType() != Node.ELEMENT_NODE || !errElt.getNodeName().equals("err"))) {
                    errElt = errElt.getNextSibling();
                }
                if (errElt == null) {
                    throw new ServiceInternalException(
                            "unexpected response returned by RTM service: " + wrapperElt.getNodeValue());
                } else {
                    if (SERVICE_UNAVAILABLE_CODE.equals(((Element) errElt).getAttribute("code")) && !repeat) {
                        try {
                            Thread.sleep(1500);
                        } catch (InterruptedException e) {
                            // ignore
                        }
                        return invoke(true, params);
                    }

                    throw new ServiceException(Integer.parseInt(((Element) errElt).getAttribute("code")),
                            ((Element) errElt).getAttribute("msg"));
                }
            } else {
                Node dataElt = wrapperElt.getFirstChild();
                while (dataElt != null && (dataElt.getNodeType() != Node.ELEMENT_NODE
                        || dataElt.getNodeName().equals("transaction") == true)) {
                    try {
                        Node nextSibling = dataElt.getNextSibling();
                        if (nextSibling == null) {
                            break;
                        } else {
                            dataElt = nextSibling;
                        }
                    } catch (IndexOutOfBoundsException exception) {
                        // Some implementation may throw this exception,
                        // instead of returning a null sibling
                        break;
                    }
                }
                if (dataElt == null) {
                    throw new ServiceInternalException(
                            "unexpected response returned by RTM service: " + wrapperElt.getNodeValue());
                } else {
                    result = (Element) dataElt;
                }
            }
        }
    } catch (IOException e) {
        throw new ServiceInternalException("Error making connection: " + e.getMessage(), e);
    } catch (SAXException e) {
        // repeat call if possible.
        if (!repeat)
            return invoke(true, params);
        else
            throw new ServiceInternalException("Error parsing response. " + "Please try sync again!", e);
    } finally {
        httpClient.getConnectionManager().closeExpiredConnections();
    }

    return result;
}

From source file:org.weloveastrid.hive.api.Invoker.java

public Element invoke(boolean repeat, Param... params) throws ServiceException {
    long timeSinceLastInvocation = System.currentTimeMillis() - lastInvocation;
    if (timeSinceLastInvocation < INVOCATION_INTERVAL) {
        // In order not to invoke the Hiveminder service too often
        try {/*  ww  w. j  av a2s. c o  m*/
            Thread.sleep(INVOCATION_INTERVAL - timeSinceLastInvocation);
        } catch (InterruptedException e) {
            return null;
        }
    }

    // We compute the URI
    final StringBuffer requestUri = computeRequestUri(params);
    HttpResponse response = null;

    final HttpGet request = new HttpGet("http://" //$NON-NLS-1$
            + ServiceImpl.SERVER_HOST_NAME + requestUri.toString());
    final String methodUri = request.getRequestLine().getUri();

    Element result;
    try {
        Log.i(TAG, "Executing the method:" + methodUri); //$NON-NLS-1$
        response = httpClient.execute(request);
        lastInvocation = System.currentTimeMillis();

        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            Log.e(TAG, "Method failed: " + response.getStatusLine()); //$NON-NLS-1$

            // Tim: HTTP error. Let's wait a little bit
            if (!repeat) {
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                    // ignore
                }
                response.getEntity().consumeContent();
                return invoke(true, params);
            }

            throw new ServiceInternalException("method failed: " + response.getStatusLine());
        }

        final Document responseDoc = builder.parse(response.getEntity().getContent());
        final Element wrapperElt = responseDoc.getDocumentElement();
        if (!wrapperElt.getNodeName().equals("rsp")) {
            throw new ServiceInternalException(
                    "unexpected response returned by Hiveminder service: " + wrapperElt.getNodeName());
        } else {
            String stat = wrapperElt.getAttribute("stat");
            if (stat.equals("fail")) {
                Node errElt = wrapperElt.getFirstChild();
                while (errElt != null
                        && (errElt.getNodeType() != Node.ELEMENT_NODE || !errElt.getNodeName().equals("err"))) {
                    errElt = errElt.getNextSibling();
                }
                if (errElt == null) {
                    throw new ServiceInternalException(
                            "unexpected response returned by Hiveminder service: " + wrapperElt.getNodeValue());
                } else {
                    if (SERVICE_UNAVAILABLE_CODE.equals(((Element) errElt).getAttribute("code")) && !repeat) {
                        try {
                            Thread.sleep(1500);
                        } catch (InterruptedException e) {
                            // ignore
                        }
                        return invoke(true, params);
                    }

                    throw new ServiceException(Integer.parseInt(((Element) errElt).getAttribute("code")),
                            ((Element) errElt).getAttribute("msg"));
                }
            } else {
                Node dataElt = wrapperElt.getFirstChild();
                while (dataElt != null && (dataElt.getNodeType() != Node.ELEMENT_NODE
                        || dataElt.getNodeName().equals("transaction") == true)) {
                    try {
                        Node nextSibling = dataElt.getNextSibling();
                        if (nextSibling == null) {
                            break;
                        } else {
                            dataElt = nextSibling;
                        }
                    } catch (IndexOutOfBoundsException exception) {
                        // Some implementation may throw this exception,
                        // instead of returning a null sibling
                        break;
                    }
                }
                if (dataElt == null) {
                    throw new ServiceInternalException(
                            "unexpected response returned by Hiveminder service: " + wrapperElt.getNodeValue());
                } else {
                    result = (Element) dataElt;
                }
            }
        }
    } catch (IOException e) {
        throw new ServiceInternalException("Error making connection: " + e.getMessage(), e);
    } catch (SAXException e) {
        // repeat call if possible.
        if (!repeat)
            return invoke(true, params);
        else
            throw new ServiceInternalException("Error parsing response. " + "Please try sync again!", e);
    } finally {
        httpClient.getConnectionManager().closeExpiredConnections();
    }

    return result;
}

From source file:com.twinsoft.convertigo.engine.util.WsReference.java

private static void extractSoapVariables(XmlSchema xmlSchema, List<RequestableHttpVariable> variables,
        Node node, String longName, boolean isMulti, QName variableType) throws EngineException {
    if (node == null)
        return;//from  w  ww  . ja v a2s .co m
    int type = node.getNodeType();

    if (type == Node.ELEMENT_NODE) {
        Element element = (Element) node;
        if (element != null) {
            String elementName = element.getLocalName();
            if (longName != null)
                elementName = longName + "_" + elementName;

            if (!element.getAttribute("soapenc:arrayType").equals("") && !element.hasChildNodes()) {
                String avalue = element.getAttribute("soapenc:arrayType");
                element.setAttribute("soapenc:arrayType", avalue.replaceAll("\\[\\]", "[1]"));

                Element child = element.getOwnerDocument().createElement("item");
                String atype = avalue.replaceAll("\\[\\]", "");
                child.setAttribute("xsi:type", atype);
                if (atype.startsWith("xsd:")) {
                    String variableName = elementName + "_item";
                    child.appendChild(
                            element.getOwnerDocument().createTextNode("$(" + variableName.toUpperCase() + ")"));
                    RequestableHttpVariable httpVariable = createHttpVariable(true, variableName,
                            new QName(Constants.URI_2001_SCHEMA_XSD, atype.split(":")[1]));
                    variables.add(httpVariable);
                }
                element.appendChild(child);
            }

            // extract from attributes
            NamedNodeMap map = element.getAttributes();
            for (int i = 0; i < map.getLength(); i++) {
                Node child = map.item(i);
                if (child.getNodeName().equals("soapenc:arrayType"))
                    continue;
                if (child.getNodeName().equals("xsi:type"))
                    continue;
                if (child.getNodeName().equals("soapenv:encodingStyle"))
                    continue;

                String variableName = getVariableName(variables, elementName + "_" + child.getLocalName());

                child.setNodeValue("$(" + variableName.toUpperCase() + ")");

                RequestableHttpVariable httpVariable = createHttpVariable(false, variableName,
                        Constants.XSD_STRING);
                variables.add(httpVariable);
            }

            // extract from children nodes
            boolean multi = false;
            QName qname = Constants.XSD_STRING;
            NodeList children = element.getChildNodes();
            if (children.getLength() > 0) {
                Node child = element.getFirstChild();
                while (child != null) {
                    if (child.getNodeType() == Node.COMMENT_NODE) {
                        String value = child.getNodeValue();
                        if (value.startsWith("type:")) {
                            String schemaType = child.getNodeValue().substring("type:".length()).trim();
                            qname = getVariableSchemaType(xmlSchema, schemaType);
                        }
                        if (value.indexOf("repetitions:") != -1) {
                            multi = true;
                        }
                    } else if (child.getNodeType() == Node.TEXT_NODE) {
                        String value = child.getNodeValue().trim();
                        if (value.equals("?") || !value.equals("")) {
                            String variableName = getVariableName(variables, elementName);

                            child.setNodeValue("$(" + variableName.toUpperCase() + ")");

                            RequestableHttpVariable httpVariable = createHttpVariable(isMulti, variableName,
                                    variableType);
                            variables.add(httpVariable);
                        }
                    } else if (child.getNodeType() == Node.ELEMENT_NODE) {
                        extractSoapVariables(xmlSchema, variables, child, elementName, multi, qname);
                        multi = false;
                        qname = Constants.XSD_STRING;
                    }

                    child = child.getNextSibling();
                }
            }

        }
    }
}