List of usage examples for org.w3c.dom Node hasChildNodes
public boolean hasChildNodes();
From source file:channellistmaker.dataextractor.AbstractEPGFileExtractor.java
/** * trace??????????????/*w w w . ja v a 2 s. c om*/ * @param node * @return trace?????????????????????????? */ protected final String dumpNode(final Node node) { if (LOG.isTraceEnabled()) { if (node == null) { //???? return ""; } else { final StringBuilder sb = new StringBuilder(); final String nodeName_t; if (node.getNodeName() != null && !"".equals(node.getNodeName())) { nodeName_t = node.getNodeName(); } else { nodeName_t = "no_Name"; } sb.append(nodeName_t).append(" [ "); /* ? */ sb.append("Node_type = ").append(node.getNodeType()).append(" "); sb.append(" "); /*(??)*/ NamedNodeMap attrs = node.getAttributes(); // NamedNodeMap?? if (attrs != null) { sb.append("Attribute [ "); for (int index = 0; index < attrs.getLength(); index++) { Node attr = attrs.item(index); // sb.append("( "); sb.append("Attribute_name = ").append(attr.getNodeName()).append(" "); // ???? sb.append("Attribute_value = ").append(attr.getNodeValue()).append(" "); // ? sb.append(")"); } sb.append(" ] "); } /* ? sb.append("] "); */ sb.append("Node_value = ").append(node.getNodeValue()).append(" "); /*(??)?? */ if (node.hasChildNodes()) { sb.append(" \n"); NodeList Children = node.getChildNodes(); int Nodes = Children.getLength(); for (int i = 0; i < Nodes; i++) { Node child = Children.item(i); sb.append(dumpNode(child)); } } sb.append("] "); return sb.toString(); } } else { return ""; } }
From source file:com.flexive.core.storage.GenericDivisionImporter.java
/** * Import sequencer settings/*w w w.java 2 s . c om*/ * * @param con an open and valid connection to store imported data * @param zip zip file containing the data * @throws Exception on errors */ public void importSequencers(Connection con, ZipFile zip) throws Exception { ZipEntry ze = getZipEntry(zip, FILE_SEQUENCERS); Statement stmt = con.createStatement(); try { SequencerStorage seq = StorageManager.getSequencerStorage(); for (CustomSequencer cust : seq.getCustomSequencers()) seq.removeSequencer(cust.getName()); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(zip.getInputStream(ze)); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xPath.evaluate("/sequencers/syssequence", document, XPathConstants.NODESET); Node currNode; String seqName; long value; for (int i = 0; i < nodes.getLength(); i++) { currNode = nodes.item(i); if (currNode.hasChildNodes()) { seqName = null; value = -1L; for (int j = 0; j < currNode.getChildNodes().getLength(); j++) if (currNode.getChildNodes().item(j).getNodeName().equals("name")) { seqName = currNode.getChildNodes().item(j).getTextContent(); } else if (currNode.getChildNodes().item(j).getNodeName().equals("value")) { value = Long.parseLong(currNode.getChildNodes().item(j).getTextContent()); } if (value != -1L && seqName != null) { try { if (value <= 0) value = 1; //make sure we have a valid value FxSystemSequencer sseq = FxSystemSequencer.valueOf(seqName); //check if this is really a system sequencer seq.setSequencerId(sseq.getSequencerName(), value); LOG.info("Set sequencer [" + seqName + "] to [" + value + "]"); } catch (IllegalArgumentException e) { LOG.error("Could not find system sequencer named [" + seqName + "]!"); } } } } nodes = (NodeList) xPath.evaluate("/sequencers/usrsequence", document, XPathConstants.NODESET); boolean rollOver = false; for (int i = 0; i < nodes.getLength(); i++) { currNode = nodes.item(i); if (currNode.hasChildNodes()) { seqName = null; value = -1L; for (int j = 0; j < currNode.getChildNodes().getLength(); j++) if (currNode.getChildNodes().item(j).getNodeName().equals("name")) { seqName = currNode.getChildNodes().item(j).getTextContent(); } else if (currNode.getChildNodes().item(j).getNodeName().equals("value")) { value = Long.parseLong(currNode.getChildNodes().item(j).getTextContent()); } else if (currNode.getChildNodes().item(j).getNodeName().equals("rollover")) { rollOver = "1".equals(currNode.getChildNodes().item(j).getTextContent()); } if (value != -1L && seqName != null) { seq.createSequencer(seqName, rollOver, value); LOG.info("Created sequencer [" + seqName + "] with start value [" + value + "], rollover: " + rollOver); } } } } finally { Database.closeObjects(GenericDivisionImporter.class, stmt); } }
From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java
/** * Thread-safety tested// www. j av a 2 s. co m */ @Override public Map<String, Object> deleteElementByPath(String path, final String originalXml) throws SAXException, IOException, XPathExpressionException { Assert.hasText(path); Assert.hasText(originalXml); Document originalDom = parse(originalXml); Document finalDom = originalDom; XPath xPath = getXPathInstance(); // find all the nodes specified by xPathString in the finalDom, and // delete them all NodeList existingNodeList = (NodeList) (xPath.evaluate(path, finalDom, XPathConstants.NODESET)); int el = existingNodeList.getLength(); logger.trace("find '" + el + "' in originalDom using xPath: " + path); for (int i = 0; i < el; i++) { Node c = existingNodeList.item(i); Node cp = c.getParentNode(); // remove this node from its parent... cp.removeChild(c); logger.trace("node has child : " + cp.getChildNodes().getLength() + ":" + cp.hasChildNodes()); } logger.trace(DomUtils.elementToString(finalDom)); Map<String, Object> resultMap = new HashMap<String, Object>(3); resultMap.put("finalXml", DomUtils.elementToString(finalDom)); resultMap.put("isDeleted", true); return resultMap; }
From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java
@Override public synchronized Map<String, Object> deleteElementByPathById(String path, final String originalXml, String elementId) throws SAXException, IOException, XPathExpressionException { Assert.hasText(path);/*from www. j a v a 2 s .com*/ Assert.hasText(originalXml); Assert.hasText(elementId); Document originalDom = parse(originalXml); Document finalDom = originalDom; String xPathString = path + "[@id='" + elementId + "']"; XPath xPath = getXPathInstance(); // find all the nodes specified by xPathString in the finalDom, and // delete them all NodeList existingNodeList = (NodeList) (xPath.evaluate(xPathString, finalDom, XPathConstants.NODESET)); int el = existingNodeList.getLength(); logger.trace("find '" + el + "' in originalDom using xPath: " + xPathString); for (int i = 0; i < el; i++) { Node c = existingNodeList.item(i); Node cp = c.getParentNode(); // remove this node from its parent... cp.removeChild(c); logger.trace("node has child : " + cp.getChildNodes().getLength() + ":" + cp.hasChildNodes()); } logger.trace(DomUtils.elementToString(finalDom)); Map<String, Object> resultMap = new HashMap<String, Object>(3); resultMap.put("finalXml", DomUtils.elementToString(finalDom)); resultMap.put("isDeleted", true); return resultMap; }
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;// w ww. j a v a 2 s. c o m try { /* Get CRM information from user */ final String serviceURL = user.getScribeMetaObject().getCrmServiceURL(); final String serviceProtocol = user.getScribeMetaObject().getCrmServiceProtocol(); final String sessionId = user.getScribeMetaObject().getCrmSessionId(); /* Create Zoho URL */ final String zohoURL = serviceProtocol + "://" + serviceURL + "/crm/private/xml/" + cADCommandObject.getObjectType() + "s/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:org.openremote.android.test.console.net.ORConnectionTest.java
/** * Asserts the panel XML definition contains all the necessary elements * for the integration tests.// w w w. j a va 2 s.com * * @throws IOException if connection fails for any reason, see checkURLWithHTTPProtocol javadoc * @throws ParserConfigurationException if DOM parsing fails on return data * @throws SAXException if parsing fails on return data */ public void testControllerGETRestFullPanelXML() throws IOException, ParserConfigurationException, SAXException { final String TESTURL = TEST_CONTROLLER_URL + RESTAPI_FULLPANEL_URI + "SimpleName"; HttpResponse response = ORConnection.checkURLWithHTTPProtocol(activity, ORHttpMethod.GET, TESTURL, NO_HTTP_AUTH); assertHttpResponse(response, TESTURL, HttpURLConnection.HTTP_OK); // TODO : // This should be fixed in Controller 2.0 Alpha 12 -- uncomment when online test controller // has been upgraded (currently returns 'text/plain') // try { assertMimeType(response, APPLICATIONXML_MIME_TYPE); fail("\n\nIncorrect content-type issue has been fixed, please update this test.\n\n"); } catch (Throwable t) { // TODO: Ignore for now, remove the check once content-type issue has been fixed. } Document doc = getDOMDocument(response); assertOpenRemoteRootElement(doc); NodeList list = doc.getElementsByTagName("screens"); assertTrue("Expected one <screens> element in panel definition.", list.getLength() == 1); list = doc.getElementsByTagName("groups"); assertTrue("Expected one <groups> element in panel definition.", list.getLength() == 1); list = doc.getElementsByTagName("group"); assertTrue("Expected at least one group in the panel definition.", list.getLength() >= 1); Set<String> screenReferences = new HashSet<String>(10); for (int groupIndex = 0; groupIndex < list.getLength(); ++groupIndex) { Node group = list.item(groupIndex); if (group.getNodeType() != Node.ELEMENT_NODE) continue; assertTrue("Expected <group> to have child elements, found none.", group.hasChildNodes()); NodeList includes = group.getChildNodes(); assertTrue("Expected at least one included screen in the group.", includes.getLength() >= 1); for (int includeIndex = 0; includeIndex < includes.getLength(); ++includeIndex) { Node include = includes.item(includeIndex); if (include.getNodeType() != Node.ELEMENT_NODE) continue; NamedNodeMap attrs = include.getAttributes(); assertNotNull("Expected to find attributes in include", attrs); assertNotNull("Expected to find 'ref' attribute in <include>, got null", attrs.getNamedItem("ref")); Node ref = attrs.getNamedItem("ref"); String screenRef = ref.getNodeValue(); screenReferences.add(screenRef); } } list = doc.getElementsByTagName("screen"); Set<String> screenIDs = new HashSet<String>(10); assertTrue("Expected at least one <screen> in panel definition.", list.getLength() >= 1); for (int screenIndex = 0; screenIndex < list.getLength(); ++screenIndex) { Node screen = list.item(screenIndex); NamedNodeMap attrs = screen.getAttributes(); assertNotNull("Expected to find 'id' attribute in screen, not null.", attrs.getNamedItem("id")); Node id = attrs.getNamedItem("id"); screenIDs.add(id.getNodeValue()); } for (String ref : screenReferences) { assertTrue("Expected to find screen with id: " + ref, screenIDs.contains(ref)); } list = doc.getElementsByTagName("button"); assertTrue("Expected at least two <button> elements, got " + list.getLength(), list.getLength() >= 2); Set<String> buttonIDs = new HashSet<String>(10); for (int btnIndex = 0; btnIndex < list.getLength(); ++btnIndex) { Node button = list.item(btnIndex); NamedNodeMap attrs = button.getAttributes(); assertNotNull("Expected to find attributes in <button>, got null.", attrs); assertNotNull("Expected to find id attribute in <button>.", attrs.getNamedItem("id")); Node id = attrs.getNamedItem("id"); buttonIDs.add(id.getNodeValue()); } assertTrue("Expected to find a button with ID=22", buttonIDs.contains("22")); assertTrue("Expected to find a button with ID=24", buttonIDs.contains("24")); list = doc.getElementsByTagName("switch"); assertTrue("Expected at least one <switch> element, got " + list.getLength(), list.getLength() >= 1); Set<String> switchIDs = new HashSet<String>(10); Set<String> sensorReferences = new HashSet<String>(10); for (int switchIndex = 0; switchIndex < list.getLength(); ++switchIndex) { Node switchComp = list.item(switchIndex); NamedNodeMap attrs = switchComp.getAttributes(); assertNotNull("Expected to find attributes in <switch>, got null.", attrs); assertNotNull("Expected to find id attribute in <switch>.", attrs.getNamedItem("id")); Node id = attrs.getNamedItem("id"); switchIDs.add(id.getNodeValue()); NodeList links = switchComp.getChildNodes(); for (int linksIndex = 0; linksIndex < links.getLength(); ++linksIndex) { Node link = links.item(linksIndex); if (link.getNodeType() != Node.ELEMENT_NODE) continue; if (!link.getNodeName().equalsIgnoreCase("link")) continue; NamedNodeMap linkAttrs = link.getAttributes(); assertNotNull("Expected attributes on <link>, got null.", linkAttrs); Node typeAttr = linkAttrs.getNamedItem("type"); if (typeAttr.getNodeValue().equalsIgnoreCase("sensor")) { Node refAttr = linkAttrs.getNamedItem("ref"); assertNotNull("Expected a 'ref' attribute in 'sensor' link, didn't find it.", refAttr); sensorReferences.add(refAttr.getNodeValue()); } } } assertTrue("Expected to find a switch with ID=28", switchIDs.contains("28")); assertTrue("Expected to find sensor link with ID=29", sensorReferences.contains("29")); }
From source file:com.twinsoft.convertigo.beans.core.Sequence.java
private static Node cloneNodeWithUserData(Node node, boolean recurse) { if (node != null) { Object node_output = node.getUserData(Step.NODE_USERDATA_OUTPUT); Node clonedNode = node.cloneNode(false); clonedNode.setUserData(Step.NODE_USERDATA_OUTPUT, node_output, null); if (node.getNodeType() == Node.ELEMENT_NODE) { // attributes NamedNodeMap attributeMap = clonedNode.getAttributes(); for (int i = 0; i < attributeMap.getLength(); i++) { Node clonedAttribute = attributeMap.item(i); String attr_name = clonedAttribute.getNodeName(); Object attr_output = ((Element) node).getAttributeNode(attr_name) .getUserData(Step.NODE_USERDATA_OUTPUT); clonedAttribute.setUserData(Step.NODE_USERDATA_OUTPUT, attr_output, null); }/*from ww w. ja va 2 s . c om*/ // recurse on element child nodes only if (recurse && node.hasChildNodes()) { NodeList list = node.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node clonedChild = cloneNodeWithUserData(list.item(i), recurse); if (clonedChild != null) { clonedNode.appendChild(clonedChild); } } } } return clonedNode; } return null; }
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;/* w w w. j av a 2s . c o m*/ try { /* Get CRM information from user */ final String serviceURL = user.getScribeMetaObject().getCrmServiceURL(); final String serviceProtocol = user.getScribeMetaObject().getCrmServiceProtocol(); final String sessionId = user.getScribeMetaObject().getCrmSessionId(); /* Create Zoho URL */ final String zohoURL = serviceProtocol + "://" + serviceURL + "/crm/private/xml/" + cADCommandObject.getObjectType() + "s/getRecords"; logger.debug("----Inside getObjects zohoURL: " + zohoURL + " & sessionId: " + sessionId); /* Instantiate post method */ postMethod = new PostMethod(zohoURL); /* Set request parameters */ postMethod.setParameter("authtoken", sessionId.trim()); postMethod.setParameter("scope", "crmapi"); final HttpClient httpclient = new HttpClient(); /* Execute method */ int result = httpclient.executeMethod(postMethod); logger.debug("----Inside getObjects response code: " + result + " & body: " + postMethod.getResponseBodyAsString()); /* Check if response if SUCCESS */ if (result == HttpStatus.SC_OK) { /* Create XML document from response */ final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.parse(postMethod.getResponseBodyAsStream()); /* Create new XPath object to query XML document */ final XPath xpath = XPathFactory.newInstance().newXPath(); /* XPath Query for showing all nodes value */ final XPathExpression expr = xpath .compile("/response/result/" + cADCommandObject.getObjectType() + "s/row"); /* Get node list from response document */ final NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET); /* Check if records founds */ if (nodeList != null && nodeList.getLength() == 0) { /* XPath Query for showing error message */ XPathExpression errorExpression = xpath.compile("/response/error/message"); /* Get erroe message from response document */ Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE); /* Check if error message is found */ if (errorMessage != null) { /* Send user error */ throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM : " + errorMessage.getTextContent()); } else { /* XPath Query for showing error message */ errorExpression = xpath.compile("/response/nodata/message"); /* Get erroe message from response document */ errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE); /* Send user error */ throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM : " + errorMessage.getTextContent()); } } else { /* Create new Scribe object list */ final List<ScribeObject> cADbjectList = new ArrayList<ScribeObject>(); /* Iterate over node list */ for (int i = 0; i < nodeList.getLength(); i++) { /* Create list of elements */ final List<Element> elementList = new ArrayList<Element>(); /* Get node from node list */ final Node node = nodeList.item(i); /* Create new Scribe object */ final ScribeObject cADbject = new ScribeObject(); /* Check if node has child nodes */ if (node.hasChildNodes()) { final NodeList subNodeList = node.getChildNodes(); /* Create new map for attributes */ final Map<String, String> attributeMap = new HashMap<String, String>(); /* Iterate over sub node list and create elements */ for (int j = 0; j < subNodeList.getLength(); j++) { final Node subNode = subNodeList.item(j); /* This trick is to avoid empty nodes */ if (!subNode.getNodeName().contains("#text")) { /* Create element from response */ final Element element = (Element) subNode; /* Populate label map */ attributeMap.put("label", element.getAttribute("val")); /* Get node name */ final String nodeName = element.getAttribute("val").replace(" ", spaceCharReplacement); /* Validate the node name */ if (XMLChar.isValidName(nodeName)) { /* Add element in list */ elementList.add(ZHCRMMessageFormatUtils.createMessageElement(nodeName, element.getTextContent(), attributeMap)); } else { logger.debug( "----Inside getObjects, found invalid XML node; ignoring field: " + element.getAttribute("val")); } } } } /* Add all CRM fields */ cADbject.setXmlContent(elementList); /* Set type information in object */ cADbject.setObjectType(cADCommandObject.getObjectType()); /* Add Scribe object in list */ cADbjectList.add(cADbject); } /* Check if no record found */ if (cADbjectList.size() == 0) { throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM"); } /* Set the final object in command object */ cADCommandObject.setObject(cADbjectList.toArray(new ScribeObject[cADbjectList.size()])); } } else if (result == HttpStatus.SC_FORBIDDEN) { throw new ScribeException(ScribeResponseCodes._1022 + "Query is forbidden by Zoho CRM"); } else if (result == HttpStatus.SC_BAD_REQUEST) { throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request content"); } else if (result == HttpStatus.SC_UNAUTHORIZED) { throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zoho CRM"); } else if (result == HttpStatus.SC_NOT_FOUND) { throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM"); } else if (result == HttpStatus.SC_INTERNAL_SERVER_ERROR) { /* Create XML document from response */ final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.parse(postMethod.getResponseBodyAsStream()); /* Create new XPath object to query XML document */ final XPath xpath = XPathFactory.newInstance().newXPath(); /* XPath Query for showing error message */ final XPathExpression errorExpression = xpath.compile("/response/error/message"); /* Get erroe message from response document */ final Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE); if (errorMessage != null) { /* Send user error */ throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM : " + errorMessage.getTextContent()); } else { /* Send user error */ throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM"); } } } catch (final ScribeException exception) { throw exception; } catch (final ParserConfigurationException exception) { throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM"); } catch (final SAXException exception) { throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM"); } catch (final IOException exception) { throw new ScribeException( ScribeResponseCodes._1022 + "Communication error while communicating with Zoho CRM"); } finally { /* Release connection socket */ if (postMethod != null) { postMethod.releaseConnection(); } } return cADCommandObject; }
From source file:com.inbravo.scribe.rest.service.crm.ZHRESTCRMService.java
/** * /* w ww .ja v a2s .co 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 w w w . j a va 2s . c o m*/ /* Query CRM object by Phone field */ returnObject = this.getObjectsByPhoneField(cADCommandObject, query, null, null, "Phone"); } catch (final ScribeException firstE) { /* Check if record is not found */ if (firstE.getMessage().contains(ScribeResponseCodes._1004)) { try { /* Query CRM object by Mobile field */ returnObject = this.getObjectsByPhoneField(cADCommandObject, query, null, null, "Mobile"); } catch (final ScribeException secondE) { /* Check if record is again not found */ if (secondE.getMessage().contains(ScribeResponseCodes._1004)) { try { /* Query CRM object by Home Phone field */ returnObject = this.getObjectsByPhoneField(cADCommandObject, query, null, null, "Home Phone"); } catch (final ScribeException thirdE) { /* Check if record is again not found */ if (thirdE.getMessage().contains(ScribeResponseCodes._1004)) { try { /* Query CRM object by Other Phone field */ returnObject = this.getObjectsByPhoneField(cADCommandObject, query, null, null, "Other Phone"); } catch (final ScribeException fourthE) { /* Throw the error to user */ throw fourthE; } } } } } } } return returnObject; } else { /* Get user from session manager */ final ScribeCacheObject user = (ScribeCacheObject) cRMSessionManager .getSessionInfo(cADCommandObject.getCrmUserId()); PostMethod postMethod = null; try { /* Get CRM information from user */ final String serviceURL = user.getScribeMetaObject().getCrmServiceURL(); final String serviceProtocol = user.getScribeMetaObject().getCrmServiceProtocol(); final String sessionId = user.getScribeMetaObject().getCrmSessionId(); /* Create Zoho URL */ final String zohoURL = serviceProtocol + "://" + serviceURL + "/crm/private/xml/" + cADCommandObject.getObjectType() + "s/getSearchRecords"; logger.debug("----Inside getObjects zohoURL: " + zohoURL + " & sessionId: " + sessionId); /* Instantiate post method */ postMethod = new PostMethod(zohoURL); /* Set request parameters */ postMethod.setParameter("authtoken", sessionId.trim()); postMethod.setParameter("scope", "crmapi"); if (!query.equalsIgnoreCase("NONE")) { /* Create ZH query */ final String zhQuery = ZHCRMMessageFormatUtils.createZHQuery(query); if (zhQuery != null && !"".equals(zhQuery)) { /* Set search parameter in request */ postMethod.setParameter("searchCondition", "(" + zhQuery + ")"); } } else { /* Without query param this method is not applicable */ return this.getObjects(cADCommandObject); } /* Set request param to select all fields */ postMethod.setParameter("selectColumns", "All"); final HttpClient httpclient = new HttpClient(); /* Execute method */ int result = httpclient.executeMethod(postMethod); logger.debug("----Inside getObjects response code: " + result + " & body: " + postMethod.getResponseBodyAsString()); /* Check if response if SUCCESS */ if (result == HttpStatus.SC_OK) { /* Create XML document from response */ final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.parse(postMethod.getResponseBodyAsStream()); /* Create new XPath object to query XML document */ final XPath xpath = XPathFactory.newInstance().newXPath(); /* XPath Query for showing all nodes value */ final XPathExpression expr = xpath .compile("/response/result/" + cADCommandObject.getObjectType() + "s/row"); /* Get node list from response document */ final NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET); /* Check if records founds */ if (nodeList != null && nodeList.getLength() == 0) { /* XPath Query for showing error message */ XPathExpression errorExpression = xpath.compile("/response/error/message"); /* Get erroe message from response document */ Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE); /* Check if error message is found */ if (errorMessage != null) { /* Send user error */ throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM : " + errorMessage.getTextContent()); } else { /* XPath Query for showing error message */ errorExpression = xpath.compile("/response/nodata/message"); /* Get erroe message from response document */ errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE); /* Send user error */ throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM : " + errorMessage.getTextContent()); } } else { /* Create new Scribe object list */ final List<ScribeObject> cADbjectList = new ArrayList<ScribeObject>(); /* Iterate over node list */ for (int i = 0; i < nodeList.getLength(); i++) { /* Create list of elements */ final List<Element> elementList = new ArrayList<Element>(); /* Get node from node list */ final Node node = nodeList.item(i); /* Create new Scribe object */ final ScribeObject cADbject = new ScribeObject(); /* Check if node has child nodes */ if (node.hasChildNodes()) { final NodeList subNodeList = node.getChildNodes(); /* Create new map for attributes */ final Map<String, String> attributeMap = new HashMap<String, String>(); /* * Iterate over sub node list and create elements */ for (int j = 0; j < subNodeList.getLength(); j++) { final Node subNode = subNodeList.item(j); /* This trick is to avoid empty nodes */ if (!subNode.getNodeName().contains("#text")) { /* Create element from response */ final Element element = (Element) subNode; /* Populate label map */ attributeMap.put("label", element.getAttribute("val")); /* Get node name */ final String nodeName = element.getAttribute("val").replace(" ", spaceCharReplacement); /* Validate the node name */ if (XMLChar.isValidName(nodeName)) { /* Add element in list */ elementList.add(ZHCRMMessageFormatUtils.createMessageElement(nodeName, element.getTextContent(), attributeMap)); } else { logger.debug( "----Inside getObjects, found invalid XML node; ignoring field: " + element.getAttribute("val")); } } } } /* Add all CRM fields */ cADbject.setXmlContent(elementList); /* Set type information in object */ cADbject.setObjectType(cADCommandObject.getObjectType()); /* Add Scribe object in list */ cADbjectList.add(cADbject); } /* Check if no record found */ if (cADbjectList.size() == 0) { throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM"); } /* Set the final object in command object */ cADCommandObject.setObject(cADbjectList.toArray(new ScribeObject[cADbjectList.size()])); } } else if (result == HttpStatus.SC_FORBIDDEN) { throw new ScribeException(ScribeResponseCodes._1022 + "Query is forbidden by Zoho CRM"); } else if (result == HttpStatus.SC_BAD_REQUEST) { throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request content"); } else if (result == HttpStatus.SC_UNAUTHORIZED) { throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zoho CRM"); } else if (result == HttpStatus.SC_NOT_FOUND) { throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM"); } else if (result == HttpStatus.SC_INTERNAL_SERVER_ERROR) { /* Create XML document from response */ final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.parse(postMethod.getResponseBodyAsStream()); /* Create new XPath object to query XML document */ final XPath xpath = XPathFactory.newInstance().newXPath(); /* XPath Query for showing error message */ final XPathExpression errorExpression = xpath.compile("/response/error/message"); /* Get erroe message from response document */ final Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE); if (errorMessage != null) { /* Send user error */ throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM : " + errorMessage.getTextContent()); } else { /* Send user error */ throw new ScribeException( ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM"); } } } catch (final ScribeException exception) { throw exception; } catch (final ParserConfigurationException exception) { throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM"); } catch (final SAXException exception) { throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM"); } catch (final IOException exception) { throw new ScribeException( ScribeResponseCodes._1022 + "Communication error while communicating with Zoho CRM"); } finally { /* Release connection socket */ if (postMethod != null) { postMethod.releaseConnection(); } } return cADCommandObject; } }