Example usage for javax.xml.xpath XPathExpression evaluate

List of usage examples for javax.xml.xpath XPathExpression evaluate

Introduction

In this page you can find the example usage for javax.xml.xpath XPathExpression evaluate.

Prototype

public Object evaluate(InputSource source, QName returnType) throws XPathExpressionException;

Source Link

Document

Evaluate the compiled XPath expression in the context of the specified InputSource and return the result as the specified type.

Usage

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

@Override
public final ScribeCommandObject getObjects(final ScribeCommandObject cADCommandObject) throws Exception {
    logger.debug("----Inside getObjects");

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

    PostMethod postMethod = null;//from   w  ww  . j  a v a2s. c o m
    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/getRecords";

        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");

        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:de.egore911.versioning.deployer.performer.PerformCopy.java

private boolean copy(String uri, String target, String targetFilename) {
    URL url;//  www .j a va 2  s . c o  m
    try {
        url = new URL(uri);
    } catch (MalformedURLException e) {
        LOG.error("Invalid URI: {}", e.getMessage(), e);
        return false;
    }
    try {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        int response = connection.getResponseCode();

        int lastSlash = uri.lastIndexOf('/');
        if (lastSlash < 0) {
            LOG.error("Invalid URI: {}", uri);
            return false;
        }

        int lastDot = uri.lastIndexOf('.');
        if (lastDot < 0) {
            LOG.error("Invalid URI: {}", uri);
            return false;
        }

        String filename;
        if (StringUtils.isEmpty(targetFilename)) {
            filename = uri.substring(lastSlash + 1);
        } else {
            filename = targetFilename;
        }

        XmlHolder xmlHolder = XmlHolder.getInstance();
        XPathExpression finalNameXpath = xmlHolder.xPath.compile("/project/build/finalName/text()");

        if (response == HttpURLConnection.HTTP_OK) {
            String downloadFilename = UrlUtil.concatenateUrlWithSlashes(target, filename);

            File downloadFile = new File(downloadFilename);
            FileUtils.forceMkdir(downloadFile.getParentFile());
            try (InputStream in = connection.getInputStream();
                    FileOutputStream out = new FileOutputStream(downloadFilename)) {
                IOUtils.copy(in, out);
            }
            LOG.debug("Downloaded {} to {}", url, downloadFilename);

            if (StringUtils.isEmpty(targetFilename)) {
                // Check if finalName if exists in pom.xml
                String destFile = null;
                try (ZipFile zipFile = new ZipFile(downloadFilename)) {
                    Enumeration<? extends ZipEntry> entries = zipFile.entries();
                    while (entries.hasMoreElements()) {
                        ZipEntry entry = entries.nextElement();
                        if (entry.getName().endsWith("/pom.xml")) {

                            String finalNameInPom;
                            try (InputStream inputStream = zipFile.getInputStream(entry)) {
                                try {
                                    MavenXpp3Reader mavenreader = new MavenXpp3Reader();
                                    Model model = mavenreader.read(inputStream);
                                    finalNameInPom = model.getBuild().getFinalName();
                                } catch (Exception e) {
                                    Document doc = xmlHolder.documentBuilder.parse(inputStream);
                                    finalNameInPom = (String) finalNameXpath.evaluate(doc,
                                            XPathConstants.STRING);
                                }
                            }

                            if (StringUtils.isNotEmpty(finalNameInPom)) {
                                destFile = UrlUtil.concatenateUrlWithSlashes(target,
                                        finalNameInPom + "." + uri.substring(lastDot + 1));
                            }
                            break;
                        }
                    }
                }

                // Move file to finalName if existed in pom.xml
                if (destFile != null) {
                    try {
                        File dest = new File(destFile);
                        if (dest.exists()) {
                            FileUtils.forceDelete(dest);
                        }
                        FileUtils.moveFile(downloadFile.getAbsoluteFile(), dest.getAbsoluteFile());
                        LOG.debug("Moved file from {} to {}", downloadFilename, destFile);
                    } catch (IOException e) {
                        LOG.error("Failed to move file to it's final name: {}", e.getMessage(), e);
                    }
                }
            }

            return true;
        } else {
            LOG.error("Could not download file: {}", uri);
            return false;
        }
    } catch (SAXException | IOException | XPathExpressionException e) {
        LOG.error("Could not download file ({}): {}", uri, e.getMessage(), e);
        return false;
    }
}

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

/**
 * /*  w w  w . j av  a2  s . c om*/
 * @param cADCommandObject
 * @param query
 * @param select
 * @param order
 * @return
 * @throws Exception
 */
private final ScribeCommandObject getObjectsByPhoneField(final ScribeCommandObject cADCommandObject,
        final String query, final String select, final String order, final String phoneFieldName)
        throws Exception {
    logger.debug("----Inside getObjectsByAllPhoneNumbers, query: " + query + " & select: " + select
            + " & order: " + order + " & phoneFieldName: " + phoneFieldName);

    /* 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 getObjectsByAllPhoneNumbers 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.createZHQueryForPhoneFields(query, phoneFieldName);

            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 != null && !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 getObjectsByAllPhoneNumbers 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 getObjectsByAllPhoneNumbers, 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.ephesoft.dcma.gwt.admin.bm.server.BatchClassManagementServiceImpl.java

private String getValueFromXML(Document doc, String xPathExpression) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    String requiredValue = BatchClassManagementConstants.EMPTY_STRING;
    try {//w  ww  .  ja va2 s . c o m
        XPathExpression expr = xpath.compile(xPathExpression);
        Object result = expr.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;
        requiredValue = nodes.item(0).getFirstChild().getNodeValue();
    } catch (Exception e) {
    }
    return requiredValue;
}

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

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

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

        ScribeCommandObject returnObject = null;

        try {/*from   w  w  w . j  ava  2s.  c  o  m*/
            /* Query CRM object by Phone field */
            returnObject = this.getObjectsByPhoneField(cADCommandObject, query, null, 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, null, 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, null, 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, null,
                                            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);
            }

            /* 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) 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.ja  v a2  s.  c  om
            /* 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 {/*  w  w w. j a  v  a 2s .  c  om*/
            /* 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:com.cloud.network.resource.PaloAltoResource.java

public boolean responseNotEmpty(String response) throws ExecutionException {
    NodeList response_body;//from ww w .ja  v  a  2s.  c  o  m
    Document doc = getDocument(response);
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {
        XPathExpression expr = xpath.compile("/response[@status='success']");
        response_body = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        throw new ExecutionException(e.getCause().getMessage());
    }

    if (response_body.getLength() > 0
            && (!response_body.item(0).getTextContent().equals("") || (response_body.item(0).hasChildNodes()
                    && response_body.item(0).getFirstChild().hasChildNodes()))) {
        return true;
    } else {
        return false;
    }
}

From source file:com.cloud.network.resource.PaloAltoResource.java

private boolean login(String username, String password) throws ExecutionException {
    Map<String, String> params = new HashMap<String, String>();
    params.put("type", "keygen");
    params.put("user", username);
    params.put("password", password);

    String keygenBody;//from w  w  w .  j a  v  a 2s  .  c  o m
    try {
        keygenBody = request(PaloAltoMethod.GET, params);
    } catch (ExecutionException e) {
        return false;
    }
    Document keygen_doc = getDocument(keygenBody);
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {
        XPathExpression expr = xpath.compile("/response[@status='success']/result/key/text()");
        _key = (String) expr.evaluate(keygen_doc, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        throw new ExecutionException(e.getCause().getMessage());
    }
    if (_key != null) {
        return true;
    }
    return false;
}

From source file:com.cloud.network.resource.PaloAltoResource.java

private String getPrivateSubnet(String vlan) throws ExecutionException {
    String _interfaceName = genPrivateInterfaceName(Long.parseLong(vlan));
    Map<String, String> params = new HashMap<String, String>();
    params.put("type", "config");
    params.put("action", "get");
    params.put("xpath", "/config/devices/entry/network/interface/" + _privateInterfaceType + "/entry[@name='"
            + _privateInterface + "']/layer3/units/entry[@name='" + _interfaceName + "']/ip/entry");
    String response = request(PaloAltoMethod.GET, params);
    if (validResponse(response) && responseNotEmpty(response)) {
        NodeList response_body;//from  www.  j av  a  2  s .c  o  m
        Document doc = getDocument(response);
        XPath xpath = XPathFactory.newInstance().newXPath();
        try {
            XPathExpression expr = xpath.compile("/response[@status='success']/result/entry");
            response_body = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            throw new ExecutionException(e.getCause().getMessage());
        }
        if (response_body.getLength() > 0) {
            return response_body.item(0).getAttributes().getNamedItem("name").getTextContent();
        }
    }
    return null;
}