Example usage for org.w3c.dom Node hasChildNodes

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

Introduction

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

Prototype

public boolean hasChildNodes();

Source Link

Document

Returns whether this node has any children.

Usage

From source file:com.inbravo.scribe.rest.service.crm.ZHRESTCRMService.java

@Override
public final ScribeCommandObject getObjects(final ScribeCommandObject cADCommandObject, final String query,
        final String select) throws Exception {
    logger.debug("----Inside getObjects, query: " + query + " & select: " + select);

    /* Transfer the call to second method */
    if (query != null && query.toUpperCase().startsWith(queryPhoneFieldConst.toUpperCase())) {

        ScribeCommandObject returnObject = null;

        try {//from   w  w  w .  j a v  a2  s.c o  m
            /* Query CRM object by Phone field */
            returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select, null, "Phone");

        } catch (final ScribeException firstE) {

            /* Check if record is not found */
            if (firstE.getMessage().contains(ScribeResponseCodes._1004)) {

                try {
                    /* Query CRM object by Mobile field */
                    returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select, null, "Mobile");
                } catch (final ScribeException secondE) {

                    /* Check if record is again not found */
                    if (secondE.getMessage().contains(ScribeResponseCodes._1004)) {

                        try {
                            /* Query CRM object by Home Phone field */
                            returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select, null,
                                    "Home Phone");
                        } catch (final ScribeException thirdE) {

                            /* Check if record is again not found */
                            if (thirdE.getMessage().contains(ScribeResponseCodes._1004)) {

                                try {
                                    /* Query CRM object by Other Phone field */
                                    returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select,
                                            null, "Other Phone");
                                } catch (final ScribeException fourthE) {

                                    /* Throw the error to user */
                                    throw fourthE;
                                }
                            }
                        }
                    }
                }
            }
        }

        return returnObject;
    } else {

        /* Get user from session manager */
        final ScribeCacheObject user = (ScribeCacheObject) cRMSessionManager
                .getSessionInfo(cADCommandObject.getCrmUserId());

        PostMethod postMethod = null;
        try {

            /* Get CRM information from user */
            final String serviceURL = user.getScribeMetaObject().getCrmServiceURL();
            final String serviceProtocol = user.getScribeMetaObject().getCrmServiceProtocol();
            final String sessionId = user.getScribeMetaObject().getCrmSessionId();

            /* Create Zoho URL */
            final String zohoURL = serviceProtocol + "://" + serviceURL + "/crm/private/xml/"
                    + cADCommandObject.getObjectType() + "s/getSearchRecords";

            logger.debug("----Inside getObjects zohoURL: " + zohoURL + " & sessionId: " + sessionId);

            /* Instantiate post method */
            postMethod = new PostMethod(zohoURL);

            /* Set request parameters */
            postMethod.setParameter("authtoken", sessionId.trim());
            postMethod.setParameter("scope", "crmapi");

            if (!query.equalsIgnoreCase("NONE")) {

                /* Create ZH query */
                final String zhQuery = ZHCRMMessageFormatUtils.createZHQuery(query);

                if (zhQuery != null && !"".equals(zhQuery)) {

                    /* Set search parameter in request */
                    postMethod.setParameter("searchCondition", "(" + zhQuery + ")");
                }
            } else {

                /* Without query param this method is not applicable */
                return this.getObjects(cADCommandObject);
            }

            if (!select.equalsIgnoreCase("ALL")) {

                /* Create ZH select CRM fields information */
                final String zhSelect = ZHCRMMessageFormatUtils.createZHSelect(cADCommandObject, select);

                /* Validate query */
                if (zhSelect != null && !"".equals(zhSelect)) {

                    /* Set request param to select fields */
                    postMethod.setParameter("selectColumns", zhSelect);
                }
            } else {

                /* Set request param to select all fields */
                postMethod.setParameter("selectColumns", "All");
            }

            final HttpClient httpclient = new HttpClient();

            /* Execute method */
            int result = httpclient.executeMethod(postMethod);
            logger.debug("----Inside getObjects response code: " + result + " & body: "
                    + postMethod.getResponseBodyAsString());

            /* Check if response if SUCCESS */
            if (result == HttpStatus.SC_OK) {

                /* Create XML document from response */
                final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                final DocumentBuilder builder = factory.newDocumentBuilder();
                final Document document = builder.parse(postMethod.getResponseBodyAsStream());

                /* Create new XPath object to query XML document */
                final XPath xpath = XPathFactory.newInstance().newXPath();

                /* XPath Query for showing all nodes value */
                final XPathExpression expr = xpath
                        .compile("/response/result/" + cADCommandObject.getObjectType() + "s/row");

                /* Get node list from response document */
                final NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

                /* Check if records founds */
                if (nodeList != null && nodeList.getLength() == 0) {

                    /* XPath Query for showing error message */
                    XPathExpression errorExpression = xpath.compile("/response/error/message");

                    /* Get erroe message from response document */
                    Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE);

                    /* Check if error message is found */
                    if (errorMessage != null) {

                        /* Send user error */
                        throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM : "
                                + errorMessage.getTextContent());
                    } else {

                        /* XPath Query for showing error message */
                        errorExpression = xpath.compile("/response/nodata/message");

                        /* Get erroe message from response document */
                        errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE);

                        /* Send user error */
                        throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM : "
                                + errorMessage.getTextContent());
                    }
                } else {
                    /* Create new Scribe object list */
                    final List<ScribeObject> cADbjectList = new ArrayList<ScribeObject>();

                    /* Iterate over node list */
                    for (int i = 0; i < nodeList.getLength(); i++) {

                        /* Create list of elements */
                        final List<Element> elementList = new ArrayList<Element>();

                        /* Get node from node list */
                        final Node node = nodeList.item(i);

                        /* Create new Scribe object */
                        final ScribeObject cADbject = new ScribeObject();

                        /* Check if node has child nodes */
                        if (node.hasChildNodes()) {

                            final NodeList subNodeList = node.getChildNodes();

                            /* Create new map for attributes */
                            final Map<String, String> attributeMap = new HashMap<String, String>();

                            /*
                             * Iterate over sub node list and create elements
                             */
                            for (int j = 0; j < subNodeList.getLength(); j++) {

                                final Node subNode = subNodeList.item(j);

                                /* This trick is to avoid empty nodes */
                                if (!subNode.getNodeName().contains("#text")) {

                                    /* Create element from response */
                                    final Element element = (Element) subNode;

                                    /* Populate label map */
                                    attributeMap.put("label", element.getAttribute("val"));

                                    /* Get node name */
                                    final String nodeName = element.getAttribute("val").replace(" ",
                                            spaceCharReplacement);

                                    /* Validate the node name */
                                    if (XMLChar.isValidName(nodeName)) {

                                        /* Add element in list */
                                        elementList.add(ZHCRMMessageFormatUtils.createMessageElement(nodeName,
                                                element.getTextContent(), attributeMap));
                                    } else {
                                        logger.debug(
                                                "----Inside getObjects, found invalid XML node; ignoring field: "
                                                        + element.getAttribute("val"));
                                    }
                                }
                            }
                        }
                        /* Add all CRM fields */
                        cADbject.setXmlContent(elementList);

                        /* Set type information in object */
                        cADbject.setObjectType(cADCommandObject.getObjectType());

                        /* Add Scribe object in list */
                        cADbjectList.add(cADbject);
                    }

                    /* Check if no record found */
                    if (cADbjectList.size() == 0) {
                        throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM");
                    }

                    /* Set the final object in command object */
                    cADCommandObject.setObject(cADbjectList.toArray(new ScribeObject[cADbjectList.size()]));
                }
            } else if (result == HttpStatus.SC_FORBIDDEN) {
                throw new ScribeException(ScribeResponseCodes._1022 + "Query is forbidden by Zoho CRM");
            } else if (result == HttpStatus.SC_BAD_REQUEST) {
                throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request content");
            } else if (result == HttpStatus.SC_UNAUTHORIZED) {
                throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zoho CRM");
            } else if (result == HttpStatus.SC_NOT_FOUND) {
                throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM");
            } else if (result == HttpStatus.SC_INTERNAL_SERVER_ERROR) {

                /* Create XML document from response */
                final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                final DocumentBuilder builder = factory.newDocumentBuilder();
                final Document document = builder.parse(postMethod.getResponseBodyAsStream());

                /* Create new XPath object to query XML document */
                final XPath xpath = XPathFactory.newInstance().newXPath();

                /* XPath Query for showing error message */
                final XPathExpression errorExpression = xpath.compile("/response/error/message");

                /* Get erroe message from response document */
                final Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE);

                if (errorMessage != null) {

                    /* Send user error */
                    throw new ScribeException(ScribeResponseCodes._1004
                            + "Requested data not found at Zoho CRM : " + errorMessage.getTextContent());
                } else {

                    /* Send user error */
                    throw new ScribeException(
                            ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM");
                }
            }
        } catch (final ScribeException exception) {
            throw exception;
        } catch (final ParserConfigurationException exception) {
            throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM");
        } catch (final SAXException exception) {
            throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM");
        } catch (final IOException exception) {
            throw new ScribeException(
                    ScribeResponseCodes._1022 + "Communication error while communicating with Zoho CRM");
        } finally {
            /* Release connection socket */
            if (postMethod != null) {
                postMethod.releaseConnection();
            }
        }

        return cADCommandObject;
    }
}

From source file:com.inbravo.scribe.rest.service.crm.ZHRESTCRMService.java

@Override
public final ScribeCommandObject getObjects(final ScribeCommandObject cADCommandObject, final String query,
        final String select, final String order) throws Exception {
    logger.debug("----Inside getObjects, query: " + query + " & select: " + select + " & order: " + order);

    /* Transfer the call to second method */
    if (query != null && query.toUpperCase().startsWith(queryPhoneFieldConst.toUpperCase())) {

        ScribeCommandObject returnObject = null;

        try {/*from w ww.  j  av a2  s . c o m*/
            /* Query CRM object by Phone field */
            returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select, order, "Phone");

        } catch (final ScribeException firstE) {

            /* Check if record is not found */
            if (firstE.getMessage().contains(ScribeResponseCodes._1004)) {

                try {
                    /* Query CRM object by Home Phone field */
                    returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select, order,
                            "Mobile Phone");
                } catch (final ScribeException secondE) {

                    /* Check if record is again not found */
                    if (secondE.getMessage().contains(ScribeResponseCodes._1004)) {

                        try {
                            /* Query CRM object by Home Phone field */
                            returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select, order,
                                    "Home Phone");
                        } catch (final ScribeException thirdE) {

                            /* Check if record is again not found */
                            if (thirdE.getMessage().contains(ScribeResponseCodes._1004)) {

                                try {
                                    /* Query CRM object by Home Phone field */
                                    returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select,
                                            order, "Other Phone");
                                } catch (final ScribeException fourthE) {

                                    /* Throw the error to user */
                                    throw fourthE;
                                }
                            }
                        }
                    }
                }
            }
        }

        return returnObject;
    } else {

        /* Get user from session manager */
        final ScribeCacheObject user = (ScribeCacheObject) cRMSessionManager
                .getSessionInfo(cADCommandObject.getCrmUserId());

        PostMethod postMethod = null;
        try {

            /* Get CRM information from user */
            final String serviceURL = user.getScribeMetaObject().getCrmServiceURL();
            final String serviceProtocol = user.getScribeMetaObject().getCrmServiceProtocol();
            final String sessionId = user.getScribeMetaObject().getCrmSessionId();

            /* Create Zoho URL */
            final String zohoURL = serviceProtocol + "://" + serviceURL + "/crm/private/xml/"
                    + cADCommandObject.getObjectType() + "s/getSearchRecords";

            logger.debug("----Inside getObjects zohoURL: " + zohoURL + " & sessionId: " + sessionId);

            /* Instantiate post method */
            postMethod = new PostMethod(zohoURL);

            /* Set request parameters */
            postMethod.setParameter("authtoken", sessionId.trim());
            postMethod.setParameter("scope", "crmapi");

            if (!query.equalsIgnoreCase("NONE")) {

                /* Create ZH query */
                final String zhQuery = ZHCRMMessageFormatUtils.createZHQuery(query);

                if (zhQuery != null && !"".equals(zhQuery)) {

                    /* Set search parameter in request */
                    postMethod.setParameter("searchCondition", "(" + zhQuery + ")");
                }
            } else {

                /* Without query param this method is not applicable */
                return this.getObjects(cADCommandObject);
            }

            if (!select.equalsIgnoreCase("ALL")) {

                /* Create ZH select CRM fields information */
                final String zhSelect = ZHCRMMessageFormatUtils.createZHSelect(cADCommandObject, select);

                /* Validate query */
                if (zhSelect != null && !"".equals(zhSelect)) {

                    /* Set request param to select fields */
                    postMethod.setParameter("selectColumns", zhSelect);
                }
            } else {

                /* Set request param to select all fields */
                postMethod.setParameter("selectColumns", "All");
            }

            /* Validate query */
            if (order != null && !"".equals(order)) {

                /* Validate ordering information */
                ZHCRMMessageFormatUtils.parseAndValidateOrderClause(order, orderFieldsSeparator);

                /* Set request param to select fields */
                postMethod.setParameter("sortColumnString",
                        ZHCRMMessageFormatUtils.createZHSortColumnString(order, orderFieldsSeparator));

                /* Set request param to select fields */
                postMethod.setParameter("sortOrderString",
                        ZHCRMMessageFormatUtils.createZHSortOrderString(order, orderFieldsSeparator));
            }

            final HttpClient httpclient = new HttpClient();

            /* Execute method */
            int result = httpclient.executeMethod(postMethod);
            logger.debug("----Inside getObjects response code: " + result + " & body: "
                    + postMethod.getResponseBodyAsString());

            /* Check if response if SUCCESS */
            if (result == HttpStatus.SC_OK) {

                /* Create XML document from response */
                final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                final DocumentBuilder builder = factory.newDocumentBuilder();
                final Document document = builder.parse(postMethod.getResponseBodyAsStream());

                /* Create new XPath object to query XML document */
                final XPath xpath = XPathFactory.newInstance().newXPath();

                /* XPath Query for showing all nodes value */
                final XPathExpression expr = xpath
                        .compile("/response/result/" + cADCommandObject.getObjectType() + "s/row");

                /* Get node list from response document */
                final NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

                /* Check if records founds */
                if (nodeList != null && nodeList.getLength() == 0) {

                    /* XPath Query for showing error message */
                    XPathExpression errorExpression = xpath.compile("/response/error/message");

                    /* Get erroe message from response document */
                    Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE);

                    /* Check if error message is found */
                    if (errorMessage != null) {

                        /* Send user error */
                        throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM : "
                                + errorMessage.getTextContent());
                    } else {

                        /* XPath Query for showing error message */
                        errorExpression = xpath.compile("/response/nodata/message");

                        /* Get erroe message from response document */
                        errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE);

                        /* Send user error */
                        throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM : "
                                + errorMessage.getTextContent());
                    }
                } else {

                    /* Create new Scribe object list */
                    final List<ScribeObject> cADbjectList = new ArrayList<ScribeObject>();

                    /* Iterate over node list */
                    for (int i = 0; i < nodeList.getLength(); i++) {

                        /* Create list of elements */
                        final List<Element> elementList = new ArrayList<Element>();

                        /* Get node from node list */
                        final Node node = nodeList.item(i);

                        /* Create new Scribe object */
                        final ScribeObject cADbject = new ScribeObject();

                        /* Check if node has child nodes */
                        if (node.hasChildNodes()) {

                            final NodeList subNodeList = node.getChildNodes();

                            /* Create new map for attributes */
                            final Map<String, String> attributeMap = new HashMap<String, String>();

                            /*
                             * Iterate over sub node list and create elements
                             */
                            for (int j = 0; j < subNodeList.getLength(); j++) {

                                final Node subNode = subNodeList.item(j);

                                /* This trick is to avoid empty nodes */
                                if (!subNode.getNodeName().contains("#text")) {

                                    /* Create element from response */
                                    final Element element = (Element) subNode;

                                    /* Populate label map */
                                    attributeMap.put("label", element.getAttribute("val"));

                                    /* Get node name */
                                    final String nodeName = element.getAttribute("val").replace(" ",
                                            spaceCharReplacement);

                                    /* Validate the node name */
                                    if (XMLChar.isValidName(nodeName)) {

                                        /* Add element in list */
                                        elementList.add(ZHCRMMessageFormatUtils.createMessageElement(nodeName,
                                                element.getTextContent(), attributeMap));
                                    } else {
                                        logger.debug(
                                                "----Inside getObjects, found invalid XML node; ignoring field: "
                                                        + element.getAttribute("val"));
                                    }
                                }
                            }
                        }

                        /* Add all CRM fields */
                        cADbject.setXmlContent(elementList);

                        /* Set type information in object */
                        cADbject.setObjectType(cADCommandObject.getObjectType());

                        /* Add Scribe object in list */
                        cADbjectList.add(cADbject);
                    }

                    /* Check if no record found */
                    if (cADbjectList.size() == 0) {
                        throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM");
                    }

                    /* Set the final object in command object */
                    cADCommandObject.setObject(cADbjectList.toArray(new ScribeObject[cADbjectList.size()]));
                }
            } else if (result == HttpStatus.SC_FORBIDDEN) {
                throw new ScribeException(ScribeResponseCodes._1022 + "Query is forbidden by Zoho CRM");
            } else if (result == HttpStatus.SC_BAD_REQUEST) {
                throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request content");
            } else if (result == HttpStatus.SC_UNAUTHORIZED) {
                throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zoho CRM");
            } else if (result == HttpStatus.SC_NOT_FOUND) {
                throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM");
            } else if (result == HttpStatus.SC_INTERNAL_SERVER_ERROR) {

                /* Create XML document from response */
                final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                final DocumentBuilder builder = factory.newDocumentBuilder();
                final Document document = builder.parse(postMethod.getResponseBodyAsStream());

                /* Create new XPath object to query XML document */
                final XPath xpath = XPathFactory.newInstance().newXPath();

                /* XPath Query for showing error message */
                final XPathExpression errorExpression = xpath.compile("/response/error/message");

                /* Get erroe message from response document */
                final Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE);

                if (errorMessage != null) {

                    /* Send user error */
                    throw new ScribeException(ScribeResponseCodes._1004
                            + "Requested data not found at Zoho CRM : " + errorMessage.getTextContent());
                } else {

                    /* Send user error */
                    throw new ScribeException(
                            ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM");
                }
            }
        } catch (final ScribeException exception) {
            throw exception;
        } catch (final ParserConfigurationException exception) {
            throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM");
        } catch (final SAXException exception) {
            throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM");
        } catch (final IOException exception) {
            throw new ScribeException(
                    ScribeResponseCodes._1022 + "Communication error while communicating with Zoho CRM");
        } finally {
            /* Release connection socket */
            if (postMethod != null) {
                postMethod.releaseConnection();
            }
        }

        return cADCommandObject;
    }
}

From source file:org.dasein.cloud.vcloud.vCloudMethod.java

public void parseMetaData(@Nonnull Taggable resource, @Nonnull String xml)
        throws CloudException, InternalException {
    Document doc = parseXML(xml);
    String docElementTagName = doc.getDocumentElement().getTagName();
    String nsString = "";
    if (docElementTagName.contains(":"))
        nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1);
    NodeList md = doc.getElementsByTagName(nsString + "MetadataEntry");

    for (int i = 0; i < md.getLength(); i++) {
        Node entry = md.item(i);// w  ww  . j  a  v  a 2s . co m

        if (entry.hasChildNodes()) {
            NodeList parts = entry.getChildNodes();
            String key = null, value = null;

            for (int j = 0; j < parts.getLength(); j++) {
                Node part = parts.item(j);
                if (part.getNodeName().contains(":"))
                    nsString = part.getNodeName().substring(0, part.getNodeName().indexOf(":") + 1);
                else
                    nsString = "";

                if (part.getNodeName().equalsIgnoreCase(nsString + "Key") && part.hasChildNodes()) {
                    key = part.getFirstChild().getNodeValue().trim();
                } else if (part.getNodeName().equalsIgnoreCase(nsString + "TypedValue")
                        && part.hasChildNodes()) {
                    NodeList values = part.getChildNodes();

                    for (int k = 0; k < values.getLength(); k++) {
                        Node v = values.item(k);

                        if (v.getNodeName().equalsIgnoreCase(nsString + "Value") && v.hasChildNodes()) {
                            value = v.getFirstChild().getNodeValue().trim();
                        }
                    }
                } else if (part.getNodeName().equalsIgnoreCase(nsString + "Value") && part.hasChildNodes()) {
                    value = part.getFirstChild().getNodeValue().trim();
                }
            }
            if (key != null && value != null) {
                resource.setTag(key, value);
            }
        }
    }
}

From source file:org.dasein.cloud.azure.compute.vm.AzureVM.java

private void parseStatus(@Nonnull ProviderContext ctx, @Nonnull String regionId, @Nonnull String serviceName,
        @Nonnull Node node, @Nonnull List<ResourceStatus> status) {
    ArrayList<ResourceStatus> list = new ArrayList<ResourceStatus>();
    NodeList attributes = node.getChildNodes();
    String id = "";
    ResourceStatus s = null;//  w  ww .j a va2  s.c om

    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);

        if (attribute.getNodeType() == Node.TEXT_NODE) {
            continue;
        }
        if (attribute.getNodeName().equalsIgnoreCase("roleinstancelist") && attribute.hasChildNodes()) {
            NodeList roleInstances = attribute.getChildNodes();

            for (int j = 0; j < roleInstances.getLength(); j++) {
                Node roleInstance = roleInstances.item(j);

                if (roleInstance.getNodeType() == Node.TEXT_NODE) {
                    continue;
                }
                if (roleInstance.getNodeName().equalsIgnoreCase("roleinstance")
                        && roleInstance.hasChildNodes()) {
                    NodeList roleAttributes = roleInstance.getChildNodes();

                    for (int l = 0; l < roleAttributes.getLength(); l++) {
                        Node roleAttribute = roleAttributes.item(l);

                        if (roleAttribute.getNodeType() == Node.TEXT_NODE) {
                            continue;
                        }
                        if (roleAttribute.getNodeName().equalsIgnoreCase("RoleName")
                                && roleAttribute.hasChildNodes()) {
                            String vmId = roleAttribute.getFirstChild().getNodeValue().trim();

                            id = serviceName + ":" + vmId;
                        } else if (roleAttribute.getNodeName().equalsIgnoreCase("PowerState")
                                && roleAttribute.hasChildNodes()) {
                            String powerStatus = roleAttribute.getFirstChild().getNodeValue().trim();

                            if ("Started".equalsIgnoreCase(powerStatus)) {
                                s = new ResourceStatus(id, VmState.RUNNING);
                            } else if ("Stopped".equalsIgnoreCase(powerStatus)) {
                                s = new ResourceStatus(id, VmState.STOPPED);
                            } else if ("Stopping".equalsIgnoreCase(powerStatus)) {
                                s = new ResourceStatus(id, VmState.STOPPING);
                            } else if ("Starting".equalsIgnoreCase(powerStatus)) {
                                s = new ResourceStatus(id, VmState.PENDING);
                            } else {
                                logger.warn("DEBUG: Unknown Azure status: " + powerStatus);
                            }
                        }
                    }
                    if (id == null) {
                        continue;
                    }

                    if (s != null) {
                        list.add(s);
                        s = null;
                    }
                }
            }
        }
    }
    for (ResourceStatus rs : list) {
        status.add(rs);
    }
}

From source file:org.dasein.cloud.azure.compute.vm.AzureVM.java

private void parseHostedServiceForStatus(@Nonnull ProviderContext ctx, @Nonnull Node entry,
        @Nullable String serviceName, @Nonnull List<ResourceStatus> status)
        throws CloudException, InternalException {
    String regionId = ctx.getRegionId();

    if (regionId == null) {
        throw new AzureConfigException("No region ID was specified for this request");
    }/*from  ww  w  .  ja  va2s .c  o m*/

    NodeList attributes = entry.getChildNodes();
    String uri = null;
    String service = null;

    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);

        if (attribute.getNodeType() == Node.TEXT_NODE) {
            continue;
        }
        if (attribute.getNodeName().equalsIgnoreCase("url") && attribute.hasChildNodes()) {
            uri = attribute.getFirstChild().getNodeValue().trim();
        } else if (attribute.getNodeName().equalsIgnoreCase("servicename") && attribute.hasChildNodes()) {
            service = attribute.getFirstChild().getNodeValue().trim();
            if (serviceName != null && !service.equals(serviceName)) {
                return;
            }
        } else if (attribute.getNodeName().equalsIgnoreCase("hostedserviceproperties")
                && attribute.hasChildNodes()) {
            NodeList properties = attribute.getChildNodes();

            boolean mediaLocationFound = false;
            for (int j = 0; j < properties.getLength(); j++) {
                Node property = properties.item(j);

                if (property.getNodeType() == Node.TEXT_NODE) {
                    continue;
                }
                if (property.getNodeName().equalsIgnoreCase("AffinityGroup") && property.hasChildNodes()) {
                    //get the region for this affinity group
                    String affinityGroup = property.getFirstChild().getNodeValue().trim();
                    if (affinityGroup != null && !affinityGroup.equals("")) {
                        AffinityGroup affinityGroupModel = getProvider().getComputeServices()
                                .getAffinityGroupSupport().get(affinityGroup);
                        if (affinityGroupModel == null)
                            return;

                        DataCenter dc = getProvider().getDataCenterServices()
                                .getDataCenter(affinityGroupModel.getDataCenterId());
                        if (dc != null && dc.getRegionId().equals(regionId)) {
                            mediaLocationFound = true;
                        } else {
                            // not correct region/datacenter
                            return;
                        }
                    }
                } else if (property.getNodeName().equalsIgnoreCase("location") && property.hasChildNodes()) {
                    if (!mediaLocationFound
                            && !regionId.equals(property.getFirstChild().getNodeValue().trim())) {
                        return;
                    }
                }
            }
        }
    }
    if (uri == null || service == null) {
        return;
    }

    AzureMethod method = new AzureMethod(getProvider());

    //dmayne 20130416: get the deployment names for each hosted service so we can then extract the detail
    String deployURL = HOSTED_SERVICES + "/" + service + "?embed-detail=true";
    Document deployDoc = method.getAsXML(ctx.getAccountNumber(), deployURL);

    if (deployDoc == null) {
        return;
    }
    NodeList deployments = deployDoc.getElementsByTagName("Deployments");
    for (int i = 0; i < deployments.getLength(); i++) {
        Node deployNode = deployments.item(i);
        NodeList deployAttributes = deployNode.getChildNodes();

        String deploymentName = "";
        for (int j = 0; j < deployAttributes.getLength(); j++) {
            Node deployment = deployAttributes.item(j);

            if (deployment.getNodeType() == Node.TEXT_NODE) {
                continue;
            }

            if (deployment.getNodeName().equalsIgnoreCase("Deployment") && deployment.hasChildNodes()) {
                NodeList dAttribs = deployment.getChildNodes();
                for (int k = 0; k < dAttribs.getLength(); k++) {
                    Node mynode = dAttribs.item(k);

                    if (mynode.getNodeName().equalsIgnoreCase("name") && mynode.hasChildNodes()) {
                        deploymentName = mynode.getFirstChild().getNodeValue().trim();

                        parseStatus(ctx, regionId, service + ":" + deploymentName, deployment, status);
                    }
                }
            }
        }
    }
}

From source file:org.dasein.cloud.vcloud.vCloudMethod.java

public void parseError(@Nonnull Node errorNode) throws CloudException {
    NodeList attributes = errorNode.getChildNodes();
    CloudErrorType type = CloudErrorType.GENERAL;
    String message = "Unknown";
    String major = "";
    String minor = "";

    Node n = errorNode.getAttributes().getNamedItem("minorErrorCode");

    if (n != null) {
        minor = n.getNodeValue().trim();
    }//  w  w w.  j  ava  2 s.c  o m
    n = errorNode.getAttributes().getNamedItem("majorErrorCode");

    if (n != null) {
        major = n.getNodeValue().trim();
    }
    n = errorNode.getAttributes().getNamedItem("message");

    if (n != null) {
        message = n.getNodeValue().trim();
    }
    for (int i = 0; i < attributes.getLength(); i++) {
        Node attr = attributes.item(i);

        if (attr.getNodeName().equalsIgnoreCase("message") && attr.hasChildNodes()) {
            message = attr.getFirstChild().getNodeValue().trim();
        } else if (attr.getNodeName().equalsIgnoreCase("majorErrorCode") && attr.hasChildNodes()) {
            major = attr.getFirstChild().getNodeValue().trim();
        } else if (attr.getNodeName().equalsIgnoreCase("minorErrorCode") && attr.hasChildNodes()) {
            minor = attr.getFirstChild().getNodeValue().trim();
        }
    }
    throw new CloudException(type, 200, major + ":" + minor, message);
}

From source file:gov.nasa.ensemble.core.jscience.csvxml.ProfileLoader.java

private ProfileWithLazyDatapointsFromCsv<?> createLazyProfile(Node columnElement)
        throws ProfileLoadingException {
    ProfileWithLazyDatapointsFromCsv result = new ProfileWithLazyDatapointsFromCsv(this);
    NamedNodeMap attributes = columnElement.getAttributes();
    result.setId(attributes.getNamedItem("id").getTextContent());
    Node unitAttribute = attributes.getNamedItem("units");
    if (unitAttribute == null) {
        result.setUnits(Unit.ONE);/*from   ww w  .  j  a v a2s.  c  o  m*/
    } else {
        String unitName = unitAttribute.getTextContent();
        Unit unit = null;
        try {
            unit = EnsembleUnitFormat.INSTANCE.parse(unitName);
        } catch (Exception e) {
            /* leave null */}
        if (unit == null)
            LogUtil.warn("Undefined unit name: " + unitName);
        result.setUnits(unit == null ? new BaseUnit(unitName + " (unrecognized units)") : unit);
    }

    Node displayNameAttribute = attributes.getNamedItem("displayName");
    if (displayNameAttribute == null) {
        result.setName(null);
    } else {
        result.setName(displayNameAttribute.getTextContent());
    }

    Node interpolationAttribute = attributes.getNamedItem("interpolation");
    String interpolationString = interpolationAttribute.getTextContent();
    result.setInterpolation(INTERPOLATION.valueOf(interpolationString.toUpperCase()));

    String typeAttribute = attributes.getNamedItem("type").getTextContent();
    result.setDataType(EMFUtils.createEDataTypeFromString(typeAttribute));

    Node defaultValueAttribute = attributes.getNamedItem("defaultValue");
    if (defaultValueAttribute != null) {
        String defaultValueString = defaultValueAttribute.getTextContent();
        result.setDefaultValue(parseValueCell(defaultValueString, Datatype.valueOf(typeAttribute)));
    }

    if (columnElement.hasChildNodes()) {
        NodeList properties = columnElement.getChildNodes();
        for (int i = 0; i < properties.getLength(); i++) {
            Node property = properties.item(i);
            if (property.getNodeType() == Node.ELEMENT_NODE) {
                NamedNodeMap propertyAttributes = property.getAttributes();
                result.getAttributes().put(propertyAttributes.getNamedItem("key").getTextContent(),
                        propertyAttributes.getNamedItem("value").getTextContent());
            }
        }
    }

    return result;
}

From source file:de.betterform.xml.xforms.model.Instance.java

/**
 * Inserts the specified node.// w  ww  .j a  va  2s .c o m
 *
 * @param parentNode the path pointing to the origin node.
 * @param beforeNode the path pointing to the node before which a clone of the
 *               origin node will be inserted.
 * @return 
 */
public Node insertNode(Node parentNode, Node originNode, Node beforeNode) throws XFormsException {
    // insert a deep clone of 'origin' node before 'before' node. if
    // 'before' node is null, the clone will be appended to 'parent' node.
    ModelItem miOrigin = getModelItem(originNode);
    Node insertedNode;
    if (originNode.getNodeType() == Node.ATTRIBUTE_NODE) {
        insertedNode = this.instanceDocument.importNode(originNode, true);
        ((Element) parentNode).setAttributeNode((Attr) insertedNode);
    } else {
        insertedNode = parentNode.insertBefore(this.instanceDocument.importNode(originNode, true), beforeNode);
    }
    String canonPath = DOMUtil.getCanonicalPath(insertedNode);

    ModelItem insertedModelItem = getModelItem(insertedNode);
    insertedModelItem.getDeclarationView().setDatatype(miOrigin.getDeclarationView().getDatatype());
    insertedModelItem.getDeclarationView().setConstraints(miOrigin.getDeclarationView().getConstraints());

    // get canonical path for inserted node
    String canonicalPath;
    if (beforeNode != null || originNode.getNodeType() == Node.ATTRIBUTE_NODE) {
        canonicalPath = BindingResolver.getCanonicalPath(insertedNode);
    } else {
        Node lastChild = ((DocumentTraversal) instanceDocument)
                .createTreeWalker(parentNode, NodeFilter.SHOW_ALL, null, false).lastChild();
        canonicalPath = BindingResolver.getCanonicalPath(lastChild);
    }

    String[] canonicalParts = XPathUtil.getNodesetAndPredicates(canonicalPath);

    if (originNode.hasChildNodes()) {
        setDatatypeOnChilds(originNode, insertedNode);
    }

    // dispatch internal betterform event (for instant repeat updating)
    HashMap map = new HashMap();
    map.put("nodeset", canonicalParts[0]);
    map.put("position", canonicalParts.length > 1 ? canonicalParts[1] : "1");
    map.put("canonPath", canonPath);
    this.container.dispatch(this.target, BetterFormEventNames.NODE_INSERTED, map);

    if (getLogger().isDebugEnabled()) {
        getLogger().debug(
                this + " insert node: instance data after manipulation" + toString(this.instanceDocument));
    }

    return insertedNode;
}

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

@Override
public @Nonnull Iterable<ResourceStatus> listDatabaseStatus() throws CloudException, InternalException {
    APITrace.begin(getProvider(), "RDBMS.listDatabaseStatus");
    try {//from   w ww.ja v  a  2 s. co m
        ArrayList<ResourceStatus> list = new ArrayList<ResourceStatus>();
        String marker = null;

        do {
            Map<String, String> parameters = getProvider().getStandardRdsParameters(getProvider().getContext(),
                    DESCRIBE_DB_INSTANCES);
            EC2Method method;
            NodeList blocks;
            Document doc;

            if (marker != null) {
                parameters.put("Marker", marker);
            }
            method = new EC2Method(SERVICE_ID, getProvider(), parameters);
            try {
                doc = method.invoke();
            } catch (EC2Exception e) {
                throw new CloudException(e);
            }
            marker = null;
            blocks = doc.getElementsByTagName("Marker");
            if (blocks.getLength() > 0) {
                for (int i = 0; i < blocks.getLength(); i++) {
                    Node item = blocks.item(i);

                    if (item.hasChildNodes()) {
                        marker = item.getFirstChild().getNodeValue().trim();
                    }
                }
                if (marker != null) {
                    break;
                }
            }
            blocks = doc.getElementsByTagName("DBInstances");
            for (int i = 0; i < blocks.getLength(); i++) {
                NodeList items = blocks.item(i).getChildNodes();

                for (int j = 0; j < items.getLength(); j++) {
                    Node item = items.item(j);

                    if (item.getNodeName().equals("DBInstance")) {
                        ResourceStatus status = toDatabaseStatus(item);

                        if (status != null) {
                            list.add(status);
                        }
                    }
                }
            }
        } while (marker != null);
        return list;
    } finally {
        APITrace.end();
    }
}

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

private void populateConfigurationList(String targetId, Jiterator<DatabaseConfiguration> iterator)
        throws CloudException, InternalException {
    APITrace.begin(getProvider(), "RDBMS.populateConfigurationList");
    try {//  w  w  w  .j a  v  a 2 s  .co m
        String marker = null;

        do {
            Map<String, String> parameters = getProvider().getStandardRdsParameters(getProvider().getContext(),
                    DESCRIBE_DB_PARAMETER_GROUPS);
            EC2Method method;
            NodeList blocks;
            Document doc;

            if (marker != null) {
                parameters.put("Marker", marker);
            }
            if (targetId != null) {
                parameters.put("DBParameterGroupName", targetId);
            }
            method = new EC2Method(SERVICE_ID, getProvider(), parameters);
            try {
                doc = method.invoke();
            } catch (EC2Exception e) {
                throw new CloudException(e);
            }
            marker = null;
            blocks = doc.getElementsByTagName("Marker");
            if (blocks.getLength() > 0) {
                for (int i = 0; i < blocks.getLength(); i++) {
                    Node item = blocks.item(i);

                    if (item.hasChildNodes()) {
                        marker = item.getFirstChild().getNodeValue().trim();
                    }
                }
                if (marker != null) {
                    break;
                }
            }
            blocks = doc.getElementsByTagName("DBParameterGroups");
            for (int i = 0; i < blocks.getLength(); i++) {
                NodeList items = blocks.item(i).getChildNodes();

                for (int j = 0; j < items.getLength(); j++) {
                    Node item = items.item(j);

                    if (item.getNodeName().equals("DBParameterGroup")) {
                        DatabaseConfiguration cfg = toConfiguration(item);

                        if (cfg != null) {
                            iterator.push(cfg);
                        }
                    }
                }
            }
        } while (marker != null);
    } finally {
        APITrace.end();
    }
}