List of usage examples for org.apache.commons.httpclient.methods PostMethod setParameter
public void setParameter(String paramString1, String paramString2)
From source file:com.tacitknowledge.maven.plugin.crx.CRXPackageInstallerPlugin.java
/** * @param cookies/*from w w w . ja v a 2 s .co m*/ * get a session using the same existing previously requested * response cookies. * @throws MojoExecutionException * if any error occurred during this process. */ @SuppressWarnings("deprecation") private void getSession(final Cookie[] cookies) throws MojoExecutionException { PostMethod loginPost = new PostMethod(crxPath + "/login.jsp"); loginPost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); try { getLog().info("login to " + loginPost.getPath()); loginPost.setParameter("Workspace", workspace); loginPost.setParameter("UserId", login); loginPost.setParameter("Password", password); HttpClient client = new HttpClient(); client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY); client.getState().addCookies(cookies); client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_DEFAULT_TIMEOUT); int status = client.executeMethod(loginPost); // log the status getLog().info( "Response status: " + status + ", statusText: " + HttpStatus.getStatusText(status) + "\r\n"); if (status == HttpStatus.SC_MOVED_TEMPORARILY) { getLog().info("Login successful"); } else { logResponseDetails(loginPost); throw new MojoExecutionException("Login failed, response=" + HttpStatus.getStatusText(status)); } } catch (Exception ex) { getLog().error("ERROR: " + ex.getClass().getName() + " " + ex.getMessage()); throw new MojoExecutionException(ex.getMessage()); } finally { loginPost.releaseConnection(); } }
From source file:com.worldline.easycukes.rest.client.RestService.java
/** * Allows to send a POST request, with parameters using JSON format * * @param path path to be used for the POST request * @param data paremeters to be used (JSON format) as a string *///www . j a v a 2 s . c o m @SuppressWarnings("unchecked") public void sendPost(final String path, final String data) throws Exception { String fullpath = path; if (path.startsWith("/")) fullpath = baseUrl + path; log.info("Sending POST request to " + fullpath); final PostMethod method = new PostMethod(fullpath); for (final Map.Entry<String, String> header : requestHeaders.entrySet()) method.setRequestHeader(header.getKey(), header.getValue()); if (data != null) { JSONObject jsonObject = null; try { jsonObject = JSONHelper.toJSONObject(data); for (final Iterator<String> iterator = jsonObject.keySet().iterator(); iterator.hasNext();) { final String param = iterator.next(); method.setParameter(param, (jsonObject.get(param) != null) ? jsonObject.get(param).toString() : null); } } catch (final ParseException e) { log.error("Sorry, parameters are not proper JSON...", e); throw new IOException(e.getMessage(), e); } } try { if (nonProxyHost != null && fullpath.contains(nonProxyHost)) { httpClient.getHostConfiguration().setProxyHost(null); } final int statusCode = httpClient.executeMethod(method); response = new ResponseWrapper(method.getResponseBodyAsString(), method.getResponseHeaders(), statusCode); } catch (final IOException e) { log.error(e.getMessage(), e); throw new IOException(e.getMessage(), e); } finally { method.releaseConnection(); } }
From source file:com.osbitools.ws.shared.auth.SamlSecurityProvider.java
/** * Look for a session and if it's completed or not found try * re-validate existing security token *///from ww w . j a va 2 s . co m @Override public void validate(HttpServletRequest req, String stoken) throws WsSrvException { Session session = activeSessions.get(stoken); if (!(session == null || session.isFinished())) // Everything fine return; getLogger(req).debug("Local session validation faied." + " Sending POST request to validate SAML session"); // Revalidate session PostMethod post = new PostMethod(_login); try { String ars = createAuthnRequest(getServiceLocation(req), getRefererUrl(req)); post.setParameter("SAMLRequest", ars); } catch (MarshallingException | SignatureException | IOException e) { //-- 63 throw new WsSrvException(63, e); } HttpClient hc = (new HttpClientBuilder()).buildClient(); post.setRequestHeader("Cookie", (String) req.getSession().getServletContext().getAttribute("scookie_name") + "=" + stoken); int result; try { result = hc.executeMethod(post); } catch (IOException e) { //-- 66 throw new WsSrvException(66, e); } // Expecting 200 if cookie valid and 302 if not, rest are errors if (result == HttpStatus.SC_OK) { // Extract end process SAML response from form String rb; try { rb = new String(post.getResponseBody()); } catch (IOException e) { //-- 67 throw new WsSrvException(67, e); } Matcher m = SAML_RESP.matcher(rb); if (m.matches() && m.groupCount() == 1) { String gs = m.group(1); // Convert hex decoded javascript variable String msg = ""; int start = 0; Matcher m1 = HP.matcher(gs); while (m1.find()) { String dc = m1.group(1); int i = Integer.decode("#" + dc); int st = m1.start(); int ed = m1.end(); msg += gs.substring(start, st) + (char) i; start = ed; } try { procAuthnResponse(req, msg, stoken); } catch (Exception e) { //-- 62 throw new WsSrvException(62, e); } } } else if (result == HttpStatus.SC_MOVED_TEMPORARILY) { //-- 64 throw new WsSrvException(64, "Redirect received"); } else { //-- 65 throw new WsSrvException(65, "Unexpected http return code " + result); } }
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; try {//ww w .j a v a2 s . c o m /* 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:com.inbravo.scribe.rest.service.crm.ZHRESTCRMService.java
/** * /*w ww . j a v a 2 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.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 {/* ww w . j a va2s . c om*/ /* 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.j a va 2 s .c o m /* Query CRM object by Phone field */ returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select, null, "Phone"); } catch (final ScribeException firstE) { /* Check if record is not found */ if (firstE.getMessage().contains(ScribeResponseCodes._1004)) { try { /* Query CRM object by Mobile field */ returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select, null, "Mobile"); } catch (final ScribeException secondE) { /* Check if record is again not found */ if (secondE.getMessage().contains(ScribeResponseCodes._1004)) { try { /* Query CRM object by Home Phone field */ returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select, null, "Home Phone"); } catch (final ScribeException thirdE) { /* Check if record is again not found */ if (thirdE.getMessage().contains(ScribeResponseCodes._1004)) { try { /* Query CRM object by Other Phone field */ returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select, null, "Other Phone"); } catch (final ScribeException fourthE) { /* Throw the error to user */ throw fourthE; } } } } } } } return returnObject; } else { /* Get user from session manager */ final ScribeCacheObject user = (ScribeCacheObject) cRMSessionManager .getSessionInfo(cADCommandObject.getCrmUserId()); PostMethod postMethod = null; try { /* Get CRM information from user */ final String serviceURL = user.getScribeMetaObject().getCrmServiceURL(); final String serviceProtocol = user.getScribeMetaObject().getCrmServiceProtocol(); final String sessionId = user.getScribeMetaObject().getCrmSessionId(); /* Create Zoho URL */ final String zohoURL = serviceProtocol + "://" + serviceURL + "/crm/private/xml/" + cADCommandObject.getObjectType() + "s/getSearchRecords"; logger.debug("----Inside getObjects zohoURL: " + zohoURL + " & sessionId: " + sessionId); /* Instantiate post method */ postMethod = new PostMethod(zohoURL); /* Set request parameters */ postMethod.setParameter("authtoken", sessionId.trim()); postMethod.setParameter("scope", "crmapi"); if (!query.equalsIgnoreCase("NONE")) { /* Create ZH query */ final String zhQuery = ZHCRMMessageFormatUtils.createZHQuery(query); if (zhQuery != null && !"".equals(zhQuery)) { /* Set search parameter in request */ postMethod.setParameter("searchCondition", "(" + zhQuery + ")"); } } else { /* Without query param this method is not applicable */ return this.getObjects(cADCommandObject); } if (!select.equalsIgnoreCase("ALL")) { /* Create ZH select CRM fields information */ final String zhSelect = ZHCRMMessageFormatUtils.createZHSelect(cADCommandObject, select); /* Validate query */ if (zhSelect != null && !"".equals(zhSelect)) { /* Set request param to select fields */ postMethod.setParameter("selectColumns", zhSelect); } } else { /* Set request param to select all fields */ postMethod.setParameter("selectColumns", "All"); } final HttpClient httpclient = new HttpClient(); /* Execute method */ int result = httpclient.executeMethod(postMethod); logger.debug("----Inside getObjects response code: " + result + " & body: " + postMethod.getResponseBodyAsString()); /* Check if response if SUCCESS */ if (result == HttpStatus.SC_OK) { /* Create XML document from response */ final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.parse(postMethod.getResponseBodyAsStream()); /* Create new XPath object to query XML document */ final XPath xpath = XPathFactory.newInstance().newXPath(); /* XPath Query for showing all nodes value */ final XPathExpression expr = xpath .compile("/response/result/" + cADCommandObject.getObjectType() + "s/row"); /* Get node list from response document */ final NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET); /* Check if records founds */ if (nodeList != null && nodeList.getLength() == 0) { /* XPath Query for showing error message */ XPathExpression errorExpression = xpath.compile("/response/error/message"); /* Get erroe message from response document */ Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE); /* Check if error message is found */ if (errorMessage != null) { /* Send user error */ throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM : " + errorMessage.getTextContent()); } else { /* XPath Query for showing error message */ errorExpression = xpath.compile("/response/nodata/message"); /* Get erroe message from response document */ errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE); /* Send user error */ throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM : " + errorMessage.getTextContent()); } } else { /* Create new Scribe object list */ final List<ScribeObject> cADbjectList = new ArrayList<ScribeObject>(); /* Iterate over node list */ for (int i = 0; i < nodeList.getLength(); i++) { /* Create list of elements */ final List<Element> elementList = new ArrayList<Element>(); /* Get node from node list */ final Node node = nodeList.item(i); /* Create new Scribe object */ final ScribeObject cADbject = new ScribeObject(); /* Check if node has child nodes */ if (node.hasChildNodes()) { final NodeList subNodeList = node.getChildNodes(); /* Create new map for attributes */ final Map<String, String> attributeMap = new HashMap<String, String>(); /* * Iterate over sub node list and create elements */ for (int j = 0; j < subNodeList.getLength(); j++) { final Node subNode = subNodeList.item(j); /* This trick is to avoid empty nodes */ if (!subNode.getNodeName().contains("#text")) { /* Create element from response */ final Element element = (Element) subNode; /* Populate label map */ attributeMap.put("label", element.getAttribute("val")); /* Get node name */ final String nodeName = element.getAttribute("val").replace(" ", spaceCharReplacement); /* Validate the node name */ if (XMLChar.isValidName(nodeName)) { /* Add element in list */ elementList.add(ZHCRMMessageFormatUtils.createMessageElement(nodeName, element.getTextContent(), attributeMap)); } else { logger.debug( "----Inside getObjects, found invalid XML node; ignoring field: " + element.getAttribute("val")); } } } } /* Add all CRM fields */ cADbject.setXmlContent(elementList); /* Set type information in object */ cADbject.setObjectType(cADCommandObject.getObjectType()); /* Add Scribe object in list */ cADbjectList.add(cADbject); } /* Check if no record found */ if (cADbjectList.size() == 0) { throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM"); } /* Set the final object in command object */ cADCommandObject.setObject(cADbjectList.toArray(new ScribeObject[cADbjectList.size()])); } } else if (result == HttpStatus.SC_FORBIDDEN) { throw new ScribeException(ScribeResponseCodes._1022 + "Query is forbidden by Zoho CRM"); } else if (result == HttpStatus.SC_BAD_REQUEST) { throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request content"); } else if (result == HttpStatus.SC_UNAUTHORIZED) { throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zoho CRM"); } else if (result == HttpStatus.SC_NOT_FOUND) { throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM"); } else if (result == HttpStatus.SC_INTERNAL_SERVER_ERROR) { /* Create XML document from response */ final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.parse(postMethod.getResponseBodyAsStream()); /* Create new XPath object to query XML document */ final XPath xpath = XPathFactory.newInstance().newXPath(); /* XPath Query for showing error message */ final XPathExpression errorExpression = xpath.compile("/response/error/message"); /* Get erroe message from response document */ final Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE); if (errorMessage != null) { /* Send user error */ throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM : " + errorMessage.getTextContent()); } else { /* Send user error */ throw new ScribeException( ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM"); } } } catch (final ScribeException exception) { throw exception; } catch (final ParserConfigurationException exception) { throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM"); } catch (final SAXException exception) { throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM"); } catch (final IOException exception) { throw new ScribeException( ScribeResponseCodes._1022 + "Communication error while communicating with Zoho CRM"); } finally { /* Release connection socket */ if (postMethod != null) { postMethod.releaseConnection(); } } return cADCommandObject; } }
From source file:com.inbravo.scribe.rest.service.crm.ZHRESTCRMService.java
@Override public final ScribeCommandObject getObjects(final ScribeCommandObject cADCommandObject, final String query, final String select, final String order) throws Exception { logger.debug("----Inside getObjects, query: " + query + " & select: " + select + " & order: " + order); /* Transfer the call to second method */ if (query != null && query.toUpperCase().startsWith(queryPhoneFieldConst.toUpperCase())) { ScribeCommandObject returnObject = null; try {/* www. ja v a 2 s .c o m*/ /* Query CRM object by Phone field */ returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select, order, "Phone"); } catch (final ScribeException firstE) { /* Check if record is not found */ if (firstE.getMessage().contains(ScribeResponseCodes._1004)) { try { /* Query CRM object by Home Phone field */ returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select, order, "Mobile Phone"); } catch (final ScribeException secondE) { /* Check if record is again not found */ if (secondE.getMessage().contains(ScribeResponseCodes._1004)) { try { /* Query CRM object by Home Phone field */ returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select, order, "Home Phone"); } catch (final ScribeException thirdE) { /* Check if record is again not found */ if (thirdE.getMessage().contains(ScribeResponseCodes._1004)) { try { /* Query CRM object by Home Phone field */ returnObject = this.getObjectsByPhoneField(cADCommandObject, query, select, order, "Other Phone"); } catch (final ScribeException fourthE) { /* Throw the error to user */ throw fourthE; } } } } } } } return returnObject; } else { /* Get user from session manager */ final ScribeCacheObject user = (ScribeCacheObject) cRMSessionManager .getSessionInfo(cADCommandObject.getCrmUserId()); PostMethod postMethod = null; try { /* Get CRM information from user */ final String serviceURL = user.getScribeMetaObject().getCrmServiceURL(); final String serviceProtocol = user.getScribeMetaObject().getCrmServiceProtocol(); final String sessionId = user.getScribeMetaObject().getCrmSessionId(); /* Create Zoho URL */ final String zohoURL = serviceProtocol + "://" + serviceURL + "/crm/private/xml/" + cADCommandObject.getObjectType() + "s/getSearchRecords"; logger.debug("----Inside getObjects zohoURL: " + zohoURL + " & sessionId: " + sessionId); /* Instantiate post method */ postMethod = new PostMethod(zohoURL); /* Set request parameters */ postMethod.setParameter("authtoken", sessionId.trim()); postMethod.setParameter("scope", "crmapi"); if (!query.equalsIgnoreCase("NONE")) { /* Create ZH query */ final String zhQuery = ZHCRMMessageFormatUtils.createZHQuery(query); if (zhQuery != null && !"".equals(zhQuery)) { /* Set search parameter in request */ postMethod.setParameter("searchCondition", "(" + zhQuery + ")"); } } else { /* Without query param this method is not applicable */ return this.getObjects(cADCommandObject); } if (!select.equalsIgnoreCase("ALL")) { /* Create ZH select CRM fields information */ final String zhSelect = ZHCRMMessageFormatUtils.createZHSelect(cADCommandObject, select); /* Validate query */ if (zhSelect != null && !"".equals(zhSelect)) { /* Set request param to select fields */ postMethod.setParameter("selectColumns", zhSelect); } } else { /* Set request param to select all fields */ postMethod.setParameter("selectColumns", "All"); } /* Validate query */ if (order != null && !"".equals(order)) { /* Validate ordering information */ ZHCRMMessageFormatUtils.parseAndValidateOrderClause(order, orderFieldsSeparator); /* Set request param to select fields */ postMethod.setParameter("sortColumnString", ZHCRMMessageFormatUtils.createZHSortColumnString(order, orderFieldsSeparator)); /* Set request param to select fields */ postMethod.setParameter("sortOrderString", ZHCRMMessageFormatUtils.createZHSortOrderString(order, orderFieldsSeparator)); } final HttpClient httpclient = new HttpClient(); /* Execute method */ int result = httpclient.executeMethod(postMethod); logger.debug("----Inside getObjects response code: " + result + " & body: " + postMethod.getResponseBodyAsString()); /* Check if response if SUCCESS */ if (result == HttpStatus.SC_OK) { /* Create XML document from response */ final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.parse(postMethod.getResponseBodyAsStream()); /* Create new XPath object to query XML document */ final XPath xpath = XPathFactory.newInstance().newXPath(); /* XPath Query for showing all nodes value */ final XPathExpression expr = xpath .compile("/response/result/" + cADCommandObject.getObjectType() + "s/row"); /* Get node list from response document */ final NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET); /* Check if records founds */ if (nodeList != null && nodeList.getLength() == 0) { /* XPath Query for showing error message */ XPathExpression errorExpression = xpath.compile("/response/error/message"); /* Get erroe message from response document */ Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE); /* Check if error message is found */ if (errorMessage != null) { /* Send user error */ throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM : " + errorMessage.getTextContent()); } else { /* XPath Query for showing error message */ errorExpression = xpath.compile("/response/nodata/message"); /* Get erroe message from response document */ errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE); /* Send user error */ throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM : " + errorMessage.getTextContent()); } } else { /* Create new Scribe object list */ final List<ScribeObject> cADbjectList = new ArrayList<ScribeObject>(); /* Iterate over node list */ for (int i = 0; i < nodeList.getLength(); i++) { /* Create list of elements */ final List<Element> elementList = new ArrayList<Element>(); /* Get node from node list */ final Node node = nodeList.item(i); /* Create new Scribe object */ final ScribeObject cADbject = new ScribeObject(); /* Check if node has child nodes */ if (node.hasChildNodes()) { final NodeList subNodeList = node.getChildNodes(); /* Create new map for attributes */ final Map<String, String> attributeMap = new HashMap<String, String>(); /* * Iterate over sub node list and create elements */ for (int j = 0; j < subNodeList.getLength(); j++) { final Node subNode = subNodeList.item(j); /* This trick is to avoid empty nodes */ if (!subNode.getNodeName().contains("#text")) { /* Create element from response */ final Element element = (Element) subNode; /* Populate label map */ attributeMap.put("label", element.getAttribute("val")); /* Get node name */ final String nodeName = element.getAttribute("val").replace(" ", spaceCharReplacement); /* Validate the node name */ if (XMLChar.isValidName(nodeName)) { /* Add element in list */ elementList.add(ZHCRMMessageFormatUtils.createMessageElement(nodeName, element.getTextContent(), attributeMap)); } else { logger.debug( "----Inside getObjects, found invalid XML node; ignoring field: " + element.getAttribute("val")); } } } } /* Add all CRM fields */ cADbject.setXmlContent(elementList); /* Set type information in object */ cADbject.setObjectType(cADCommandObject.getObjectType()); /* Add Scribe object in list */ cADbjectList.add(cADbject); } /* Check if no record found */ if (cADbjectList.size() == 0) { throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM"); } /* Set the final object in command object */ cADCommandObject.setObject(cADbjectList.toArray(new ScribeObject[cADbjectList.size()])); } } else if (result == HttpStatus.SC_FORBIDDEN) { throw new ScribeException(ScribeResponseCodes._1022 + "Query is forbidden by Zoho CRM"); } else if (result == HttpStatus.SC_BAD_REQUEST) { throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request content"); } else if (result == HttpStatus.SC_UNAUTHORIZED) { throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zoho CRM"); } else if (result == HttpStatus.SC_NOT_FOUND) { throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM"); } else if (result == HttpStatus.SC_INTERNAL_SERVER_ERROR) { /* Create XML document from response */ final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.parse(postMethod.getResponseBodyAsStream()); /* Create new XPath object to query XML document */ final XPath xpath = XPathFactory.newInstance().newXPath(); /* XPath Query for showing error message */ final XPathExpression errorExpression = xpath.compile("/response/error/message"); /* Get erroe message from response document */ final Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE); if (errorMessage != null) { /* Send user error */ throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM : " + errorMessage.getTextContent()); } else { /* Send user error */ throw new ScribeException( ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM"); } } } catch (final ScribeException exception) { throw exception; } catch (final ParserConfigurationException exception) { throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM"); } catch (final SAXException exception) { throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM"); } catch (final IOException exception) { throw new ScribeException( ScribeResponseCodes._1022 + "Communication error while communicating with Zoho CRM"); } finally { /* Release connection socket */ if (postMethod != null) { postMethod.releaseConnection(); } } return cADCommandObject; } }
From source file:com.inbravo.scribe.rest.service.crm.ZHRESTCRMService.java
@Override public final ScribeCommandObject createObject(final ScribeCommandObject cADCommandObject) throws Exception { logger.debug("----Inside createObject"); /* Get user from session manager */ final ScribeCacheObject user = (ScribeCacheObject) cRMSessionManager .getSessionInfo(cADCommandObject.getCrmUserId()); PostMethod postMethod = null; try {/*from ww w .j a v a 2 s . com*/ /* 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/insertRecords"; logger.debug("----Inside createObject, zohoURL: " + zohoURL + " & sessionId: " + sessionId); /* Instantiate post method */ postMethod = new PostMethod(zohoURL); final String xmlData = ZHCRMMessageFormatUtils.createRequestString(cADCommandObject, spaceCharReplacement, permittedDateFormats, zohoInputDateFormat); /* Validate xmlData */ if (xmlData != null && !"".equals(xmlData)) { /* Set request param to send request data */ postMethod.setParameter("xmlData", xmlData); } /* 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 createObject 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/recorddetail"); /* Get node list from response document */ final NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET); /* Check if records founds */ if (nodeList.getLength() == 0) { /* 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); /* Send user error */ throw new ScribeException(ScribeResponseCodes._1004 + "Not able to create record at Zoho CRM : " + errorMessage.getTextContent()); } else { /* Iterate over node list */ for (int i = 0; i < nodeList.getLength(); i++) { /* Get node from node list */ final Node node = nodeList.item(i); /* Check if node has child nodes */ if (node.hasChildNodes()) { final NodeList subNodeList = node.getChildNodes(); /* 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; if (element.getAttribute("val").equalsIgnoreCase(("ID"))) { /* Set object id in request object */ cADCommandObject.getObject()[0] = ZHCRMMessageFormatUtils.addNode("Id", element.getTextContent(), cADCommandObject.getObject()[0]); } } } } } } } 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 + "Not able to create record at Zoho CRM : " + errorMessage.getTextContent()); } else { /* Send user error */ throw new ScribeException(ScribeResponseCodes._1004 + "Not able to create record 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", exception); } catch (final SAXException exception) { throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM", exception); } catch (final IOException exception) { throw new ScribeException( ScribeResponseCodes._1022 + "Communication error while communicating with Zoho CRM", exception); } finally { /* Release connection socket */ if (postMethod != null) { postMethod.releaseConnection(); } } return cADCommandObject; }
From source file:com.bluexml.xforms.controller.alfresco.AlfrescoController.java
/** * Request post. Bridge to our XForms webscript under Alfresco. //$$ TRACE * LOG/*from ww w.j ava2 s. c om*/ * * @param transaction * the transaction. MANDATORY and NEVER <code>null</code> * @param parameters * the parameters * @param opCode * the code for the webscript operation being called. * @param dataSourceURI * @return the post method * @throws IOException * Signals that an I/O exception has occurred. * @throws HttpException * the http exception * @throws ServletException */ private PostMethod requestPost(AlfrescoTransaction transaction, Map<String, String> parameters, MsgId opCode, String dataSourceURI) throws IOException, ServletException { // // security: enforce use of possible access controls on the Alfresco side. if (transaction == null) { logger.error("Null transaction."); throw new ServletException("A transaction is required for webscript requests."); } String legitimateLogin = transaction.getLogin(); if (legitimateLogin == null) { legitimateLogin = getParamUserName(transaction.getPage().getInitParams()); } if (StringUtils.trimToNull(legitimateLogin) == null) { logger.error("No user name in the transaction."); throw new ServletException( "Cannot complete the action: a user name is required for webscript requests."); } // // log some info if (loggertrace.isTraceEnabled()) { logger.trace("Calling the webscript for user '" + legitimateLogin + "' with request: " + opCode); logger.trace("Parameters : "); Set<Entry<String, String>> entrySet2 = parameters.entrySet(); for (Entry<String, String> entry2 : entrySet2) { String value = entry2.getValue(); if (value == null) { value = NULL_STRING; } else if (value.equals("")) { value = EMPTY_STRING; } logger.trace(" " + entry2.getKey() + " = " + value); } } // set url String url; boolean useDataSource = dataSourceURI != null && dataSourceURI.startsWith("http"); if (useDataSource) { // it's possible that url have parameters so to avoid conflic with sidereader parameters '&' is replaced by '#' url = dataSourceURI.replaceAll("@\\$@", "&"); } else { url = ALFRESCO_XFORMS_URL + opCode; } PostMethod post = new PostMethod(url); if (!useDataSource) { Set<Entry<String, String>> entrySet = parameters.entrySet(); for (Entry<String, String> entry : entrySet) { post.setParameter(entry.getKey(), entry.getValue()); } // if (StringUtils.trimToNull(transaction.getLogin()) == null) { // post.setParameter("username", getParamLoginUserName(transaction.getInitParams())); // } else { // post.setParameter("username", transaction.getLogin()); // } post.setParameter("username", transaction.getLogin()); post.setParameter("serviceCallerId", "XFormsController"); post.setParameter("serviceCallerVersion", "2.0.0"); } else { Gson gson = new Gson(); String json = gson.toJson(parameters); post.setParameter("xformsParameters", json); } post.addRequestHeader("Content-Type", PostMethod.FORM_URL_ENCODED_CONTENT_TYPE + "; charset=UTF-8"); executeMethod(post, false); if (loggertrace.isTraceEnabled()) { logger.trace("Response : "); String responseBodyAsString = post.getResponseBodyAsString(); if (responseBodyAsString == null) { logger.trace(NULL_STRING); } else if (responseBodyAsString.equals("")) { logger.trace(EMPTY_STRING); } else { logger.trace(responseBodyAsString); } } return post; }