Example usage for org.dom4j Node selectSingleNode

List of usage examples for org.dom4j Node selectSingleNode

Introduction

In this page you can find the example usage for org.dom4j Node selectSingleNode.

Prototype

Node selectSingleNode(String xpathExpression);

Source Link

Document

selectSingleNode evaluates an XPath expression and returns the result as a single Node instance.

Usage

From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java

License:Apache License

private double floatNodeValue(final Node result1, final String path, final double defValue) {
    if (null != result1.selectSingleNode(path)) {
        try {/*from   www. jav  a2 s.  c o  m*/
            Float.parseFloat(result1.selectSingleNode(path).getStringValue());
        } catch (NumberFormatException e) {

        }
    }
    return defValue;
}

From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java

License:Apache License

private long longNodeValue(final Node result1, final String path, final long defValue) {
    if (null != result1.selectSingleNode(path)) {
        try {//from   w w  w  . j  av a  2 s  .  c om
            return Long.parseLong(result1.selectSingleNode(path).getStringValue());
        } catch (NumberFormatException e) {

        }
    }
    return defValue;
}

From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java

License:Apache License

private Date w3cDateNodeValue(final Node result1, final String path, final Date defValue) {
    if (null != result1.selectSingleNode(path)) {
        final String stringValue = result1.selectSingleNode(path).getStringValue();
        try {/*from   w  w w  .  j a  v a 2 s . c  om*/
            return w3cDateFormat.parse(stringValue);
        } catch (ParseException e) {

        }
    }
    return defValue;
}

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 ww.  j  a va  2  s  .  co  m*/
        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  .ja  v  a2  s .  co 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<IStoredJob> reallistStoredJobs(final IStoredJobsQuery iStoredJobsQuery)
        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();

    if (null != nameMatch) {
        params.put("jobExactFilter", nameMatch);
    }//from ww w . ja  v  a2s  . co  m
    if (null != groupMatch) {
        final Matcher matcher = Pattern.compile("^/*(.+?)/*$").matcher(groupMatch);
        if (matcher.matches()) {
            //strip leading and trailing slashes
            groupMatch = matcher.group(1);
        }
        params.put("groupPathExact", 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_LIST_PATH, params, null, null, null);
    } catch (MalformedURLException e) {
        throw new CentralDispatcherServerRequestException("Failed to make request", e);
    }
    validateResponse(response);
    //extract job list
    final Document resultDoc = response.getResultDoc();
    final ArrayList<IStoredJob> list = new ArrayList<IStoredJob>();

    final Node jobs = resultDoc.selectSingleNode("/result/jobs");
    for (final Object job1 : jobs.selectNodes("job")) {
        final Node job = (Node) job1;
        final String id = job.selectSingleNode("@id").getStringValue();
        final String name = job.selectSingleNode("name").getStringValue();
        final String group = job.selectSingleNode("group").getStringValue();
        final String desc = job.selectSingleNode("description").getStringValue();
        final String url = createJobURL(id);
        list.add(StoredJobImpl.create(id, name, url, group, desc, projectFilter));
    }

    return list;
}

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 {/*from   www . jav  a  2s . 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);
}

From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java

License:Apache License

private IStoredJobLoadResult parseAPIJobResult(final Node node1, final boolean successful,
        final boolean skippedJob, final String message) {
    final Node uuidNode = node1.selectSingleNode("uuid");
    final Node idNode = node1.selectSingleNode("id");
    final String id = null != uuidNode ? uuidNode.getStringValue()
            : null != idNode ? idNode.getStringValue() : null;
    final String name = node1.selectSingleNode("name").getStringValue();
    final String url = null != id ? createJobURL(id) : null;
    final String group = null != node1.selectSingleNode("group")
            ? node1.selectSingleNode("group").getStringValue()
            : null;/*from  w ww .j  a va 2 s .c  om*/
    final String description = null != node1.selectSingleNode("description")
            ? node1.selectSingleNode("description").getStringValue()
            : null;
    final String project = null != node1.selectSingleNode("project")
            ? node1.selectSingleNode("project").getStringValue()
            : null;
    logger.debug("\t" + name + " [" + id + "] <" + url + "> (" + project + ")");
    return StoredJobLoadResultImpl.createLoadResult(id, name, url, group, description, project, successful,
            skippedJob, message);
}

From source file:com.dtolabs.client.services.RundeckCentralDispatcher.java

License:Apache License

/**
 * Submit a request to the server which expects a list of queued item results in the response, and return a single QueuedItemResult parsed from the response.
 *
 * @param tempxml xml temp file (or null)
 * @param otherparams parameters for the request
 *
 * @param requestPath// w  w  w  .  ja v a 2  s. co m
 * @return a single QueuedItemResult
 *
 * @throws CentralDispatcherException if an error occurs
 */
private QueuedItemResult submitQueueRequest(final File tempxml, final HashMap<String, String> otherparams,
        final String requestPath) throws CentralDispatcherException {

    final HashMap<String, String> params = new HashMap<String, String>();
    params.put("xmlreq", "true");
    if (null != otherparams) {
        params.putAll(otherparams);
    }

    final WebserviceResponse response;
    try {
        response = serverService.makeRundeckRequest(requestPath, params, tempxml, null);
    } catch (MalformedURLException e) {
        throw new CentralDispatcherServerRequestException("Failed to make request", e);
    }
    validateResponse(response);

    ////////////////////
    //parse result list of execution responses.  this implementation handles multiple responses, but only
    //returns a single QueuedItem (the first one found).
    //TODO: update to return multiple QueuedItems when multiple job queue requests are supported
    ///////////////////

    final Document resultDoc = response.getResultDoc();

    final int succeeded;
    final int failed;

    Node node = resultDoc.selectSingleNode("/result/succeeded/@count");
    if (null != node) {
        succeeded = Integer.parseInt(node.getStringValue());
    } else {
        succeeded = -1;
    }
    node = resultDoc.selectSingleNode("/result/failed/@count");
    if (null != node) {
        failed = Integer.parseInt(node.getStringValue());
    } else {
        failed = -1;
    }
    final String succeededId;
    if (succeeded > 0) {
        logger.info("Succeeded queueing " + succeeded + " Job" + (succeeded > 1 ? "s" : "") + ":");
        final List nodes = resultDoc.selectNodes("/result/succeeded/execution");
        final Node node1 = (Node) nodes.iterator().next();
        final String index = node1.selectSingleNode("@index").getStringValue();
        final String id = node1.selectSingleNode("id").getStringValue();
        succeededId = id;
        final String name = node1.selectSingleNode("name").getStringValue();
        String url = node1.selectSingleNode("url").getStringValue();
        url = makeAbsoluteURL(url);
        logger.info("\t" + index + ": " + name + " [" + id + "] <" + url + ">");
        return QueuedItemResultImpl.successful("Succeeded queueing " + name, succeededId, url, name);
    }
    if (failed > 0) {
        final String s1 = "Failed to queue " + failed + " Job" + (failed > 1 ? "s" : "") + ":";
        logger.error(s1);
        final List nodes = resultDoc.selectNodes("/result/failed/execution");
        final Node node1 = (Node) nodes.iterator().next();
        final String index = node1.selectSingleNode("@index").getStringValue();
        final String id = null != node1.selectSingleNode("id") ? node1.selectSingleNode("id").getStringValue()
                : null;
        String url = null != node1.selectSingleNode("url") ? node1.selectSingleNode("url").getStringValue()
                : null;
        url = makeAbsoluteURL(url);
        final String error = null != node1.selectSingleNode("error")
                ? node1.selectSingleNode("error").getStringValue()
                : null;
        final String message = null != node1.selectSingleNode("message")
                ? node1.selectSingleNode("message").getStringValue()
                : null;
        final String errmsg = error + (null != id ? " [" + id + "] <" + url + ">" : "")
                + (null != message ? " : " + message : "");
        final String s2 = index + ": " + errmsg;
        logger.error(s2);
        return QueuedItemResultImpl.failed(errmsg);
    }
    return QueuedItemResultImpl.failed("Server response contained no success information.");
}