Example usage for javax.xml.xpath XPath compile

List of usage examples for javax.xml.xpath XPath compile

Introduction

In this page you can find the example usage for javax.xml.xpath XPath compile.

Prototype

public XPathExpression compile(String expression) throws XPathExpressionException;

Source Link

Document

Compile an XPath expression for later evaluation.

Usage

From source file:cz.cas.lib.proarc.common.export.mets.structure.MetsElementVisitor.java

private Node getPremisEvent(IMetsElement metsElement, String datastream, FileMD5Info md5Info,
        String eventDetail) throws MetsExportException {
    PremisComplexType premis = new PremisComplexType();
    ObjectFactory factory = new ObjectFactory();
    JAXBElement<PremisComplexType> jaxbPremix = factory.createPremis(premis);
    EventComplexType event = factory.createEventComplexType();
    premis.getEvent().add(event);//from  w w  w.j a v a2s.  co  m
    event.setEventDateTime(md5Info.getCreated().toXMLFormat());
    event.setEventDetail(eventDetail);
    EventIdentifierComplexType eventIdentifier = new EventIdentifierComplexType();
    event.setEventIdentifier(eventIdentifier);
    event.setEventType("derivation");
    eventIdentifier.setEventIdentifierType("ProArc_EventID");
    eventIdentifier.setEventIdentifierValue(Const.dataStreamToEvent.get(datastream));
    EventOutcomeInformationComplexType eventInformation = new EventOutcomeInformationComplexType();
    event.getEventOutcomeInformation().add(eventInformation);
    eventInformation.getContent().add(factory.createEventOutcome("successful"));
    LinkingAgentIdentifierComplexType linkingAgentIdentifier = new LinkingAgentIdentifierComplexType();
    linkingAgentIdentifier.setLinkingAgentIdentifierType("ProArc_AgentID");
    linkingAgentIdentifier.setLinkingAgentIdentifierValue("ProArc");
    linkingAgentIdentifier.getLinkingAgentRole().add("software");
    LinkingObjectIdentifierComplexType linkingObject = new LinkingObjectIdentifierComplexType();
    linkingObject.setLinkingObjectIdentifierType("ProArc_URI");
    linkingObject.setLinkingObjectIdentifierValue(
            Const.FEDORAPREFIX + metsElement.getOriginalPid() + "/" + Const.dataStreamToModel.get(datastream));
    event.getLinkingObjectIdentifier().add(linkingObject);
    event.getLinkingAgentIdentifier().add(linkingAgentIdentifier);
    JAXBContext jc;
    try {
        jc = JAXBContext.newInstance(PremisComplexType.class);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.newDocument();

        // Marshal the Object to a Document
        Marshaller marshaller = jc.createMarshaller();
        marshaller.marshal(jaxbPremix, document);
        XPath xpath = XPathFactory.newInstance().newXPath();
        Node premisNode = (Node) xpath.compile("*[local-name()='premis']/*[local-name()='event']")
                .evaluate(document, XPathConstants.NODE);
        return premisNode;
    } catch (Exception e) {
        throw new MetsExportException(metsElement.getOriginalPid(), "Error while generating premis data", false,
                e);
    }
}

From source file:com.zimbra.qa.unittest.TestCalDav.java

/**
 * http://svn.calendarserver.org/repository/calendarserver/CalendarServer/trunk/doc/Extensions/caldav-proxy.txt
 * This is an Apple standard implemented by Apple Mac OSX at least up to Yosemite and offers a fairly simple
 * sharing model for calendars.  The model is simpler than Zimbra's native model and there are mismatches,
 * for instance Zimbra requires the proposed delegate to accept shares.
 *///from ww w  .j  a  v  a2s . c o  m
@Test
public void testAppleCaldavProxyFunctions() throws ServiceException, IOException {
    Account sharer = users[3].create();
    Account sharee1 = users[1].create();
    Account sharee2 = users[2].create();
    ZMailbox mboxSharer = TestUtil.getZMailbox(sharer.getName());
    ZMailbox mboxSharee1 = TestUtil.getZMailbox(sharee1.getName());
    ZMailbox mboxSharee2 = TestUtil.getZMailbox(sharee2.getName());
    setZimbraPrefAppleIcalDelegationEnabled(mboxSharer, true);
    setZimbraPrefAppleIcalDelegationEnabled(mboxSharee1, true);
    setZimbraPrefAppleIcalDelegationEnabled(mboxSharee2, true);
    // Test PROPPATCH to "calendar-proxy-read" URL
    setGroupMemberSet(TestCalDav.getCalendarProxyReadUrl(sharer), sharer, sharee2);
    // Test PROPPATCH to "calendar-proxy-write" URL
    setGroupMemberSet(TestCalDav.getCalendarProxyWriteUrl(sharer), sharer, sharee1);

    // verify that adding new members to groups triggered notification messages
    List<ZMessage> msgs = TestUtil.waitForMessages(mboxSharee1,
            "in:inbox subject:\"Share Created: Calendar shared by \"", 1, 10000);
    assertNotNull(String.format("Notification msgs for %s", sharee1.getName()), msgs);
    assertEquals(String.format("num msgs for %s", sharee1.getName()), 1, msgs.size());

    msgs = TestUtil.waitForMessages(mboxSharee2, "in:inbox subject:\"Share Created: Calendar shared by \"", 1,
            10000);
    assertNotNull(String.format("Notification msgs for %s", sharee2.getName()), msgs);
    assertEquals(String.format("num msgs for %s", sharee2.getName()), 1, msgs.size());
    // Simulate acceptance of the shares (would normally need to be done in ZWC
    createCalendarMountPoint(mboxSharee1, sharer);
    createCalendarMountPoint(mboxSharee2, sharer);
    Document doc = delegateForExpandProperty(sharee1);
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(TestCalDav.NamespaceContextForXPath.forCalDAV());
    XPathExpression xPathExpr;
    try {
        String xpathS = "/D:multistatus/D:response/D:href/text()";
        xPathExpr = xpath.compile(xpathS);
        NodeList result = (NodeList) xPathExpr.evaluate(doc, XPathConstants.NODESET);
        assertEquals(String.format("num XPath nodes for %s for %s", xpathS, sharee1.getName()), 1,
                result.getLength());
        String text = (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
        assertEquals("HREF for account owner", UrlNamespace.getPrincipalUrl(sharee1).replaceAll("@", "%40"),
                text);

        xpathS = "/D:multistatus/D:response/D:propstat/D:prop/CS:calendar-proxy-write-for/D:response/D:href/text()";
        xPathExpr = xpath.compile(xpathS);
        result = (NodeList) xPathExpr.evaluate(doc, XPathConstants.NODESET);
        assertEquals(String.format("num XPath nodes for %s for %s", xpathS, sharee1.getName()), 1,
                result.getLength());
        text = (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
        assertEquals("HREF for sharer", UrlNamespace.getPrincipalUrl(sharer).replaceAll("@", "%40"), text);
    } catch (XPathExpressionException e1) {
        ZimbraLog.test.debug("xpath problem", e1);
    }
    // Check that proxy write has sharee1 in it
    doc = groupMemberSetExpandProperty(sharer, sharee1, true);
    // Check that proxy read has sharee2 in it
    doc = groupMemberSetExpandProperty(sharer, sharee2, false);
    String davBaseName = "notAllowed@There";
    String url = String.format("%s%s",
            getFolderUrl(sharee1, "Shared Calendar").replaceAll(" ", "%20").replaceAll("@", "%40"),
            davBaseName);
    HttpMethodExecutor exe = doIcalPut(url, sharee1, simpleEvent(sharer), HttpStatus.SC_MOVED_TEMPORARILY);
    String location = null;
    for (Header hdr : exe.respHeaders) {
        if ("Location".equals(hdr.getName())) {
            location = hdr.getValue();
        }
    }
    assertNotNull("Location Header not returned when creating", location);
    url = String.format("%s%s",
            getFolderUrl(sharee1, "Shared Calendar").replaceAll(" ", "%20").replaceAll("@", "%40"),
            location.substring(location.lastIndexOf('/') + 1));
    doIcalPut(url, sharee1, simpleEvent(sharer), HttpStatus.SC_CREATED);
}

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

/**
 * //from   w  w  w. jav  a 2s .c o m
 * @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.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   ww  w . j a  v  a 2  s .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 va2  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:cz.cas.lib.proarc.common.export.mets.structure.MetsElementVisitor.java

/**
 * Generates the premis for amdSec//from   ww w .j a v  a 2  s  .  c  o  m
 *
 * @param metsElement
 * @param datastream
 * @param md5Info
 * @param created
 * @param formatVersion
 * @return
 * @throws MetsExportException
 */
private Node getPremisFile(IMetsElement metsElement, String datastream, FileMD5Info md5Info)
        throws MetsExportException {
    PremisComplexType premis = new PremisComplexType();
    ObjectFactory factory = new ObjectFactory();
    JAXBElement<PremisComplexType> jaxbPremix = factory.createPremis(premis);
    cz.cas.lib.proarc.premis.File file = factory.createFile();
    premis.getObject().add(file);
    ObjectIdentifierComplexType objectIdentifier = new ObjectIdentifierComplexType();
    objectIdentifier.setObjectIdentifierType("ProArc_URI");
    objectIdentifier.setObjectIdentifierValue(
            Const.FEDORAPREFIX + metsElement.getOriginalPid() + "/" + Const.dataStreamToModel.get(datastream));
    file.getObjectIdentifier().add(objectIdentifier);
    PreservationLevelComplexType preservation = new PreservationLevelComplexType();
    if ("RAW".equals(datastream)) {
        preservation.setPreservationLevelValue("deleted");
    } else {
        preservation.setPreservationLevelValue("preservation");
    }
    file.getPreservationLevel().add(preservation);
    ObjectCharacteristicsComplexType characteristics = new ObjectCharacteristicsComplexType();
    characteristics.setCompositionLevel(BigInteger.ZERO);
    file.getObjectCharacteristics().add(characteristics);
    FixityComplexType fixity = new FixityComplexType();
    fixity.setMessageDigest(md5Info.getMd5());
    fixity.setMessageDigestAlgorithm("MD5");
    fixity.setMessageDigestOriginator("ProArc");
    characteristics.getFixity().add(fixity);
    characteristics.setSize(md5Info.getSize());
    FormatComplexType format = new FormatComplexType();
    characteristics.getFormat().add(format);
    FormatDesignationComplexType formatDesignation = new FormatDesignationComplexType();
    formatDesignation.setFormatName(md5Info.getMimeType());
    formatDesignation.setFormatVersion(md5Info.getFormatVersion());
    JAXBElement<FormatDesignationComplexType> jaxbDesignation = factory
            .createFormatDesignation(formatDesignation);
    format.getContent().add(jaxbDesignation);
    FormatRegistryComplexType formatRegistry = new FormatRegistryComplexType();
    formatRegistry.setFormatRegistryName("PRONOM");
    formatRegistry.setFormatRegistryKey(Const.mimeToFmtMap.get(md5Info.getMimeType()));
    JAXBElement<FormatRegistryComplexType> jaxbRegistry = factory.createFormatRegistry(formatRegistry);
    format.getContent().add(jaxbRegistry);

    CreatingApplicationComplexType creatingApplication = new CreatingApplicationComplexType();
    characteristics.getCreatingApplication().add(creatingApplication);
    creatingApplication.getContent().add(factory.createCreatingApplicationName("ProArc"));

    creatingApplication.getContent()
            .add(factory.createCreatingApplicationVersion(metsElement.getMetsContext().getProarcVersion()));
    creatingApplication.getContent()
            .add(factory.createDateCreatedByApplication(MetsUtils.getCurrentDate().toXMLFormat()));

    RelationshipComplexType relationShip = new RelationshipComplexType();

    if (!("RAW").equals(datastream)) {
        relationShip.setRelationshipType("derivation");
        relationShip.setRelationshipSubType("created from");
        RelatedObjectIdentificationComplexType relatedObject = new RelatedObjectIdentificationComplexType();
        relationShip.getRelatedObjectIdentification().add(relatedObject);
        relatedObject.setRelatedObjectIdentifierType("ProArc_URI");
        relatedObject.setRelatedObjectIdentifierValue(
                Const.FEDORAPREFIX + metsElement.getOriginalPid() + "/" + Const.dataStreamToModel.get("RAW"));
        RelatedEventIdentificationComplexType eventObject = new RelatedEventIdentificationComplexType();
        relationShip.getRelatedEventIdentification().add(eventObject);
        eventObject.setRelatedEventIdentifierType("ProArc_EventID");
        eventObject.setRelatedEventIdentifierValue(Const.dataStreamToEvent.get(datastream));
        eventObject.setRelatedEventSequence(BigInteger.ONE);
        file.getRelationship().add(relationShip);
    } else {
        relationShip.setRelationshipType("creation");
        relationShip.setRelationshipSubType("created from");
        LinkingEventIdentifierComplexType eventIdentifier = new LinkingEventIdentifierComplexType();
        file.getLinkingEventIdentifier().add(eventIdentifier);
        eventIdentifier.setLinkingEventIdentifierType("ProArc_EventID");
        eventIdentifier.setLinkingEventIdentifierValue(Const.dataStreamToEvent.get(datastream));
    }

    String originalFile = MetsUtils.xPathEvaluateString(metsElement.getRelsExt(),
            "*[local-name()='RDF']/*[local-name()='Description']/*[local-name()='importFile']");
    OriginalNameComplexType originalName = factory.createOriginalNameComplexType();
    originalName.setValue(originalFile);
    file.setOriginalName(originalName);

    JAXBContext jc;
    try {
        jc = JAXBContext.newInstance(PremisComplexType.class);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.newDocument();

        // Marshal the Object to a Document
        Marshaller marshaller = jc.createMarshaller();
        marshaller.marshal(jaxbPremix, document);
        XPath xpath = XPathFactory.newInstance().newXPath();
        Node premisNode = (Node) xpath.compile("*[local-name()='premis']/*[local-name()='object']")
                .evaluate(document, XPathConstants.NODE);
        return premisNode;
    } catch (Exception e) {
        throw new MetsExportException(metsElement.getOriginalPid(), "Error while generating premis data", false,
                e);
    }
}

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 va 2  s  .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.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 {//from   ww  w  . java2s  .  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.cloud.network.resource.PaloAltoResource.java

public boolean responseNotEmpty(String response) throws ExecutionException {
    NodeList response_body;/* www .j av 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 2 s .  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;
}