Example usage for org.w3c.dom Node getFirstChild

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

Introduction

In this page you can find the example usage for org.w3c.dom Node getFirstChild.

Prototype

public Node getFirstChild();

Source Link

Document

The first child of this node.

Usage

From source file:org.dasein.cloud.cloudstack.CSMethod.java

private ParsedError parseError(int httpStatus, String assumedXml) throws InternalException {
    Logger logger = CSCloud.getLogger(CSMethod.class, "std");

    if (logger.isTraceEnabled()) {
        logger.trace(/*ww  w.j  a v a  2 s  .  co m*/
                "enter - " + CSMethod.class.getName() + ".parseError(" + httpStatus + "," + assumedXml + ")");
    }
    try {
        ParsedError error = new ParsedError();

        error.code = httpStatus;
        error.message = null;
        try {
            Document doc = parseResponse(httpStatus, assumedXml);

            NodeList codes = doc.getElementsByTagName("errorcode");
            for (int i = 0; i < codes.getLength(); i++) {
                Node n = codes.item(i);

                if (n != null && n.hasChildNodes()) {
                    error.code = Integer.parseInt(n.getFirstChild().getNodeValue().trim());
                }
            }
            NodeList text = doc.getElementsByTagName("errortext");
            for (int i = 0; i < text.getLength(); i++) {
                Node n = text.item(i);

                if (n != null && n.hasChildNodes()) {
                    error.message = n.getFirstChild().getNodeValue();
                }
            }
        } catch (Throwable ignore) {
            logger.warn("parseError(): Error was unparsable: " + ignore.getMessage());
            if (error.message == null) {
                error.message = assumedXml;
            }
        }
        if (error.message == null) {
            if (httpStatus == 401) {
                error.message = "Unauthorized user";
            } else if (httpStatus == 430) {
                error.message = "Malformed parameters";
            } else if (httpStatus == 547 || httpStatus == 530) {
                error.message = "Server error in cloud (" + httpStatus + ")";
            } else if (httpStatus == 531) {
                error.message = "Unable to find account";
            } else {
                error.message = "Received error code from server: " + httpStatus;
            }
        }
        return error;
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + CSMethod.class.getName() + ".parseError()");
        }
    }
}

From source file:com.signavio.warehouse.business.util.jpdl4.Script.java

public Script(org.w3c.dom.Node script) {
    this.uuid = "oryx_" + UUID.randomUUID().toString();
    NamedNodeMap attributes = script.getAttributes();
    this.name = JpdlToJson.getAttribute(attributes, "name");
    this.expression = JpdlToJson.getAttribute(attributes, "expr");
    this.language = JpdlToJson.getAttribute(attributes, "lang");
    this.variable = JpdlToJson.getAttribute(attributes, "var");
    if (script.hasChildNodes())
        for (org.w3c.dom.Node a = script.getFirstChild(); a != null; a = a.getNextSibling())
            if (a.getNodeName().equals("text")) {
                this.text = a.getTextContent();
                break;
            }/*from  w  w w.  j  a v a 2s . com*/
    this.bounds = JpdlToJson.getBounds(attributes.getNamedItem("g"));
}

From source file:com.nortal.jroad.endpoint.AbstractXTeeBaseEndpoint.java

private void copyParing(Document paring, Node response) throws Exception {
    Node paringElement = response.appendChild(response.getOwnerDocument().createElement("paring"));
    Node kehaNode = response.getOwnerDocument().importNode(paring.getDocumentElement(), true);

    NamedNodeMap attrs = kehaNode.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        paringElement.getAttributes().setNamedItem(attrs.item(i).cloneNode(true));
    }//from   ww w. j  a v  a 2  s . c  o m

    while (kehaNode.hasChildNodes()) {
        paringElement.appendChild(kehaNode.getFirstChild());
    }
}

From source file:com.enonic.esl.xml.XMLTool.java

public static String serialize(Node n, boolean includeSelf, String encoding) {
    DocumentFragment df = XMLTool.createDocument().createDocumentFragment();
    NodeList children = n.getChildNodes();

    // Check whether the child is a CDATA node
    Node firstChild = n.getFirstChild();
    if (firstChild != null && firstChild.getNodeType() == Node.CDATA_SECTION_NODE) {
        return null;
    }/*from   w w  w.  j a va 2s.c  o  m*/

    if (includeSelf) {
        df.appendChild(df.getOwnerDocument().importNode(n, true));
    } else {
        if (children == null || children.getLength() == 0) {
            return null;
        }

        // If only one node is found and it is a CDATA section, there is no need for serialization
        if (children.getLength() == 1 && children.item(0).getNodeType() == Node.CDATA_SECTION_NODE) {
            return null;
        }

        for (int i = 0; i < children.getLength(); i++) {
            df.appendChild(df.getOwnerDocument().importNode(children.item(i), true));
        }
    }

    return serialize(df, 4);
}

From source file:com.rubika.aotalk.util.ItemRef.java

private final String getElementValue(Node elem) {
    Node child;/*  w ww  . j a  v  a  2 s. c o m*/

    if (elem != null) {
        if (elem.hasChildNodes()) {
            for (child = elem.getFirstChild(); child != null; child = child.getNextSibling()) {
                if (child.getNodeType() == Node.TEXT_NODE) {
                    return child.getNodeValue();
                }
            }
        }
    }

    return "";
}

From source file:org.dasein.cloud.aws.platform.CloudFrontMethod.java

CloudFrontResponse invoke(String... args) throws CloudFrontException, CloudException, InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new InternalException("Context not specified for this request");
    }/*from  w  w w.  j  a  v a2 s. c om*/
    StringBuilder url = new StringBuilder();
    String dateString = getDate();
    HttpRequestBase method;
    HttpClient client;

    url.append(CLOUD_FRONT_URL + "/" + CF_VERSION + "/distribution");
    if (args != null && args.length > 0) {
        for (String arg : args) {
            url.append("/");
            url.append(arg);
        }
    }
    method = action.getMethod(url.toString());
    method.addHeader(AWSCloud.P_AWS_DATE, dateString);
    try {
        String signature = provider.signCloudFront(new String(ctx.getAccessPublic(), "utf-8"),
                ctx.getAccessPrivate(), dateString);

        method.addHeader(AWSCloud.P_CFAUTH, signature);
    } catch (UnsupportedEncodingException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    }
    if (headers != null) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            method.addHeader(entry.getKey(), entry.getValue());
        }
    }
    if (body != null) {
        try {
            ((HttpEntityEnclosingRequestBase) method)
                    .setEntity(new StringEntity(body, "application/xml", "utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new InternalException(e);
        }
    }
    attempts++;
    client = getClient(url.toString());
    CloudFrontResponse response = new CloudFrontResponse();

    HttpResponse httpResponse;
    int status;

    try {
        APITrace.trace(provider, action.toString());
        httpResponse = client.execute(method);
        status = httpResponse.getStatusLine().getStatusCode();

    } catch (IOException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    }
    Header header = httpResponse.getFirstHeader("ETag");

    if (header != null) {
        response.etag = header.getValue();
    } else {
        response.etag = null;
    }
    if (status == HttpServletResponse.SC_OK || status == HttpServletResponse.SC_CREATED
            || status == HttpServletResponse.SC_ACCEPTED) {
        try {
            HttpEntity entity = httpResponse.getEntity();

            if (entity == null) {
                throw new CloudFrontException(status, null, null, "NoResponse",
                        "No response body was specified");
            }
            InputStream input;

            try {
                input = entity.getContent();
            } catch (IOException e) {
                throw new CloudException(e);
            }
            try {
                response.document = parseResponse(input);
                return response;
            } finally {
                input.close();
            }
        } catch (IOException e) {
            logger.error(e);
            e.printStackTrace();
            throw new CloudException(e);
        }
    } else if (status == HttpServletResponse.SC_NO_CONTENT) {
        return null;
    } else {
        if (status == HttpServletResponse.SC_SERVICE_UNAVAILABLE
                || status == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) {
            if (attempts >= 5) {
                String msg;

                if (status == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
                    msg = "Cloud service is currently unavailable.";
                } else {
                    msg = "The cloud service encountered a server error while processing your request.";
                }
                logger.error(msg);
                throw new CloudException(msg);
            } else {
                try {
                    Thread.sleep(5000L);
                } catch (InterruptedException ignore) {
                }
                return invoke(args);
            }
        }
        try {
            HttpEntity entity = httpResponse.getEntity();

            if (entity == null) {
                throw new CloudFrontException(status, null, null, "NoResponse",
                        "No response body was specified");
            }
            InputStream input;

            try {
                input = entity.getContent();
            } catch (IOException e) {
                throw new CloudException(e);
            }
            Document doc;

            try {
                doc = parseResponse(input);
            } finally {
                input.close();
            }
            if (doc != null) {
                String code = null, message = null, requestId = null, type = null;
                NodeList blocks = doc.getElementsByTagName("Error");

                if (blocks.getLength() > 0) {
                    Node error = blocks.item(0);
                    NodeList attrs;

                    attrs = error.getChildNodes();
                    for (int i = 0; i < attrs.getLength(); i++) {
                        Node attr = attrs.item(i);

                        if (attr.getNodeName().equals("Code")) {
                            code = attr.getFirstChild().getNodeValue().trim();
                        } else if (attr.getNodeName().equals("Type")) {
                            type = attr.getFirstChild().getNodeValue().trim();
                        } else if (attr.getNodeName().equals("Message")) {
                            message = attr.getFirstChild().getNodeValue().trim();
                        }
                    }

                }
                blocks = doc.getElementsByTagName("RequestId");
                if (blocks.getLength() > 0) {
                    Node id = blocks.item(0);

                    requestId = id.getFirstChild().getNodeValue().trim();
                }
                if (message == null) {
                    throw new CloudException(
                            "Unable to identify error condition: " + status + "/" + requestId + "/" + code);
                }
                throw new CloudFrontException(status, requestId, type, code, message);
            }
            throw new CloudException("Unable to parse error.");
        } catch (IOException e) {
            logger.error(e);
            e.printStackTrace();
            throw new CloudException(e);
        }
    }
}

From source file:eionet.gdem.qa.QAResultPostProcessor.java

/**
 * Parses div nodes and adds warning node to result
 * @param divElements Div elements//from   w w w .  j  av a 2s . c  o m
 * @param warnMessage Warning message
 * @return true if feedbacktext class is found
 * @throws XmlException If an error occurs.
 */
private boolean parseDivNodes(NodeList divElements, String warnMessage) throws XmlException {
    boolean feedBackDivFound = false;
    try {
        for (int i = 0; divElements != null && i < divElements.getLength(); i++) {
            Node divNode = divElements.item(i);
            Node classNode = divNode.getAttributes().getNamedItem("class");

            if (classNode != null && classNode.getNodeValue().equalsIgnoreCase("feedbacktext")) {
                // found feedback div
                feedBackDivFound = true;

                Node firstChild = divNode.getFirstChild();
                Document doc = divNode.getOwnerDocument();

                Node warningNode = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                        .parse(new InputSource(
                                new StringReader("<div class=\"error-msg\">" + warnMessage + "</div>")))
                        .getFirstChild();
                warningNode = doc.importNode(warningNode, true);
                if (firstChild == null) {
                    divNode.appendChild(warningNode);
                } else {
                    warningNode = divNode.insertBefore(warningNode, firstChild);
                }
                //
                break;
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error processing divNodes " + e);
    }
    return feedBackDivFound;
}

From source file:com.centeractive.ws.builder.soap.XmlUtils.java

private static int findNodeIndex(Node node) {
    String nm = node.getLocalName();
    String ns = node.getNamespaceURI();
    short nt = node.getNodeType();

    Node parentNode = node.getParentNode();
    if (parentNode.getNodeType() != Node.ELEMENT_NODE)
        return 1;

    Node child = parentNode.getFirstChild();

    int ix = 0;/*from  w  w w . ja  va  2s  .c  om*/
    while (child != null) {
        if (child == node)
            return ix + 1;

        if (child.getNodeType() == nt && nm.equals(child.getLocalName())
                && ((ns == null && child.getNamespaceURI() == null)
                        || (ns != null && ns.equals(child.getNamespaceURI()))))
            ix++;

        child = child.getNextSibling();
    }

    throw new SoapBuilderException("Child node not found in parent!?");
}

From source file:com.signavio.warehouse.business.util.jpdl4.Sql.java

public Sql(org.w3c.dom.Node sql) {
    this.uuid = "oryx_" + UUID.randomUUID().toString();
    NamedNodeMap attributes = sql.getAttributes();
    this.name = JpdlToJson.getAttribute(attributes, "name");
    this.unique = Boolean.parseBoolean(JpdlToJson.getAttribute(attributes, "unique"));
    this.var = JpdlToJson.getAttribute(attributes, "var");

    this.bounds = JpdlToJson.getBounds(attributes.getNamedItem("g"));

    if (sql.hasChildNodes())
        for (org.w3c.dom.Node a = sql.getFirstChild(); a != null; a = a.getNextSibling()) {
            if (a.getNodeName().equals("query"))
                this.query = a.getTextContent();
            if (a.getNodeName().equals("parameters"))
                this.parameters = new Parameters(a);
        }/*w w w. j av  a 2s .  c om*/
}

From source file:net.sf.zekr.engine.bookmark.BookmarkSet.java

private void loadXml(BookmarkItem item, Node node) {
    NodeList nodeList = node.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node n = nodeList.item(i);
        if (n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().equals("info")) {
            NodeList infoChildren = n.getChildNodes();
            for (int j = 0; j < infoChildren.getLength(); j++) {
                Node nd = infoChildren.item(j);
                if (nd.getNodeType() != Node.ELEMENT_NODE)
                    continue;
                String name = nd.getNodeName();
                String value = "";
                if (nd.getFirstChild() != null)
                    value = nd.getFirstChild().getNodeValue();
                if (name.equals("name")) {
                    setName(value);//from   w ww  .j  a  v  a 2 s  . c o  m
                } else if (name.equals("desc")) {
                    setDescription(value);
                } else if (name.equals("author")) {
                    setAuthor(value);
                } else if (name.equals("language")) {
                    setLanguage(value);
                } else if (name.equals("dir")) {
                    setDirection(value);
                } else if (name.equals("modifyDate")) {
                    setCreateDate(toDateFormat(value));
                } else if (name.equals("createDate")) {
                    setCreateDate(toDateFormat(value));
                }
            }
            break;
        }
    }
    _loadXml(item, node);
}