List of usage examples for org.dom4j Node getStringValue
String getStringValue();
From source file:ca.coder2000.recipes.RecipeFile.java
License:Mozilla Public License
/** * Gets the ingredients list.//from w w w .ja v a2 s . c o m * @return The list of ingredients in the recipe. */ public ArrayList getIngredients() { ArrayList<Ingredient> list = new ArrayList<Ingredient>(); List lst = doc.selectNodes("//Ingredients/Ingredient"); Iterator i = lst.iterator(); while (i.hasNext()) { Node ing = (Node) i.next(); Node name = ing.selectSingleNode("//Name"); Node amount = ing.selectSingleNode("//Amount"); Node measure = ing.selectSingleNode("//Measure"); Ingredient j = new Ingredient(name.getStringValue(), amount.getStringValue(), measure.getStringValue()); list.add(j); } return list; }
From source file:com.chingo247.structureapi.plan.io.document.StructurePlanDocument.java
License:Open Source License
private Flag<?> makeFlag(LineElement node) { String name;/*from ww w .j a v a 2s.co m*/ String value; Element e = node.getElement(); if (e.attribute("name") != null) { if (e.attribute("value") == null) { throw new PlanException("No 'value' attribute for element in '" + getFile().getAbsolutePath() + "' on line " + node.getLine()); } name = e.attributeValue("name"); value = e.attributeValue("value"); } else if (e.selectSingleNode("Name") != null) { if (e.selectSingleNode("Name") == null) { throw new PlanException("No 'Value' element within element of '" + getFile().getAbsolutePath() + "' on line " + node.getLine()); } Node nameNode = e.selectSingleNode("Name"); Node valueNode = e.selectSingleNode("Value"); name = nameNode.getStringValue(); value = valueNode.getStringValue(); } else { throw new PlanException("Invalid flag element in '" + getFile().getAbsolutePath() + "' on line " + node.getLine() + ": No 'Name' or 'Value' defined"); } if (name.trim().isEmpty()) { throw new PlanException( "Name was emtpy in '" + getFile().getAbsolutePath() + "' on line " + node.getLine()); } if (value.trim().isEmpty()) { throw new PlanException( "Value was emtpy in '" + getFile().getAbsolutePath() + "' on line " + node.getLine()); } if (NumberUtils.isNumber(value)) { try { double d = Double.parseDouble(value); return new DoubleFlag(name, d); } catch (NumberFormatException nfe) { Integer i = Integer.parseInt(value); return new IntegerFlag(name, i); } } else if (value.equalsIgnoreCase("false") || value.equalsIgnoreCase("true")) { return new BooleanFlag(name, value.equalsIgnoreCase("true")); } else { return new StringFlag(name, value); } }
From source file:com.devoteam.srit.xmlloader.core.Parameter.java
License:Open Source License
public void applyXPath(String xml, String xpath, boolean deleteNS) throws Exception { // remove beginning to '<' character int iPosBegin = xml.indexOf('<'); if (iPosBegin > 0) { xml = xml.substring(iPosBegin);/*ww w . j a v a 2 s . c o m*/ } // remove from '>' character to the end int iPosEnd = xml.lastIndexOf('>'); if ((iPosEnd > 0) && (iPosEnd < xml.length() - 1)) { xml = xml.substring(0, iPosEnd + 1); } int iPosXMLLine = xml.indexOf("<?xml"); if (iPosXMLLine < 0) { xml = "<?xml version='1.0'?>" + xml; } // remove the namespace because the parser does not support them if there are not declare in the root node if (deleteNS) { xml = xml.replaceAll("<[a-zA-Z\\.0-9_]+:", "<"); xml = xml.replaceAll("</[a-zA-Z\\.0-9_]+:", "</"); } // remove doctype information (dtd files for the XML syntax) xml = xml.replaceAll("<!DOCTYPE\\s+\\w+\\s+\\w+\\s+[^>]+>", ""); InputStream input = new ByteArrayInputStream(xml.getBytes()); SAXReader reader = new SAXReader(false); reader.setEntityResolver(new XMLLoaderEntityResolver()); Document document = reader.read(input); XPath xpathObject = document.createXPath(xpath); Object obj = xpathObject.evaluate(document.getRootElement()); if (obj instanceof List) { List<Node> list = (List<Node>) obj; for (Node node : list) { add(node.asXML()); } } else if (obj instanceof DefaultElement) { Node node = (Node) obj; add(node.asXML()); } else if (obj instanceof DefaultAttribute) { Node node = (Node) obj; add(node.getStringValue()); } else if (obj instanceof DefaultText) { Node node = (Node) obj; add(node.getText()); } else { add(obj.toString()); } }
From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java
License:Apache License
/** * Submit a request to the server which expects an execution id in response, and return a single * QueuedItemResult parsed from the response. * * @param uploadFileParam name of file upload parameter * @param tempxml xml temp file (or null) * @param otherparams parameters for the request * @param requestPath path/*from w w w . j ava 2 s. com*/ * * @return a single QueuedItemResult * * @throws com.dtolabs.rundeck.core.dispatcher.CentralDispatcherException * if an error occurs */ private QueuedItemResult submitRunRequest(final File tempxml, final HashMap<String, String> otherparams, final HashMap<String, String> dataValues, final String requestPath, final String uploadFileParam) throws CentralDispatcherException { final HashMap<String, String> params = new HashMap<String, String>(); if (null != otherparams) { params.putAll(otherparams); } final HashMap<String, String> data = new HashMap<String, String>(); if (null != dataValues) { data.putAll(dataValues); } final WebserviceResponse response; try { response = serverService.makeRundeckRequest(requestPath, params, tempxml, null, null, data, uploadFileParam); } catch (MalformedURLException e) { throw new CentralDispatcherServerRequestException("Failed to make request", e); } validateResponse(response); final Document resultDoc = response.getResultDoc(); if (null != resultDoc.selectSingleNode("/result/execution") && null != resultDoc.selectSingleNode("/result/execution/@id")) { final Node node = resultDoc.selectSingleNode("/result/execution/@id"); final String succeededId = node.getStringValue(); final String name = "adhoc"; String url = createExecutionURL(succeededId); url = makeAbsoluteURL(url); logger.info("\t[" + succeededId + "] <" + url + ">"); return QueuedItemResultImpl.successful("Succeeded queueing " + name, succeededId, url, name); } return QueuedItemResultImpl.failed("Server response contained no success information."); }
From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java
License:Apache License
private ArrayList<QueuedItem> parseExecutionListResult(final WebserviceResponse response) { final Document resultDoc = response.getResultDoc(); final Node node = resultDoc.selectSingleNode("/result/executions"); final List items = node.selectNodes("execution"); final ArrayList<QueuedItem> list = new ArrayList<QueuedItem>(); if (null != items && items.size() > 0) { for (final Object o : items) { final Node node1 = (Node) o; final String id = node1.selectSingleNode("@id").getStringValue(); final Node jobname = node1.selectSingleNode("job/name"); final Node desc = node1.selectSingleNode("description"); final String name; if (null != jobname) { name = jobname.getStringValue(); } else { name = desc.getStringValue(); }//from w w w . j a v a 2s .co m String url = node1.selectSingleNode("@href").getStringValue(); url = makeAbsoluteURL(url); logger.info("\t" + ": " + name + " [" + id + "] <" + url + ">"); list.add(QueuedItemResultImpl.createQueuedItem(id, url, name)); } } return list; }
From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java
License:Apache License
/** * Follow execution output for an Execution by synchronously emitting output to a receiver * @param execId execution ID//from w w w. j a v a 2 s . c o m * @param request request * @param receiver output receiver * @return result * @throws CentralDispatcherException on error */ public ExecutionFollowResult followDispatcherExecution(final String execId, final ExecutionFollowRequest request, final ExecutionFollowReceiver receiver) throws CentralDispatcherException { final String rundeckApiExecOutputJobPath = substitutePathVariable(RUNDECK_API_EXEC_OUTPUT_PATH, "id", execId) + ".xml"; //output complete boolean complete = false; boolean interrupt = false; boolean receiverfinished = false; boolean jobsuccess = false; boolean jobcomplete = false; boolean jobcancel = false; //byte offset Long offset = 0L; Long rlastmod = 0L; boolean resume = null != request && request.isResume(); //percent complete double percentage = 0.0; //delay between requests final int BASE_DELAY = 1000; final int MAX_DELAY = 5000; long delay = BASE_DELAY; float backoff = 1f; String jobstatus = null; while (!complete && !interrupt && !receiverfinished) { //follow output until complete final HashMap<String, String> params = new HashMap<String, String>(); if (resume) { params.put("lastlines", "0"); resume = false; } else { params.put("offset", offset.toString()); params.put("lastmod", rlastmod.toString()); } params.put("maxlines", "500"); logger.debug("request" + rundeckApiExecOutputJobPath + " params: " + params); //2. send request via ServerService final WebserviceResponse response; try { response = serverService.makeRundeckRequest(rundeckApiExecOutputJobPath, params, null, null, null); } catch (MalformedURLException e) { throw new CentralDispatcherServerRequestException("Failed to make request", e); } final Envelope envelope = validateResponse(response); final Node result1 = envelope.doc.selectSingleNode("result/output"); if (null == result1) { throw new CentralDispatcherServerRequestException("Response output was unexpected"); } final String errorStr = stringNodeValue(result1, "error", null); final String messageStr = stringNodeValue(result1, "message", null); final Boolean unmodified = boolNodeValue(result1, "unmodified", null); final Boolean empty = boolNodeValue(result1, "empty", null); final Boolean iscompleted = boolNodeValue(result1, "completed", null); final Boolean jobcompleted = boolNodeValue(result1, "execCompleted", null); jobstatus = stringNodeValue(result1, "execState", null); final Long lastmod = longNodeValue(result1, "lastModified", 0); final Long duration = longNodeValue(result1, "execDuration", 0); final Long totalsize = longNodeValue(result1, "totalSize", 0); final Double percentLoaded = floatNodeValue(result1, "percentLoaded", 0.0); final Long dataoffset = longNodeValue(result1, "offset", -1L); if (dataoffset > 0 && dataoffset > offset) { offset = dataoffset; } if (lastmod > 0 && lastmod > rlastmod) { rlastmod = lastmod; } if (percentLoaded > 0.0 && percentLoaded > percentage) { percentage = percentLoaded; } //update delay if (null != unmodified && unmodified && delay < MAX_DELAY) { delay = delay + (Math.round(backoff * BASE_DELAY)); } else if (null != unmodified && !unmodified) { delay = BASE_DELAY; } if (null != iscompleted) { complete = iscompleted; } if (null != receiver && !receiver.receiveFollowStatus(offset, totalsize, duration)) { //end receiverfinished = true; break; } final List list = result1.selectNodes("entries/entry"); for (final Object obj : list) { Node node = (Node) obj; final String timeStr = stringNodeValue(node, "@time", null); final String levelStr = stringNodeValue(node, "@level", null); final String user = stringNodeValue(node, "@user", null); final String command = stringNodeValue(node, "@command", null); final String nodeName = stringNodeValue(node, "@node", null); final String logMessage = node.getStringValue(); if (null != receiver && !receiver.receiveLogEntry(timeStr, levelStr, user, command, nodeName, logMessage)) { receiverfinished = true; break; } } //sleep delay try { Thread.sleep(delay); } catch (InterruptedException e) { interrupt = true; } } final boolean finalComplete = complete; final boolean finalReceiverfinished = receiverfinished; ExecutionState state = null; if (null != jobstatus) { try { state = ExecutionState.valueOf(jobstatus); } catch (IllegalArgumentException e) { } } final ExecutionState finalState = state; return new ExecutionFollowResult() { public boolean isLogComplete() { return finalComplete; } public ExecutionState getState() { return finalState; } public boolean isReceiverFinished() { return finalReceiverfinished; } }; }
From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java
License:Apache License
public Collection<IStoredJob> listStoredJobs(final IStoredJobsQuery iStoredJobsQuery, final OutputStream output, final JobDefinitionFileFormat fformat) throws CentralDispatcherException { final HashMap<String, String> params = new HashMap<String, String>(); final String nameMatch = iStoredJobsQuery.getNameMatch(); String groupMatch = iStoredJobsQuery.getGroupMatch(); final String projectFilter = iStoredJobsQuery.getProjectFilter(); final String idlistFilter = iStoredJobsQuery.getIdlist(); final String expectedContentType; if (null != fformat) { params.put("format", fformat.getName()); expectedContentType = fformat == JobDefinitionFileFormat.xml ? "text/xml" : "text/yaml"; } else {/*from w w w . j a va 2s. c om*/ params.put("format", JobDefinitionFileFormat.xml.getName()); expectedContentType = "text/xml"; } if (null != nameMatch) { params.put("jobFilter", nameMatch); } if (null != groupMatch) { final Matcher matcher = Pattern.compile("^/*(.+?)/*$").matcher(groupMatch); if (matcher.matches()) { //strip leading and trailing slashes groupMatch = matcher.group(1); } params.put("groupPath", groupMatch); } if (null != projectFilter) { params.put("project", projectFilter); } if (null != idlistFilter) { params.put("idlist", idlistFilter); } //2. send request via ServerService final WebserviceResponse response; try { response = serverService.makeRundeckRequest(RUNDECK_API_JOBS_EXPORT_PATH, params, null, null, expectedContentType, null); } catch (MalformedURLException e) { throw new CentralDispatcherServerRequestException("Failed to make request", e); } checkErrorResponse(response); //if xml, do local validation and listing if (null == fformat || fformat == JobDefinitionFileFormat.xml) { validateJobsResponse(response); //////////////////// //parse result list of queued items, return the collection of QueuedItems /////////////////// final Document resultDoc = response.getResultDoc(); final Node node = resultDoc.selectSingleNode("/joblist"); final ArrayList<IStoredJob> list = new ArrayList<IStoredJob>(); if (null == node) { return list; } final List items = node.selectNodes("job"); if (null != items && items.size() > 0) { for (final Object o : items) { final Node node1 = (Node) o; final Node uuid = node1.selectSingleNode("uuid"); final Node id1 = node1.selectSingleNode("id"); final String id = null != uuid ? uuid.getStringValue() : id1.getStringValue(); final String name = node1.selectSingleNode("name").getStringValue(); final String url = createJobURL(id); final Node gnode = node1.selectSingleNode("group"); final String group = null != gnode ? gnode.getStringValue() : null; final String description = node1.selectSingleNode("description").getStringValue(); list.add(StoredJobImpl.create(id, name, url, group, description, projectFilter)); } } if (null != output) { //write output doc to the outputstream final OutputFormat format = OutputFormat.createPrettyPrint(); try { final XMLWriter writer = new XMLWriter(output, format); writer.write(resultDoc); writer.flush(); } catch (IOException e) { throw new CentralDispatcherServerRequestException(e); } } return list; } else if (fformat == JobDefinitionFileFormat.yaml) { //do rough yaml parse final Collection<Map> mapCollection; //write to temp file File temp; InputStream tempIn; try { temp = File.createTempFile("listStoredJobs", ".yaml"); temp.deleteOnExit(); OutputStream os = new FileOutputStream(temp); try { Streams.copyStream(response.getResultStream(), os); } finally { os.close(); } tempIn = new FileInputStream(temp); try { mapCollection = validateJobsResponseYAML(response, tempIn); } finally { tempIn.close(); } } catch (IOException e) { throw new CentralDispatcherServerRequestException(e); } final ArrayList<IStoredJob> list = new ArrayList<IStoredJob>(); if (null == mapCollection || mapCollection.size() < 1) { return list; } for (final Map map : mapCollection) { final Object uuidobj = map.get("uuid"); final Object idobj = map.get("id"); final String id = null != uuidobj ? uuidobj.toString() : idobj.toString(); final String name = (String) map.get("name"); final String group = map.containsKey("group") ? (String) map.get("group") : null; final String desc = map.containsKey("description") ? (String) map.get("description") : ""; final String url = createJobURL(id); list.add(StoredJobImpl.create(id, name, url, group, desc, projectFilter)); } if (null != output) { //write output doc to the outputstream try { tempIn = new FileInputStream(temp); try { Streams.copyStream(tempIn, output); } finally { tempIn.close(); } temp.delete(); } catch (IOException e) { throw new CentralDispatcherServerRequestException(e); } } return list; } return null; }
From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java
License:Apache License
public Collection<DeleteJobResult> deleteStoredJobs(Collection<String> jobIds) throws CentralDispatcherException { final Map<String, Object> params = new HashMap<String, Object>(); params.put("ids", jobIds); final WebserviceResponse response; try {//from w ww .j a v a 2 s .c o m response = serverService.makeRundeckRequest(RUNDECK_API_JOBS_BULK_DELETE_PATH, null, params); } catch (MalformedURLException e) { throw new CentralDispatcherServerRequestException("Failed to make request", e); } checkErrorResponse(response); //////////////////// //parse result list of delete result items, return the collection of DeleteJobResult /////////////////// final Document result = response.getResultDoc(); final int succeeded; final int failed; Node node = result.selectSingleNode("/result/deleteJobs/succeeded/@count"); if (null != node) { succeeded = Integer.parseInt(node.getStringValue()); } else { succeeded = -1; } node = result.selectSingleNode("/result/deleteJobs/failed/@count"); if (null != node) { failed = Integer.parseInt(node.getStringValue()); } else { failed = -1; } final ArrayList<DeleteJobResult> resultList = new ArrayList<DeleteJobResult>(); if (succeeded > 0) { logger.debug("Succeeded deleting " + succeeded + " Jobs:"); final List nodes = result.selectNodes("/result/deleteJobs/succeeded/deleteJobResult"); for (final Object node2 : nodes) { final Node node1 = (Node) node2; final String message = null != node1.selectSingleNode("message") ? node1.selectSingleNode("message").getStringValue() : "Succeeded"; final DeleteJobResult storedJobLoadResult = parseAPIJobDeleteResult(node1, true, message); resultList.add(storedJobLoadResult); } } if (failed > 0) { logger.debug("Failed to delete " + failed + " Jobs:"); final List nodes = result.selectNodes("/result/deleteJobs/failed/deleteJobResult"); for (final Object node2 : nodes) { final Node node1 = (Node) node2; final String error = null != node1.selectSingleNode("error") ? node1.selectSingleNode("error").getStringValue() : "Failed"; final DeleteJobResult storedJobLoadResult = parseAPIJobDeleteResult(node1, false, error); resultList.add(storedJobLoadResult); } } return resultList; }
From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java
License:Apache License
public Collection<IStoredJobLoadResult> loadJobs(final ILoadJobsRequest iLoadJobsRequest, final File input, final JobDefinitionFileFormat format) throws CentralDispatcherException {/*w w w . j a va 2 s . c o m*/ final HashMap<String, String> params = new HashMap<String, String>(); params.put("dupeOption", iLoadJobsRequest.getDuplicateOption().toString()); if (null != format) { params.put("format", format.getName()); } if (null != iLoadJobsRequest.getProject()) { params.put("project", iLoadJobsRequest.getProject()); } if (null != iLoadJobsRequest.getUUIDOption()) { params.put("uuidOption", iLoadJobsRequest.getUUIDOption().toString()); } /* * Send the request bean and the file as a multipart request. */ //2. send request via ServerService final WebserviceResponse response; try { response = serverService.makeRundeckRequest(RUNDECK_API_JOBS_UPLOAD, params, input, null, "xmlBatch"); } catch (MalformedURLException e) { throw new CentralDispatcherServerRequestException("Failed to make request", e); } validateResponse(response); //////////////////// //parse result list of queued items, return the collection of QueuedItems /////////////////// final Document result = response.getResultDoc(); final int succeeded; final int failed; final int skipped; Node node = result.selectSingleNode("/result/succeeded/@count"); if (null != node) { succeeded = Integer.parseInt(node.getStringValue()); } else { succeeded = -1; } node = result.selectSingleNode("/result/failed/@count"); if (null != node) { failed = Integer.parseInt(node.getStringValue()); } else { failed = -1; } node = result.selectSingleNode("/result/skipped/@count"); if (null != node) { skipped = Integer.parseInt(node.getStringValue()); } else { skipped = -1; } final ArrayList<IStoredJobLoadResult> resultList = new ArrayList<IStoredJobLoadResult>(); if (succeeded > 0) { logger.debug("Succeeded creating/updating " + succeeded + " Jobs:"); final List nodes = result.selectNodes("/result/succeeded/job"); for (final Object node2 : nodes) { final Node node1 = (Node) node2; final IStoredJobLoadResult storedJobLoadResult = parseAPIJobResult(node1, true, false, "Succeeded"); resultList.add(storedJobLoadResult); } } if (failed > 0) { logger.debug("Failed to add " + failed + " Jobs:"); final List nodes = result.selectNodes("/result/failed/job"); for (final Object node2 : nodes) { final Node node1 = (Node) node2; final String error = null != node1.selectSingleNode("error") ? node1.selectSingleNode("error").getStringValue() : "Failed"; final IStoredJobLoadResult storedJobLoadResult = parseAPIJobResult(node1, false, false, error); resultList.add(storedJobLoadResult); } } if (skipped > 0) { logger.debug("Skipped " + skipped + " Jobs:"); final List nodes = result.selectNodes("/result/skipped/job"); for (final Object node2 : nodes) { final Node node1 = (Node) node2; final String error = null != node1.selectSingleNode("error") ? node1.selectSingleNode("error").getStringValue() : "Skipped"; final IStoredJobLoadResult storedJobLoadResult = parseAPIJobResult(node1, true, true, error); resultList.add(storedJobLoadResult); } } return resultList; }
From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java
License:Apache License
private DeleteJobResult parseAPIJobDeleteResult(final Node node1, final boolean successful, final String message) { final Node idNode = node1.selectSingleNode("@id"); final String id = null != idNode ? idNode.getStringValue() : null; final Node codeNode = node1.selectSingleNode("errorCode"); final String errorCode = null != codeNode ? codeNode.getStringValue() : null; logger.debug("\t[" + id + "] " + message); return DeleteJobResultImpl.createDeleteJobResultImpl(successful, message, id, errorCode); }