List of usage examples for org.w3c.dom Node getFirstChild
public Node getFirstChild();
From source file:org.powertac.visualizer.services.VisualizerServiceTournament.java
private void tournamentLogin() { //log.info("Tournament URL='" + tournamentUrl + "'"); if (tournamentUrl.isEmpty()) { // No TM, just connect to server putEvent(Event.noTm);/*from ww w .j ava2 s . co m*/ return; } OperatingSystemMXBean mxBean = ManagementFactory.getOperatingSystemMXBean(); double load = mxBean.getSystemLoadAverage(); String urlString = tournamentUrl + visualizerLoginContext + "?machineName=" + machineName + "&machineLoad=" + load; log.info("tourney url=" + urlString); URL url; try { url = new URL(urlString); URLConnection conn = url.openConnection(); InputStream input = conn.getInputStream(); log.info("Parsing message.."); DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(input); doc.getDocumentElement().normalize(); // Two different message types Node retryNode = doc.getElementsByTagName("retry").item(0); Node loginNode = doc.getElementsByTagName("login").item(0); if (retryNode != null) { String checkRetry = retryNode.getFirstChild().getNodeValue(); log.info("Retry in " + checkRetry + " seconds"); // Received retry message; spin and try again try { Thread.sleep(Integer.parseInt(checkRetry) * 1000); } catch (InterruptedException e) { //e.printStackTrace(); } } else if (loginNode != null) { log.info("Login response received! "); queueName = doc.getElementsByTagName("queueName").item(0).getFirstChild().getNodeValue(); serverQueue = doc.getElementsByTagName("serverQueue").item(0).getFirstChild().getNodeValue(); log.info(String.format("Login message received: queueName=%s, serverQueue=%s", queueName, serverQueue)); putEvent(Event.accept); } else { // this is not working log.info("Invalid response from TS"); } } catch (Exception e) { // should we have an event here? e.printStackTrace(); } }
From source file:org.dasein.cloud.ibm.sce.compute.disk.SCEDisk.java
private SCEOffering findOffering(int sizeInGb) throws InternalException, CloudException { SCEOffering offering = null;//from w w w . j a v a 2 s.c o m ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new SCEConfigException("No context was configured for this request"); } SCEMethod method = new SCEMethod(provider); Document xml = method.getAsXML("offerings/storage"); if (xml == null) { throw new CloudException("No storage offerings exist"); } NodeList nodes = xml.getElementsByTagName("Offerings"); for (int i = 0; i < nodes.getLength(); i++) { Node item = nodes.item(i); if (item.hasChildNodes()) { NodeList attrs = item.getChildNodes(); String id = null, format = null; int[] sizes = new int[0]; for (int j = 0; j < attrs.getLength(); j++) { Node attr = attrs.item(j); String n = attr.getNodeName(); if (n.equalsIgnoreCase("ID")) { id = attr.getFirstChild().getNodeValue().trim(); } else if (n.equalsIgnoreCase("SupportedSizes")) { String s = attr.getFirstChild().getNodeValue().trim(); String[] parts; if (s.contains(",")) { parts = s.split(","); } else { parts = new String[] { s }; } sizes = new int[parts.length]; for (int k = 0; k < parts.length; k++) { sizes[k] = Integer.parseInt(parts[k].trim()); } } else if (n.equalsIgnoreCase("SupportedFormats") && attr.hasChildNodes()) { NodeList formats = attr.getChildNodes(); for (int k = 0; k < formats.getLength(); k++) { Node fmt = formats.item(k); if (fmt.getNodeName().equalsIgnoreCase("Format") && fmt.hasChildNodes()) { NodeList fa = fmt.getChildNodes(); for (int l = 0; l < fa.getLength(); l++) { Node fan = fa.item(l); if (fan.getNodeName().equalsIgnoreCase("ID") && fan.hasChildNodes()) { format = fan.getFirstChild().getNodeValue().trim(); if (!format.equalsIgnoreCase("RAW")) { format = null; } } } } } } } if (sizes.length > 0 && format != null) { if (offering == null) { offering = new SCEOffering(); offering.format = format; offering.offeringId = id; if (sizes[0] > sizeInGb) { offering.size = sizes[0]; } else { int sz = 0; for (int s : sizes) { if (s < sizeInGb && s >= sz) { sz = s; } else { break; } } offering.size = sz; } } } } } if (offering == null) { throw new CloudException("No storage offerings exist"); } return offering; }
From source file:XMLConfig.java
/** Returns the value as specified by the DOM path. * @param path DOM path/*from w ww. j a va 2 s.c om*/ * @param root node where the search should start * @return list of values. */ public List<String> getMultiple(String path, Node root) { List<Node> accum = getNodes(path, root); List<String> strings = new LinkedList<String>(); for (Node n : accum) { if (n instanceof Attr) { strings.add(n.getNodeValue()); } else { Node child; String acc = ""; child = n.getFirstChild(); while (child != null) { if (child.getNodeName().equals("#text")) { acc += " " + child.getNodeValue(); } else if (child.getNodeName().equals("#comment")) { // ignore } else { throw new XMLConfigException("Node " + n.getNodeName() + " contained node " + child.getNodeName() + ", but should only contain #text and #comment."); } child = child.getNextSibling(); } strings.add(acc.trim()); } } return strings; }
From source file:net.sf.jasperreports.engine.fonts.SimpleFontExtensionHelper.java
/** * *///from w w w . j ava 2 s. com private SimpleFontFace parseFontFace(JasperReportsContext jasperReportsContext, Node fontFaceNode, boolean loadFonts) throws SAXException { SimpleFontFace fontFace = new SimpleFontFace(jasperReportsContext); NodeList nodeList = fontFaceNode.getChildNodes(); if (nodeList.getLength() == 1 && (fontFaceNode.getFirstChild().getNodeType() == Node.TEXT_NODE || fontFaceNode.getFirstChild().getNodeType() == Node.CDATA_SECTION_NODE)) { fontFace.setTtf(fontFaceNode.getFirstChild().getTextContent(), loadFonts); } else { for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { if (NODE_ttf.equals(node.getNodeName())) { fontFace.setTtf(node.getTextContent(), loadFonts); } else if (NODE_pdf.equals(node.getNodeName())) { fontFace.setPdf(node.getTextContent()); } else if (NODE_eot.equals(node.getNodeName())) { fontFace.setEot(node.getTextContent()); } else if (NODE_svg.equals(node.getNodeName())) { fontFace.setSvg(node.getTextContent()); } else if (NODE_woff.equals(node.getNodeName())) { fontFace.setWoff(node.getTextContent()); } } } } return fontFace; }
From source file:com.collabnet.tracker.core.PTrackerWebServicesClient.java
/** * This is a check to ensure that invalid next page calls are not sent to the server. * @param pageInfo/*from ww w . ja v a 2 s . c o m*/ * @throws Exception */ public void validateNextPage(Node pageInfo, String altQueryRef) throws Exception { Node child = pageInfo.getFirstChild(); String msg = "Next page does not have a valid query reference"; String name, value; while (child != null) { name = child.getNodeName(); value = child.getTextContent(); if (name.contains("queryReference")) { if (value == null || value.length() < 1) { if (altQueryRef == null) throw new Exception(msg); child.setTextContent(altQueryRef); } return; } child = child.getNextSibling(); } throw new Exception(msg); }
From source file:org.dasein.cloud.aws.platform.SimpleDB.java
@Override public KeyValueDatabase getDatabase(String domainId) throws CloudException, InternalException { APITrace.begin(provider, "KVDB.getDatabase"); try {/*from ww w . j a va 2s.c o m*/ Map<String, String> parameters = provider.getStandardSimpleDBParameters(provider.getContext(), DOMAIN_META_DATA); EC2Method method; Document doc; parameters.put("DomainName", domainId); method = new EC2Method(SERVICE_ID, provider, parameters); try { doc = method.invoke(); } catch (EC2Exception e) { String code = e.getCode(); if (code != null && code.equals("NoSuchDomain")) { return null; } throw new CloudException(e); } KeyValueDatabase database = new KeyValueDatabase(); database.setProviderOwnerId(provider.getContext().getAccountNumber()); database.setProviderRegionId(provider.getContext().getRegionId()); database.setProviderDatabaseId(domainId); database.setName(domainId); database.setDescription(domainId); NodeList blocks = doc.getElementsByTagName("DomainMetadataResult"); if (blocks.getLength() > 0) { for (int i = 0; i < blocks.getLength(); i++) { NodeList items = blocks.item(i).getChildNodes(); for (int j = 0; j < items.getLength(); j++) { Node item = items.item(j); String name = item.getNodeName(); if (name.equals("ItemCount")) { if (item.hasChildNodes()) { database.setItemCount(Integer.parseInt(item.getFirstChild().getNodeValue())); } } else if (name.equals("AttributeValueCount")) { if (item.hasChildNodes()) { database.setKeyValueCount(Integer.parseInt(item.getFirstChild().getNodeValue())); } } else if (name.equals("AttributeNameCount")) { if (item.hasChildNodes()) { database.setKeyCount(Integer.parseInt(item.getFirstChild().getNodeValue())); } } else if (name.equals("ItemNamesSizeBytes")) { if (item.hasChildNodes()) { database.setItemSize(Integer.parseInt(item.getFirstChild().getNodeValue())); } } else if (name.equals("AttributeValuesSizeBytes")) { if (item.hasChildNodes()) { database.setKeyValueSize(Integer.parseInt(item.getFirstChild().getNodeValue())); } } else if (name.equals("AttributeNamesSizeBytes")) { if (item.hasChildNodes()) { database.setKeySize(Integer.parseInt(item.getFirstChild().getNodeValue())); } } } } } return database; } finally { APITrace.end(); } }
From source file:com.android.flickrbot.FlickrClient.java
boolean getAuthToken() throws Exception { // TODO: Check the state before running this. /** Retrieve the frob from the database **/ String frob = m_database.getConfigValue(FROB_NAME); /**//from w w w . j a va 2 s . c om * Get auth token using frob. Once again, a signature is required * for authenticated calls to the Flickr API. */ parameterList params = this.new parameterList(); params.addParameter("api_key", KEY); params.addParameter("frob", frob); params.addParameter("method", "flickr.auth.getToken"); HttpClient client = new DefaultHttpClient(); HttpGet getrequest = new HttpGet(REST_URL + params.getSignedList()); // Send GET request HttpResponse response = client.execute(getrequest); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { throw new Exception("Method failed: " + response.getStatusLine()); } InputStream rstream = null; // Get the response body rstream = response.getEntity().getContent(); /** * Retrieve the XML response to the token request and get the token value */ Document parsedResponse = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(rstream); String token = null; // Check if token is in the response NodeList tokenResponse = parsedResponse.getElementsByTagName("token"); Node tokenNode = tokenResponse.item(0); if (tokenNode == null) { NodeList error = parsedResponse.getElementsByTagName("err"); // Get Flickr error code and msg // TODO: Define this better String code = error.item(0).getAttributes().item(0).getNodeValue(); String msg = error.item(0).getAttributes().item(1).getNodeValue(); System.out.println("Flickr request failed with error code " + code + ", " + msg); return false; } token = tokenNode.getFirstChild().getNodeValue(); System.out.println("Successfully retrieved token: " + token); // TODO: Save other stuff such as the user name, etc? m_database.deleteConfigValue(FROB_NAME); m_database.setConfigValue(AUTH_TOKEN_NAME, token); // TODO: Check that the perms field is "write" // Assume that all of this will work. If they don't, we throw. tokenResponse = parsedResponse.getElementsByTagName("user"); String nsid = tokenResponse.item(0).getAttributes().getNamedItem("nsid").getNodeValue(); String username = tokenResponse.item(0).getAttributes().getNamedItem("username").getNodeValue(); m_database.setConfigValue(NSID_NAME, nsid); m_database.setConfigValue(USERNAME_NAME, username); return true; }
From source file:edu.wpi.margrave.MCommunicator.java
private static Document handleAddVocabFact(Node margraveCommandNode, Node childNode) { String vname = getVocabName(margraveCommandNode); Node secondChildNode = childNode.getNextSibling(); // WORRY Shouldn't be hardcoded in!! String addType = secondChildNode.getNodeName(); writeToLog("addType: " + addType + "\n"); if (addType.equalsIgnoreCase("SUBSORT")) { String parent = getSubSortParent(margraveCommandNode); String child = getSubSortChild(margraveCommandNode); return MEnvironment.addSubsort(vname, parent, child); } else if (addType.equalsIgnoreCase("SORT")) { String sortName = getSortName(margraveCommandNode); return MEnvironment.addSort(vname, sortName); } else if (addType.equalsIgnoreCase("SORT-WITH-CHILDREN")) { String sortName = getAttributeOfChildNodeOrNode(margraveCommandNode, "SORT-WITH-CHILDREN", "name"); List<String> childnames = getListElements(margraveCommandNode, "SORT-WITH-CHILDREN", "name"); return MEnvironment.addSortWithSubs(vname, sortName, childnames); } else if (addType.equalsIgnoreCase("PREDICATE")) { String sName = getPredicateName(margraveCommandNode); List<String> constr = getRelationsList(margraveCommandNode); writeToLog("Adding Predicate\n"); return MEnvironment.addPredicate(vname, sName, constr); }/*from w w w.ja va 2 s. co m*/ else if (addType.equalsIgnoreCase("CONSTANT")) { String sName = getAttributeOfChildNodeOrNode(secondChildNode, "CONSTANT", "name"); String sSort = getAttributeOfChildNodeOrNode(secondChildNode, "CONSTANT", "type"); writeToLog("Adding constant " + sName + " : " + sSort + "\n"); return MEnvironment.addConstant(vname, sName, sSort); } else if (addType.equalsIgnoreCase("FUNCTION")) { String sName = getAttributeOfChildNodeOrNode(secondChildNode, "FUNCTION", "name"); List<String> constr = getListElements(secondChildNode, "RELATIONS", "name"); writeToLog("Adding function " + sName + " : " + constr + "\n"); //System.err.println("Adding function "+sName+" : "+constr+"\n"); return MEnvironment.addFunction(vname, sName, constr); } else if (addType.equalsIgnoreCase("CONSTRAINT")) { Node constraintNode = secondChildNode; //Just for clarity String constraintType = getConstraintType(constraintNode); // FORMULA is special. if (constraintType.equalsIgnoreCase("FORMULA")) { return MEnvironment.addConstraintFormula(vname, exploreHelper(constraintNode.getFirstChild(), new ArrayList<String>()).fmla); } List<String> relations = getRelationsList(constraintNode); assert (relations != null); String firstRelation = relations.get(0); if (constraintType.equalsIgnoreCase("SINGLETON")) { return MEnvironment.addConstraintSingleton(vname, firstRelation); } else if (constraintType.equalsIgnoreCase("SINGLETON-ALL")) { return MEnvironment.addConstraintSingletonAll(vname, firstRelation); } else if (constraintType.equalsIgnoreCase("ATMOSTONE")) { return MEnvironment.addConstraintAtMostOne(vname, firstRelation); } else if (constraintType.equalsIgnoreCase("DISJOINT")) { assert (relations.size() == 2); String secondRelation = relations.get(1); return MEnvironment.addConstraintDisjoint(vname, firstRelation, secondRelation); } else if (constraintType.equalsIgnoreCase("SUBSET")) { assert (relations.size() == 2); String secondRelation = relations.get(1); return MEnvironment.addConstraintSubset(vname, firstRelation, secondRelation); } else if (constraintType.equalsIgnoreCase("CONSTANTS-NEQ")) { assert (relations.size() == 2); String secondRelation = relations.get(1); return MEnvironment.addConstraintConstantsNeq(vname, firstRelation, secondRelation); } else if (constraintType.equalsIgnoreCase("CONSTANTS-COVER")) { return MEnvironment.addConstraintConstantsCover(vname, firstRelation); } else if (constraintType.equalsIgnoreCase("CONSTANTS-NEQ-ALL")) { MCommunicator.writeToLog("\nAdding constraint constants-neq-all: " + firstRelation); return MEnvironment.addConstraintConstantsNeqAll(vname, firstRelation); } else if (constraintType.equalsIgnoreCase("ATMOSTONE-ALL")) { return MEnvironment.addConstraintAtMostOneAll(vname, firstRelation); } else if (constraintType.equalsIgnoreCase("NONEMPTY")) { return MEnvironment.addConstraintNonempty(vname, firstRelation); } else if (constraintType.equalsIgnoreCase("NONEMPTY-ALL")) { return MEnvironment.addConstraintNonemptyAll(vname, firstRelation); } else if (constraintType.equalsIgnoreCase("ABSTRACT")) { return MEnvironment.addConstraintAbstract(vname, firstRelation); } else if (constraintType.equalsIgnoreCase("ABSTRACT-ALL")) { return MEnvironment.addConstraintAbstractAll(vname, firstRelation); } else if (constraintType.equalsIgnoreCase("TOTAL-FUNCTION")) { return MEnvironment.addConstraintTotalFunction(vname, firstRelation); } else if (constraintType.equalsIgnoreCase("TOTAL-RELATION")) { return MEnvironment.addConstraintTotalRelation(vname, firstRelation); } else if (constraintType.equalsIgnoreCase("PARTIAL-FUNCTION")) { return MEnvironment.addConstraintPartialFunction(vname, firstRelation); } else { // Unknown constraint type; throw an exception return MEnvironment.errorResponse(MEnvironment.sUnknown, MEnvironment.sConstraint, constraintType); } } else { return MEnvironment.errorResponse(MEnvironment.sCommand, MEnvironment.sNotExpected, addType); } }
From source file:com.nexmo.verify.sdk.NexmoVerifyClient.java
public CheckResult check(final String requestId, final String code, final String ipAddress) throws IOException, SAXException { if (requestId == null || code == null) throw new IllegalArgumentException("request ID and code parameters are mandatory."); log.debug("HTTP-Number-Verify-Check Client .. for [ " + requestId + " ] code [ " + code + " ] "); 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("request_id", requestId)); params.add(new BasicNameValuePair("code", code)); if (ipAddress != null) params.add(new BasicNameValuePair("ip_address", ipAddress)); String verifyCheckBaseUrl = this.baseUrl + PATH_VERIFY_CHECK; // Now that we have generated a query string, we can instanciate a HttpClient, // construct a POST method and execute to submit the request String response = null;// w ww . j a v a2s .co m for (int pass = 1; pass <= 2; pass++) { HttpPost httpPost = new HttpPost(verifyCheckBaseUrl); httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpUriRequest method = httpPost; String url = verifyCheckBaseUrl + "?" + 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 CheckResult(BaseResult.STATUS_COMMS_FAILURE, null, 0, null, "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 (!"verify_response".equals(root.getNodeName())) throw new IOException("No valid response found [ " + response + "] "); String eventId = null; int status = -1; float price = -1; String currency = null; String errorText = null; NodeList fields = root.getChildNodes(); for (int i = 0; i < fields.getLength(); i++) { Node node = fields.item(i); if (node.getNodeType() != Node.ELEMENT_NODE) continue; String name = node.getNodeName(); if ("event_id".equals(name)) { eventId = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); } else if ("status".equals(name)) { String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); try { if (str != null) status = Integer.parseInt(str); } catch (NumberFormatException e) { log.error("xml parser .. invalid value in <status> node [ " + str + " ] "); status = BaseResult.STATUS_INTERNAL_ERROR; } } else if ("price".equals(name)) { String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); try { if (str != null) price = Float.parseFloat(str); } catch (NumberFormatException e) { log.error("xml parser .. invalid value in <price> node [ " + str + " ] "); } } else if ("currency".equals(name)) { currency = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); } else if ("error_text".equals(name)) { errorText = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); } } if (status == -1) throw new IOException("Xml Parser - did not find a <status> node"); // Is this a temporary error ? boolean temporaryError = (status == BaseResult.STATUS_THROTTLED || status == BaseResult.STATUS_INTERNAL_ERROR); return new CheckResult(status, eventId, price, currency, errorText, temporaryError); }