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.RundeckCentralDispatcher.java

License:Apache License

public Collection<QueuedItem> listDispatcherQueue(final String project) throws CentralDispatcherException {
    final HashMap<String, String> params = new HashMap<String, String>();
    params.put("xmlreq", "true");
    if (null != project) {
        params.put("projFilter", project);
    }//w  w w  .ja v  a2  s  .co m

    final WebserviceResponse response;
    try {
        response = serverService.makeRundeckRequest(RUNDECK_LIST_EXECUTIONS_PATH, params, null, null);
    } 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 resultDoc = response.getResultDoc();

    final Node node = resultDoc.selectSingleNode("/result/items");
    final List items = node.selectNodes("item");
    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 String name = node1.selectSingleNode("name").getStringValue();
            String url = node1.selectSingleNode("url").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.RundeckCentralDispatcher.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();

    if (null != output && null != fformat) {
        params.put("format", fformat.getName());
    } else {/*from w w  w.j a va  2 s  . c o m*/
        params.put("format", JobDefinitionFileFormat.xml.getName());
    }
    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("projFilter", projectFilter);
    }
    if (null != idlistFilter) {
        params.put("idlist", idlistFilter);
    }

    //2. send request via ServerService
    final WebserviceResponse response;
    try {
        response = serverService.makeRundeckRequest(RUNDECK_LIST_STORED_JOBS_PATH, params, null, null);
    } catch (MalformedURLException e) {
        throw new CentralDispatcherServerRequestException("Failed to make request", e);
    }

    //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 String id = node1.selectSingleNode("id").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 rought yaml parse
        final Collection<Map> mapCollection = validateJobsResponseYAML(response);
        final ArrayList<IStoredJob> list = new ArrayList<IStoredJob>();

        if (null == mapCollection || mapCollection.size() < 1) {
            return list;
        }
        for (final Map map : mapCollection) {
            final String id = map.get("id").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 {
                final Writer writer = new OutputStreamWriter(output);
                writer.write(response.getResults());
                writer.flush();
            } catch (IOException e) {
                throw new CentralDispatcherServerRequestException(e);
            }
        }
        return list;
    }
    return null;
}

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

License:Apache License

public Collection<IStoredJobLoadResult> loadJobs(final ILoadJobsRequest iLoadJobsRequest, final File input,
        final JobDefinitionFileFormat format) throws

CentralDispatcherException {// www  .jav  a2s  .c  o m
    final HashMap params = new HashMap();
    params.put("dupeOption", iLoadJobsRequest.getDuplicateOption().toString());
    params.put("xmlreq", "true");

    if (null != format) {
        params.put("fileformat", format.getName());
    }

    /*
     * Send the request bean and the file as a multipart request.
     */

    //2. send request via ServerService
    final WebserviceResponse response;
    try {
        response = serverService.makeRundeckRequest(RUNDECK_JOBS_UPLOAD, params, input, null);
    } 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;
    }
    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 = parseStoredJobResult(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 = parseStoredJobResult(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 = parseStoredJobResult(node1, true, true, error);
            resultList.add(storedJobLoadResult);

        }
    }
    return resultList;
}

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

License:Apache License

private IStoredJobLoadResult parseStoredJobResult(final Node node1, final boolean successful,
        final boolean skippedJob, final String message) {
    final String index = node1.selectSingleNode("@index").getStringValue();
    final Node idNode = node1.selectSingleNode("id");
    final String id = null != idNode ? idNode.getStringValue() : null;
    final String name = node1.selectSingleNode("name").getStringValue();
    final Node urlNode = node1.selectSingleNode("url");
    final String url = null != urlNode ? makeAbsoluteURL(urlNode.getStringValue()) : null;
    final String group = null != node1.selectSingleNode("group")
            ? node1.selectSingleNode("group").getStringValue()
            : null;//from   ww w. j a  v  a 2  s .com
    final String description = null != node1.selectSingleNode("description")
            ? node1.selectSingleNode("description").getStringValue()
            : null;
    logger.debug("\t" + index + ": " + name + " [" + id + "] <" + url + ">");
    int ndx = -1;
    try {
        ndx = Integer.parseInt(index);
    } catch (NumberFormatException e) {

    }
    return StoredJobLoadResultImpl.createLoadResult(id, name, url, group, description, successful, skippedJob,
            message);
}

From source file:com.dtolabs.shared.resources.ResourceXMLParser.java

License:Apache License

/**
 * Parse a simple resource/entity node for the type/name attributes, returning a new or existing Entity
 *
 * @param set entity set//  w  w w .j av  a  2s. co  m
 * @param n   entity DOM node
 *
 * @return new or existing Entity
 *
 * @throws ResourceXMLParserException if the ndoe is missing the required attributes
 */
private Entity parseResourceRef(final EntitySet set, final Node n) throws ResourceXMLParserException {
    final Node node2 = n.selectSingleNode("@" + COMMON_NAME);
    if (null == node2) {
        throw new ResourceXMLParserException("@" + COMMON_NAME + " required: " + reportNodeErrorLocation(n));
    }
    final String rname = node2.getStringValue();
    return set.getOrCreateEntity(rname);
}

From source file:com.flaptor.hounder.indexer.MultiIndexer.java

License:Apache License

protected IndexerReturnCode processCommand(final Document doc) {
    Node commandNode = doc.selectSingleNode("/command");
    Node attNode = commandNode.selectSingleNode("@node");

    if (null == attNode) { // so it is for all nodes

        for (IRemoteIndexer indexer : indexers) {
            boolean accepted = false;
            int retries = 0;

            // try until accepted, or too much retries.
            while (!accepted && retries < RETRY_LIMIT) {
                try {
                    IndexerReturnCode retValue = indexer.index(doc);
                    if (IndexerReturnCode.SUCCESS == retValue) {
                        accepted = true;
                    } else {
                        retries++;//from  w ww . java 2 s.  c  o  m
                        Execute.sleep(10 * 1000); // wait 10 seconds before retry
                    }
                } catch (com.flaptor.util.remote.RpcException e) {
                    logger.error("processCommand: Connection failed: " + e.getMessage(), e);
                }
            }
            // if could not send to indexer
            if (!accepted) {
                logger.error(
                        "processCommand: tried " + RETRY_LIMIT + " times to index command, but failed on node "
                                + indexer.toString() + ". Will not continue with other indexers.");
                return IndexerReturnCode.FAILURE;

            }
        }
        // in case no one returned Indexer.FAILURE
        return IndexerReturnCode.SUCCESS;
    } else { // specific node

        try {
            int indexerNumber = Integer.parseInt(attNode.getText());
            if (indexerNumber < indexers.size() && indexerNumber >= 0) {
                IRemoteIndexer indexer = indexers.get(indexerNumber);
                try {
                    return indexer.index(doc);
                } catch (com.flaptor.util.remote.RpcException e) {
                    logger.error("processCommand: while sending command to single node " + indexer.toString()
                            + " " + e.getMessage(), e);
                    return IndexerReturnCode.FAILURE;
                }
            } else {
                logger.error("processCommand: received command for node number out of indexers range. Received "
                        + indexerNumber + " and have " + indexers.size() + " indexers. Ignoring command.");
                return IndexerReturnCode.FAILURE;
            }
        } catch (NumberFormatException e) {
            logger.error("processCommand: can not parse node number: " + e, e);
            return IndexerReturnCode.PARSE_ERROR;
        }
    }
}

From source file:com.genericworkflownodes.knime.config.impl.DOMHelper.java

License:Open Source License

public static Node selectSingleNode(Node root, String query) throws Exception {
    Node result = root.selectSingleNode(query);
    if (result == null) {
        throw new Exception("XPath query yielded null result");
    }// w w w  . ja  v a  2 s. com
    return result;
}

From source file:com.globalsight.cxe.adapter.serviceware.Importer.java

License:Apache License

/**
 * Makes a special ServiceWareXML that contains the fields
 * GlobalSight needs to localize/*from   www.  j a  va 2s .  co  m*/
 *
 * @param p_koXml knowledge object XML
 * @return Service Ware XML to localize
 * @exception Exception
 */
private String makeServiceWareXml(String p_sessionId, String p_koXml) throws Exception {
    //first get some data from the knowledge objxml
    XmlParser xmlp = XmlParser.hire();
    Document d = xmlp.parseXml(p_koXml);
    Element root = d.getRootElement();
    String koName = root.selectSingleNode("/GetKOsResponse/return/SessionKOs/KO/Name").getText();
    m_koName = koName;
    String koShortDesc = root.selectSingleNode("/GetKOsResponse/return/SessionKOs/KO/ShortDescription")
            .getText();
    StringBuffer swXml = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
    swXml.append("<serviceWareXml>\r\n");
    swXml.append("<knowledgeObj id=\"");
    swXml.append(m_koid);
    swXml.append("\">\r\n");
    swXml.append("<knowledgeObjName>");
    swXml.append(koName);
    swXml.append("</knowledgeObjName>\r\n");
    swXml.append("<knowledgeObjShortDesc>");
    swXml.append(koShortDesc);
    swXml.append("</knowledgeObjShortDesc>\r\n");
    List conceptIdListNodes = root.selectNodes("/GetKOsResponse/return/SessionKOs/KO/ConceptIDs");
    String conceptIdListOrig = ((Node) conceptIdListNodes.get(0)).getText();
    m_logger.debug("orig concept Id list: " + conceptIdListOrig);
    String conceptIdList = conceptIdListOrig.replaceAll(", ", ",");
    m_logger.debug("fixed concept Ids: " + conceptIdList);

    //get the XML for all concept Objs
    String conceptObjXml = ServiceWareAPI.getConceptObjectXml(p_sessionId, conceptIdList);
    XmlParser conceptXmlp = XmlParser.hire();
    Document conceptDoc = conceptXmlp.parseXml(conceptObjXml);
    Element conceptRoot = conceptDoc.getRootElement();
    List conceptNodes = conceptRoot.selectNodes("/GetConceptsResponse/return/SessionConcepts/Concept");
    m_logger.debug("There are " + conceptNodes.size() + " concept nodes.");
    for (int i = 0; i < conceptNodes.size(); i++) {
        Node conceptNode = (Node) conceptNodes.get(i);
        String conceptId = conceptNode.selectSingleNode("ConceptID").getText();
        String conceptName = conceptNode.selectSingleNode("Name").getText();
        String conceptShortDesc = conceptNode.selectSingleNode("ShortDescription").getText();
        swXml.append("<concept id=\"");
        swXml.append(conceptId);
        swXml.append("\">");
        swXml.append("<conceptName>");
        swXml.append(conceptName);
        swXml.append("</conceptName>\r\n");
        swXml.append("<conceptShortDesc>");
        swXml.append(conceptShortDesc);
        swXml.append("</conceptShortDesc>\r\n");
        swXml.append("</concept>\r\n");
    }
    swXml.append("</knowledgeObj>\r\n");
    swXml.append("</serviceWareXml>\r\n");
    XmlParser.fire(conceptXmlp);
    XmlParser.fire(xmlp);
    return swXml.toString();
}

From source file:com.globalsight.cxe.adapter.serviceware.ServiceWareAPI.java

License:Apache License

/**
 * Takes in a serviceware xml and gets all IDs, names, and short
 * descriptions from it for updating ServiceWare
 * /*w ww.j ava  2 s .  c  o  m*/
 * @param p_sessionId
 * @param p_serviceWareXml
 * @return
 */
public static void updateKnowledgeAndConceptObjects(String p_sessionId, String p_serviceWareXml,
        String p_targetLocale) throws Exception {
    XmlParser xmlp = XmlParser.hire();
    Document d = xmlp.parseXml(p_serviceWareXml);
    Element root = d.getRootElement();
    String koID = root.selectSingleNode("/serviceWareXml/knowledgeObj/@id").getText();
    String koName = root.selectSingleNode("/serviceWareXml/knowledgeObj/knowledgeObjName").getText();
    String koShortDesc = root.selectSingleNode("/serviceWareXml/knowledgeObj/knowledgeObjShortDesc").getText();
    ServiceWareAPI.updateKnowledgeObject(p_sessionId, koID, koName, koShortDesc, p_targetLocale);

    // now update the concepts
    List conceptNodes = root.selectNodes("/serviceWareXml/knowledgeObj/concept");
    for (int i = 0; i < conceptNodes.size(); i++) {
        Node conceptNode = (Node) conceptNodes.get(i);
        String conceptId = conceptNode.selectSingleNode("@id").getText();
        String conceptName = conceptNode.selectSingleNode("conceptName").getText();
        String conceptShortDesc = conceptNode.selectSingleNode("conceptShortDesc").getText();
        ServiceWareAPI.updateConceptObject(p_sessionId, conceptId, conceptName, conceptShortDesc,
                p_targetLocale);
    }
    XmlParser.fire(xmlp);
}

From source file:com.globalsight.smartbox.util.WebClientHelper.java

License:Apache License

/**
 * Get jobStatus from GS Server//w  ww  .  j  av a 2  s.c o m
 * 
 * @param jobInfo
 * @return
 * @throws Exception
 */
public static boolean getJobStatus(JobInfo jobInfo) {
    try {
        String jobStatus = ambassador.getJobStatus(accessToken, jobInfo.getJobName());
        Document profileDoc = DocumentHelper.parseText(jobStatus);
        Node node = profileDoc.selectSingleNode("/job");
        String id = node.selectSingleNode("id").getText();
        String status = node.selectSingleNode("status").getText();
        jobInfo.setId(id);
        jobInfo.setStatus(status);
    } catch (Exception e) {
        String message = "Failed to get job status, Job Name:" + jobInfo.getJobName();
        LogUtil.fail(message, e);
        return false;
    }
    return true;
}