List of usage examples for org.w3c.dom Element getNodeName
public String getNodeName();
From source file:com.cloud.agent.api.storage.OVFHelper.java
private Element getParentNode(final NodeList itemList, final Element childItem) { NodeList cn = childItem.getChildNodes(); String parent_id = null;//w w w . j a va2 s . c o m for (int l = 0; l < cn.getLength(); l++) { if (cn.item(l) instanceof Element) { Element el = (Element) cn.item(l); if ("rasd:Parent".equals(el.getNodeName())) { parent_id = el.getTextContent(); } } } if (parent_id != null) { for (int k = 0; k < itemList.getLength(); k++) { Element item = (Element) itemList.item(k); NodeList child = item.getChildNodes(); for (int l = 0; l < child.getLength(); l++) { if (child.item(l) instanceof Element) { Element el = (Element) child.item(l); if ("rasd:InstanceID".equals(el.getNodeName()) && el.getTextContent().trim().equals(parent_id)) { return item; } } } } } return null; }
From source file:com.cloud.agent.api.storage.OVFHelper.java
private OVFDiskController getControllerType(final NodeList itemList, final String diskId) { for (int k = 0; k < itemList.getLength(); k++) { Element item = (Element) itemList.item(k); NodeList cn = item.getChildNodes(); for (int l = 0; l < cn.getLength(); l++) { if (cn.item(l) instanceof Element) { Element el = (Element) cn.item(l); if ("rasd:HostResource".equals(el.getNodeName()) && (el.getTextContent().contains("ovf:/file/" + diskId) || el.getTextContent().contains("ovf:/disk/" + diskId))) { Element oe = getParentNode(itemList, item); Element voe = oe; while (oe != null) { voe = oe;// w w w . j a va 2 s.c om oe = getParentNode(itemList, voe); } return getController(voe); } } } } return null; }
From source file:org.weloveastrid.hive.api.Invoker.java
public Element invoke(boolean repeat, Param... params) throws ServiceException { long timeSinceLastInvocation = System.currentTimeMillis() - lastInvocation; if (timeSinceLastInvocation < INVOCATION_INTERVAL) { // In order not to invoke the Hiveminder service too often try {/*from w ww . j av a 2 s .c om*/ Thread.sleep(INVOCATION_INTERVAL - timeSinceLastInvocation); } catch (InterruptedException e) { return null; } } // We compute the URI final StringBuffer requestUri = computeRequestUri(params); HttpResponse response = null; final HttpGet request = new HttpGet("http://" //$NON-NLS-1$ + ServiceImpl.SERVER_HOST_NAME + requestUri.toString()); final String methodUri = request.getRequestLine().getUri(); Element result; try { Log.i(TAG, "Executing the method:" + methodUri); //$NON-NLS-1$ response = httpClient.execute(request); lastInvocation = System.currentTimeMillis(); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.e(TAG, "Method failed: " + response.getStatusLine()); //$NON-NLS-1$ // Tim: HTTP error. Let's wait a little bit if (!repeat) { try { Thread.sleep(1500); } catch (InterruptedException e) { // ignore } response.getEntity().consumeContent(); return invoke(true, params); } throw new ServiceInternalException("method failed: " + response.getStatusLine()); } final Document responseDoc = builder.parse(response.getEntity().getContent()); final Element wrapperElt = responseDoc.getDocumentElement(); if (!wrapperElt.getNodeName().equals("rsp")) { throw new ServiceInternalException( "unexpected response returned by Hiveminder service: " + wrapperElt.getNodeName()); } else { String stat = wrapperElt.getAttribute("stat"); if (stat.equals("fail")) { Node errElt = wrapperElt.getFirstChild(); while (errElt != null && (errElt.getNodeType() != Node.ELEMENT_NODE || !errElt.getNodeName().equals("err"))) { errElt = errElt.getNextSibling(); } if (errElt == null) { throw new ServiceInternalException( "unexpected response returned by Hiveminder service: " + wrapperElt.getNodeValue()); } else { if (SERVICE_UNAVAILABLE_CODE.equals(((Element) errElt).getAttribute("code")) && !repeat) { try { Thread.sleep(1500); } catch (InterruptedException e) { // ignore } return invoke(true, params); } throw new ServiceException(Integer.parseInt(((Element) errElt).getAttribute("code")), ((Element) errElt).getAttribute("msg")); } } else { Node dataElt = wrapperElt.getFirstChild(); while (dataElt != null && (dataElt.getNodeType() != Node.ELEMENT_NODE || dataElt.getNodeName().equals("transaction") == true)) { try { Node nextSibling = dataElt.getNextSibling(); if (nextSibling == null) { break; } else { dataElt = nextSibling; } } catch (IndexOutOfBoundsException exception) { // Some implementation may throw this exception, // instead of returning a null sibling break; } } if (dataElt == null) { throw new ServiceInternalException( "unexpected response returned by Hiveminder service: " + wrapperElt.getNodeValue()); } else { result = (Element) dataElt; } } } } catch (IOException e) { throw new ServiceInternalException("Error making connection: " + e.getMessage(), e); } catch (SAXException e) { // repeat call if possible. if (!repeat) return invoke(true, params); else throw new ServiceInternalException("Error parsing response. " + "Please try sync again!", e); } finally { httpClient.getConnectionManager().closeExpiredConnections(); } return result; }
From source file:org.weloveastrid.rmilk.api.Invoker.java
public Element invoke(boolean repeat, Param... params) throws ServiceException { long timeSinceLastInvocation = System.currentTimeMillis() - lastInvocation; if (timeSinceLastInvocation < INVOCATION_INTERVAL) { // In order not to invoke the RTM service too often try {//from ww w .j av a2 s.com Thread.sleep(INVOCATION_INTERVAL - timeSinceLastInvocation); } catch (InterruptedException e) { return null; } } // We compute the URI final StringBuffer requestUri = computeRequestUri(params); HttpResponse response = null; final HttpGet request = new HttpGet("http://" //$NON-NLS-1$ + ServiceImpl.SERVER_HOST_NAME + requestUri.toString()); final String methodUri = request.getRequestLine().getUri(); Element result; try { Log.i(TAG, "Executing the method:" + methodUri); //$NON-NLS-1$ response = httpClient.execute(request); lastInvocation = System.currentTimeMillis(); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.e(TAG, "Method failed: " + response.getStatusLine()); //$NON-NLS-1$ // Tim: HTTP error. Let's wait a little bit if (!repeat) { try { Thread.sleep(1500); } catch (InterruptedException e) { // ignore } response.getEntity().consumeContent(); return invoke(true, params); } throw new ServiceInternalException("method failed: " + response.getStatusLine()); } final Document responseDoc = builder.parse(response.getEntity().getContent()); final Element wrapperElt = responseDoc.getDocumentElement(); if (!wrapperElt.getNodeName().equals("rsp")) { throw new ServiceInternalException( "unexpected response returned by RTM service: " + wrapperElt.getNodeName()); } else { String stat = wrapperElt.getAttribute("stat"); if (stat.equals("fail")) { Node errElt = wrapperElt.getFirstChild(); while (errElt != null && (errElt.getNodeType() != Node.ELEMENT_NODE || !errElt.getNodeName().equals("err"))) { errElt = errElt.getNextSibling(); } if (errElt == null) { throw new ServiceInternalException( "unexpected response returned by RTM service: " + wrapperElt.getNodeValue()); } else { if (SERVICE_UNAVAILABLE_CODE.equals(((Element) errElt).getAttribute("code")) && !repeat) { try { Thread.sleep(1500); } catch (InterruptedException e) { // ignore } return invoke(true, params); } throw new ServiceException(Integer.parseInt(((Element) errElt).getAttribute("code")), ((Element) errElt).getAttribute("msg")); } } else { Node dataElt = wrapperElt.getFirstChild(); while (dataElt != null && (dataElt.getNodeType() != Node.ELEMENT_NODE || dataElt.getNodeName().equals("transaction") == true)) { try { Node nextSibling = dataElt.getNextSibling(); if (nextSibling == null) { break; } else { dataElt = nextSibling; } } catch (IndexOutOfBoundsException exception) { // Some implementation may throw this exception, // instead of returning a null sibling break; } } if (dataElt == null) { throw new ServiceInternalException( "unexpected response returned by RTM service: " + wrapperElt.getNodeValue()); } else { result = (Element) dataElt; } } } } catch (IOException e) { throw new ServiceInternalException("Error making connection: " + e.getMessage(), e); } catch (SAXException e) { // repeat call if possible. if (!repeat) return invoke(true, params); else throw new ServiceInternalException("Error parsing response. " + "Please try sync again!", e); } finally { httpClient.getConnectionManager().closeExpiredConnections(); } return result; }
From source file:com.nexmo.insight.sdk.NexmoInsightClient.java
public InsightResult request(final String number, final String callbackUrl, final String[] features, final long callbackTimeout, final String callbackMethod, final String clientRef, final String ipAddress) throws IOException, SAXException { if (number == null || callbackUrl == null) throw new IllegalArgumentException("number and callbackUrl parameters are mandatory."); if (callbackTimeout >= 0 && (callbackTimeout < 1000 || callbackTimeout > 30000)) throw new IllegalArgumentException("callback timeout must be between 1000 and 30000."); log.debug("HTTP-Number-Insight Client .. to [ " + number + " ] "); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("api_key", this.apiKey)); params.add(new BasicNameValuePair("api_secret", this.apiSecret)); params.add(new BasicNameValuePair("number", number)); params.add(new BasicNameValuePair("callback", callbackUrl)); if (features != null) params.add(new BasicNameValuePair("features", strJoin(features, ","))); if (callbackTimeout >= 0) params.add(new BasicNameValuePair("callback_timeout", String.valueOf(callbackTimeout))); if (callbackMethod != null) params.add(new BasicNameValuePair("callback_method", callbackMethod)); if (ipAddress != null) params.add(new BasicNameValuePair("ip", ipAddress)); if (clientRef != null) params.add(new BasicNameValuePair("client_ref", clientRef)); String inshightBaseUrl = this.baseUrl + PATH_INSIGHT; // Now that we have generated a query string, we can instanciate a HttpClient, // construct a POST or GET method and execute to submit the request String response = null;//from w ww . ja v a2 s .c o m for (int pass = 1; pass <= 2; pass++) { HttpPost httpPost = new HttpPost(inshightBaseUrl); httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpUriRequest method = httpPost; String url = inshightBaseUrl + "?" + URLEncodedUtils.format(params, "utf-8"); try { if (this.httpClient == null) this.httpClient = HttpClientUtils.getInstance(this.connectionTimeout, this.soTimeout) .getNewHttpClient(); HttpResponse httpResponse = this.httpClient.execute(method); int status = httpResponse.getStatusLine().getStatusCode(); if (status != 200) throw new Exception( "got a non-200 response [ " + status + " ] from Nexmo-HTTP for url [ " + url + " ] "); response = new BasicResponseHandler().handleResponse(httpResponse); log.info(".. SUBMITTED NEXMO-HTTP URL [ " + url + " ] -- response [ " + response + " ] "); break; } catch (Exception e) { method.abort(); log.info("communication failure: " + e); String exceptionMsg = e.getMessage(); if (exceptionMsg.indexOf("Read timed out") >= 0) { log.info( "we're still connected, but the target did not respond in a timely manner .. drop ..."); } else { if (pass == 1) { log.info("... re-establish http client ..."); this.httpClient = null; continue; } } // return a COMMS failure ... return new InsightResult(InsightResult.STATUS_COMMS_FAILURE, null, null, 0, 0, "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e, true); } } Document doc; synchronized (this.documentBuilder) { doc = this.documentBuilder.parse(new InputSource(new StringReader(response))); } Element root = doc.getDocumentElement(); if (!"lookup".equals(root.getNodeName())) throw new IOException("No valid response found [ " + response + "] "); return parseInsightResult(root); }
From source file:Main.java
public static boolean validate(Element ele, String[] requiredAttributes, String[] optionalAttributes, String[] requiredElements, String[] optionalElements) { boolean[] foundAttributes = new boolean[requiredAttributes.length]; for (int i = 0; i < foundAttributes.length; i++) { foundAttributes[i] = false;/*from w w w . ja va2s . c o m*/ } for (int i = 0; i < ele.getAttributes().getLength(); i++) { Node n = ele.getAttributes().item(i); boolean found = false; for (int j = 0; j < requiredAttributes.length; j++) { if (requiredAttributes[j].equalsIgnoreCase(n.getNodeName())) { foundAttributes[j] = true; found = true; break; } } if (!found) { for (String c : optionalAttributes) { if (n.getNodeName().equalsIgnoreCase(c)) { found = true; break; } } } // If we've got this far and nothings been found then there must have been an unexpected attribute if (!found) { throw new IllegalArgumentException("Error validating XML Element: " + ele.getNodeName() + "; Found unexpected attribute: " + n.getNodeName()); } } // Check all required attributes were found for (int i = 0; i < foundAttributes.length; i++) { if (foundAttributes[i] == false) { throw new IllegalArgumentException("Error validating XML Element: " + ele.getNodeName() + "; Failed to find expected attribute or child element named: " + requiredAttributes[i]); } } boolean[] foundElements = new boolean[requiredElements.length]; for (int i = 0; i < foundElements.length; i++) { foundElements[i] = false; } for (int i = 0; i < ele.getChildNodes().getLength(); i++) { Node n = ele.getChildNodes().item(i); boolean found = false; for (int j = 0; j < requiredElements.length; j++) { if (requiredElements[j].equalsIgnoreCase(n.getNodeName())) { foundElements[j] = true; found = true; break; } } if (!found) { for (String c : optionalElements) { if (n.getNodeName().equalsIgnoreCase(c)) { found = true; break; } } } // If we've got this far and nothings been found then there must have been an unexpected element if (!found) { if (n.getNodeName().startsWith("#") || n.getNodeName().startsWith("<!--")) { // Then we just ignore these elements } else { throw new IllegalArgumentException("Error validating XML Element: " + ele.getNodeName() + "; Found unexpected child node: " + n.getNodeName()); } } } // Check all required child elements were found for (int i = 0; i < foundElements.length; i++) { if (foundElements[i] == false) { throw new IllegalArgumentException("Error validating XML Element: " + ele.getNodeName() + "; Failed to find expected attribute or child element named: " + requiredElements[i]); } } return true; }
From source file:com.hp.autonomy.searchcomponents.idol.search.fields.FieldsParserImpl.java
@Override public void parseDocumentFields(final Hit hit, final IdolSearchResult.Builder searchResultBuilder) { final FieldsInfo fieldsInfo = configService.getConfig().getFieldsInfo(); final Map<String, FieldInfo<?>> fieldConfig = fieldsInfo.getFieldConfigByName(); final DocContent content = hit.getContent(); Map<String, FieldInfo<?>> fieldMap = Collections.emptyMap(); String qmsId = null;/* w w w . j av a2 s .c om*/ PromotionCategory promotionCategory = PromotionCategory.NONE; if (content != null) { final Element docContent = (Element) content.getContent().get(0); if (docContent.hasChildNodes()) { final NodeList childNodes = docContent.getChildNodes(); fieldMap = new HashMap<>(childNodes.getLength()); parseAllFields(fieldConfig, childNodes, fieldMap, docContent.getNodeName()); qmsId = parseField(docContent, IdolDocumentFieldsService.QMS_ID_FIELD_INFO, String.class); promotionCategory = determinePromotionCategory(docContent, hit.getPromotionname(), hit.getDatabase()); } } searchResultBuilder.setFieldMap(fieldMap).setQmsId(qmsId).setPromotionCategory(promotionCategory); }
From source file:importer.handler.post.stages.Discriminator.java
/** * Does this element only contain deleted text? * @param elem the element in question// ww w.j ava2 s . c o m * @return true if it is, else false */ boolean isDeleted(Element elem) { boolean result = true; String eName = elem.getNodeName(); if (eName.equals(del)) result = true; else { String text = elem.getTextContent(); int textLen = (text != null) ? text.length() : 0; int childLen = 0; Element child = firstChild(elem); while (child != null && !result) { String childText = elem.getTextContent(); if (isDeleted(child)) childLen += (childText != null) ? childText.length() : 0; child = nextSibling(child, true); } result = childLen == textLen; } return result; }
From source file:com.espertech.esper.client.ConfigurationParser.java
private static void handleEngineSettings(Configuration configuration, Element element) { DOMElementIterator nodeIterator = new DOMElementIterator(element.getChildNodes()); while (nodeIterator.hasNext()) { Element subElement = nodeIterator.next(); if (subElement.getNodeName().equals("defaults")) { handleEngineSettingsDefaults(configuration, subElement); }//from w w w .j a va 2 s . c om } }
From source file:com.espertech.esper.client.ConfigurationParser.java
private static void handleDefaultsVariables(Configuration configuration, Element parentElement) { DOMElementIterator nodeIterator = new DOMElementIterator(parentElement.getChildNodes()); while (nodeIterator.hasNext()) { Element subElement = nodeIterator.next(); if (subElement.getNodeName().equals("msec-version-release")) { String valueText = getRequiredAttribute(subElement, "value"); Long value = Long.parseLong(valueText); configuration.getEngineDefaults().getVariables().setMsecVersionRelease(value); }/*from ww w. j av a 2s. c o m*/ } }