Example usage for org.dom4j Node selectNodes

List of usage examples for org.dom4j Node selectNodes

Introduction

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

Prototype

List<Node> selectNodes(String xpathExpression);

Source Link

Document

selectNodes evaluates an XPath expression and returns the result as a List of Node instances or String instances depending on the XPath expression.

Usage

From source file:com.beetle.framework.web.cache.imp.CacheConfig.java

License:Apache License

public synchronized void readCacheURLs(InputStream xmlIs) {
    url_cacheAttr.clear();/*from   www .  j  a  v a  2  s. c o m*/
    if (xmlIs == null) {
        return;
    }
    SAXReader reader = new SAXReader();
    Document doc = null;
    try {
        doc = reader.read(xmlIs);
        Node node = doc.selectSingleNode(convertPath("mappings.caches"));
        if (node != null) {
            config.setDiskStorePath(node.valueOf("@diskStorePath"));
            config.setMaxElementsInMemory(toInt(node.valueOf("@maxElementsInMemory")));
            config.setMemoryStoreEvictionPolicy(node.valueOf("memoryStoreEvictionPolicy"));
            Iterator<?> it = node.selectNodes("cItem").iterator();
            while (it.hasNext()) {
                CacheAttr attr = new CacheAttr();
                Element e = (Element) it.next();
                attr.setUrl(e.valueOf("@name"));
                attr.setScope(e.valueOf("@scope"));
                attr.setTime(toInt(e.valueOf("@time")));
                url_cacheAttr.put(attr.getUrl(), attr);
            }
        }
    } catch (Exception de) {
        de.printStackTrace();
    } finally {
        if (doc != null) {
            doc.clearContent();
        }
        reader = null;
    }
}

From source file:com.chingo247.settlercraft.structure.plan.PlanMenuManager.java

License:Open Source License

/**
 * Loads the PlanMenu from the menu.xml. If menu.xml doesn't exist, the menu.xml from the jar
 * will be written to the FileSystem.// ww  w .j  av  a  2s.co  m
 *
 * @throws DocumentException When XML is invalid
 * @throws StructureAPIException When XML contains invalid data
 */
public final void init() throws DocumentException, StructureAPIException {
    File file = new File(PLUGIN_FOLDER, "menu.xml");
    if (!file.exists()) {
        InputStream input = PlanMenuManager.class.getClassLoader()
                .getResourceAsStream(RESOURCE_FOLDER + "/menu.xml");
        FileUtil.write(input, file);
    }

    Document d = new SAXReader().read(file);
    List<Node> rows = d.selectNodes("Menu/SlotRow");
    if (rows.size() > 2) {
        throw new StructureAPIException("Max rows is 2 for menu.xml");
    }

    planMenu = MenuAPI.createMenu(SettlerCraft.getInstance(), PLANSHOP_NAME, 54);
    boolean hasRow2 = false;

    for (int row = 0; row < rows.size(); row++) {
        Node rowNode = rows.get(row);
        List<Node> slotNodes = rowNode.selectNodes("Slot");
        // Slot #1 is reserved for all category
        if (row == 0 && slotNodes.size() > 8) {
            throw new StructureAPIException(" 'SlotRow#1' has max 8 slots to customize");
        } else if (slotNodes.size() > 9) {
            throw new StructureAPIException(" 'SlotRow#" + (row + 2) + "' has max 9 slots to customize");
        }
        int count = 0;

        for (Node categorySlotNode : slotNodes) {

            if (!categorySlotNode.hasContent()) {
                count++;
                continue;
            }

            Node mId = categorySlotNode.selectSingleNode("MaterialID");
            Node cat = categorySlotNode.selectSingleNode("Category");
            Node ali = categorySlotNode.selectSingleNode("Aliases");

            if (mId == null) {
                throw new StructureAPIException("Missing 'MaterialID' element in 'SlotRow#" + (row + 1)
                        + "' 'Slot#" + (count + 1) + "'");
            }
            if (cat == null) {
                throw new StructureAPIException(
                        "Missing 'Category' element in 'SlotRow#" + (row + 1) + "' 'Slot#" + (count + 1) + "'");
            }

            int id;
            try {
                id = Integer.parseInt(mId.getText());
            } catch (NumberFormatException nfe) {
                throw new StructureAPIException("Invalid number for 'MaterialID' element in 'SlotRow#"
                        + (row + 1) + "' 'Slot#" + (count + 1) + "'");
            }
            String category = cat.getText();
            if (category.isEmpty()) {
                Element catEl = (Element) cat;
                category = catEl.attributeValue("value");
            }
            if (category.trim().isEmpty()) {
                throw new StructureAPIException("Empty 'Category' element in 'SlotRow#" + (row + 1)
                        + "' and 'Slot#" + (count + 1) + "'");
            }
            category = category.replaceAll(" AND ", "&");

            String[] aliases;
            if (ali == null) {
                aliases = new String[0];
            } else {
                List<Node> aliasNodes = ali.selectNodes("Alias");
                aliases = new String[aliasNodes.size()];
                for (int j = 0; j < aliasNodes.size(); j++) {
                    String alias = aliasNodes.get(j).getText();

                    if (alias.isEmpty()) {
                        Element aliasEl = (Element) cat;
                        alias = aliasEl.attributeValue("value");
                    }
                    if (alias.trim().isEmpty()) {
                        throw new StructureAPIException("Empty 'Alias' element in  'SlotRow#" + (row + 1)
                                + "' and 'Slot#" + (count + 1) + "' and 'Alias#" + (j + 1) + "'");
                    }

                    aliases[j] = aliasNodes.get(j).getText();
                }
            }
            int slot = count;
            if (row == 0) {
                slot += 1; // slot 0 is reserved...
            } else {

                hasRow2 = true;
            }

            planMenu.putCategorySlot((row * 9) + slot, category, Material.getMaterial(id), aliases);

            count++;
        }
        // fill remaining
        if (count < 8 && row == 0) {
            for (int i = count; i < 8; i++) {
                planMenu.putLocked(i);
            }

        } else if (row > 0 && count < 9) {
            for (int i = count; i < 9; i++) {
                planMenu.putLocked((row * 9) + i);
            }
        }
    }

    if (hasRow2) {
        planMenu.putLocked(19, 20, 21, 22, 23, 24, 25);
        planMenu.putActionSlot(18, "Previous", Material.COAL_BLOCK);
        planMenu.putActionSlot(26, "Next", Material.COAL_BLOCK);
    } else {
        planMenu.putLocked(10, 11, 12, 13, 14, 15, 16);
        planMenu.putActionSlot(9, "Previous", Material.COAL_BLOCK);
        planMenu.putActionSlot(17, "Next", Material.COAL_BLOCK);
    }

}

From source file:com.chingo247.structureapi.menus.plans.StructurePlanMenuReader.java

License:Open Source License

public CategoryMenu read(File file) throws DocumentException, SettlerCraftException {
    Preconditions.checkArgument(file.exists(), "File '" + file.getAbsolutePath() + "' does not exist!");

    Document d = new SAXReader().read(file);

    CategoryMenu menu = new DefaultCategoryMenu("Buy & Build");

    List<Node> rows = d.selectNodes("Menu/SlotRow");
    if (rows.size() > 2) {
        throw new SettlerCraftException("Max rows is 2 for menu.xml");
    }/*w w  w  . j  a v a 2 s.  c  o m*/

    boolean hasRow2 = false;

    for (int row = 0; row < rows.size(); row++) {
        Node rowNode = rows.get(row);
        List<Node> slotNodes = rowNode.selectNodes("Slot");
        // Slot #1 is reserved for all category
        if (row == 0 && slotNodes.size() > 8) {
            throw new SettlerCraftException(" 'SlotRow#1' has max 8 slots to customize");
        } else if (slotNodes.size() > 9) {
            throw new SettlerCraftException(" 'SlotRow#" + (row + 2) + "' has max 9 slots to customize");
        }
        int count = 0;

        for (Node categorySlotNode : slotNodes) {

            if (!categorySlotNode.hasContent()) {
                count++;
                continue;
            }

            Node mId = categorySlotNode.selectSingleNode("MaterialID");
            Node cat = categorySlotNode.selectSingleNode("Category");
            //                Node ali = categorySlotNode.selectSingleNode("Aliases");

            if (mId == null) {
                throw new SettlerCraftException("Missing 'MaterialID' element in 'SlotRow#" + (row + 1)
                        + "' 'Slot#" + (count + 1) + "'");
            }
            if (cat == null) {
                throw new SettlerCraftException(
                        "Missing 'Category' element in 'SlotRow#" + (row + 1) + "' 'Slot#" + (count + 1) + "'");
            }

            int id;
            try {
                id = Integer.parseInt(mId.getText());
            } catch (NumberFormatException nfe) {
                throw new SettlerCraftException("Invalid number for 'MaterialID' element in 'SlotRow#"
                        + (row + 1) + "' 'Slot#" + (count + 1) + "'");
            }

            Node catNameNode = cat.selectSingleNode("Name");
            if (catNameNode == null) {
                throw new SettlerCraftException(
                        "Missing 'Name' element in 'SlotRow#" + (row + 1) + "' 'Slot#" + (count + 1) + "'");
            }

            String category = catNameNode.getText();
            if (category.isEmpty()) {
                Element catEl = (Element) cat;
                category = catEl.attributeValue("value");
            }
            if (category.trim().isEmpty()) {
                throw new SettlerCraftException("Empty 'Category' element in 'SlotRow#" + (row + 1)
                        + "' and 'Slot#" + (count + 1) + "'");
            }
            category = category.replaceAll(" AND ", "&");

            Node synonymsNode = cat.selectSingleNode("Synonyms");

            // Set aliases
            String[] synonyms;
            if (synonymsNode == null) {
                synonyms = new String[0];
            } else {
                List<Node> synonymNodes = synonymsNode.selectNodes("Synonym");
                synonyms = new String[synonymNodes.size()];
                for (int j = 0; j < synonymNodes.size(); j++) {
                    String synonym = synonymNodes.get(j).getText();

                    if (synonym.isEmpty()) {
                        Element synoEl = (Element) cat;
                        synonym = synoEl.attributeValue("value");
                    }
                    if (synonym.trim().isEmpty()) {
                        throw new SettlerCraftException("Empty 'Synonym' element in  'SlotRow#" + (row + 1)
                                + "' and 'Slot#" + (count + 1) + "' and 'Synonym#" + (j + 1) + "'");
                    }

                    synonyms[j] = synonymNodes.get(j).getText();
                }
            }
            int slot = count;
            if (row == 0) {
                slot += 1; // slot 0 is reserved...
            } else {

                hasRow2 = true;
            }

            CategorySlot categorySlot = SlotFactory.getInstance().createCategorySlot(category, id);
            categorySlot.addSynonyms(synonyms);
            menu.setCategorySlot((row * 9) + slot, categorySlot);

            count++;
        }
        // fill remaining
        if (count < 8 && row == 0) {
            for (int i = count; i < 8; i++) {
                menu.setLocked(i);
            }

        } else if (row > 0 && count < 9) {
            for (int i = count; i < 9; i++) {
                menu.setLocked((row * 9) + i);
            }
        }
    }

    if (hasRow2) {
        menu.setLocked(19, 20, 21, 22, 23, 24, 25);
        menu.setActionSlot(18, "Previous", 173); // block of coal
        menu.setActionSlot(26, "Next", 173);
    } else {
        menu.setLocked(10, 11, 12, 13, 14, 15, 16);
        menu.setActionSlot(9, "Previous", 173);
        menu.setActionSlot(17, "Next", 173);
    }
    return menu;
}

From source file:com.chingo247.structureapi.plan.holograms.StructureHologramLoader.java

License:Open Source License

@Override
public List<StructureHologram> load(Element hologramsElement) throws StructureDataException {
    if (hologramsElement == null) {
        throw new AssertionError("Overviews element was null");
    }//from   ww  w.j av  a2s .com

    if (!hologramsElement.getName().equals(Elements.STRUCTURE_HOLOGRAMS)) {
        throw new AssertionError("Expected '" + Elements.STRUCTURE_HOLOGRAMS + "' element, but got '"
                + hologramsElement.getName() + "'");
    }

    List<StructureHologram> holograms = new ArrayList<>();
    List<Node> hologramNodes = hologramsElement.selectNodes(Elements.STRUCTURE_HOLOGRAM);
    int count = 0;

    for (Node hologramNode : hologramNodes) {

        Node xNode = hologramNode.selectSingleNode(Elements.X);
        Node yNode = hologramNode.selectSingleNode(Elements.Y);
        Node zNode = hologramNode.selectSingleNode(Elements.Z);
        if (xNode == null) {
            throw new StructureDataException("Missing 'X' node for 'StructureOverview#" + count + "'");
        }
        if (yNode == null) {
            throw new StructureDataException("Missing 'Y' node for 'StructureOverview#" + count + "'");
        }
        if (zNode == null) {
            throw new StructureDataException("Missing 'Z' node for 'StructureOverview#" + count + "'");
        }

        try {
            int x = Integer.parseInt(xNode.getText());
            int y = Integer.parseInt(yNode.getText());
            int z = Integer.parseInt(zNode.getText());

            List<Node> lines = hologramNode.selectNodes("Lines/Line");
            String[] tArray = new String[lines.size()];
            for (int i = 0; i < tArray.length; i++) {
                tArray[i] = (lines.get(i)).getText();
            }
            holograms.add(new StructureHologram(x, y, z, tArray));

        } catch (NumberFormatException nfe) {
            throw new StructureDataException(
                    "Values for (x,y,z) are not of type number in 'StructureOverview#" + count + "'");
        }
        count++;

    }

    return holograms;
}

From source file:com.chingo247.structureapi.plan.holograms.StructureHologramValidator.java

License:Open Source License

@Override
public void validate(Element e) throws StructureDataException {
    List<Node> nodes = e.selectNodes(Nodes.HOLOGRAM_NODE);

    if (nodes != null && !nodes.isEmpty()) {
        int count = 0;
        for (Node n : nodes) {
            Node xNode = n.selectSingleNode(Elements.X);
            Node yNode = n.selectSingleNode(Elements.Y);
            Node zNode = n.selectSingleNode(Elements.Z);

            if (xNode == null) {
                throw new StructureDataException("Missing 'X' node for 'Hologram#" + count + "'");
            }//from  www  .  j a  v  a2s .  com

            if (yNode == null) {
                throw new StructureDataException("Missing 'Y' node for 'Hologram#" + count + "'");
            }

            if (zNode == null) {
                throw new StructureDataException("Missing 'Z' node for 'Hologram#" + count + "'");
            }
            try {
                Integer.parseInt(xNode.getText());
            } catch (NumberFormatException nfe) {
                throw new StructureDataException("Invalid X value should 'Hologram#" + count + "'");
            }

            try {
                Integer.parseInt(yNode.getText());
            } catch (NumberFormatException nfe) {
                throw new StructureDataException("Invalid Y value for 'Hologram#" + count + "'");
            }

            try {
                Integer.parseInt(zNode.getText());
            } catch (NumberFormatException nfe) {
                throw new StructureDataException("Invalid Z value for 'Hologram#" + count + "'");
            }

            Node linesNode = n.selectSingleNode("Lines");
            if (linesNode == null) {
                throw new StructureDataException("Missing 'Lines' node for 'Hologram#" + count + "'");
            }

            List<Node> lineNodes = n.selectNodes("Lines/Line");
            if (lineNodes == null || lineNodes.isEmpty()) {
                throw new StructureDataException("Missing 'Line' nodes for 'Hologram#" + count + "'");
            }

            count++;
        }
    }
}

From source file:com.dotmarketing.viewtools.XmlTool.java

License:Apache License

/**
 * Performs an XPath selection on the current set of {@link Node}s held by this instance and returns a new
 * {@link XmlTool} instance that wraps those results. If the specified value is null or this instance does not
 * currently hold any nodes, then this will return {@code null}. If the specified value, when converted to a
 * string, does not contain a '/' character, then it has "//" prepended to it. This means that a call to
 * {@code $xml.find("a")} is equivalent to calling {@code $xml.find("//a")}. The full range of XPath selectors is
 * supported here.//  w ww. ja va 2  s .co m
 */
public XmlTool find(String xpath) {
    if (xpath == null || xpath.length() == 0) {
        return null;
    }
    if (xpath.indexOf('/') < 0) {
        xpath = "//" + xpath;
    }
    List<Node> found = new ArrayList<Node>();
    for (Node n : nodes) {
        found.addAll((List<Node>) n.selectNodes(xpath));
    }
    if (found.isEmpty()) {
        return null;
    }
    return new XmlTool(found);
}

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

License:Apache License

private List<ExecutionDetail> parseExecutionsResult(final WebserviceResponse response) {
    final Document resultDoc = response.getResultDoc();

    final Node node = resultDoc.selectSingleNode("/result/executions");
    final List items = node.selectNodes("execution");
    final ArrayList<ExecutionDetail> list = new ArrayList<ExecutionDetail>();
    if (null != items && items.size() > 0) {
        for (final Object o : items) {
            final Node node1 = (Node) o;
            ExecutionDetailImpl detail = new ExecutionDetailImpl();
            String url = node1.selectSingleNode("@href").getStringValue();
            url = makeAbsoluteURL(url);/*ww  w  .  j a  v a  2s  .  c  o m*/
            detail.setId(stringNodeValue(node1, "@id", null));
            try {
                detail.setStatus(
                        ExecutionState.valueOf(stringNodeValue(node1, "@status", "").replaceAll("-", "_")));
            } catch (IllegalArgumentException e) {
            }
            detail.setUrl(url);
            detail.setUser(stringNodeValue(node1, "user", null));
            detail.setAbortedBy(stringNodeValue(node1, "abortedBy", null));
            detail.setDescription(stringNodeValue(node1, "description", null));
            detail.setArgString(stringNodeValue(node1, "argString", null));
            detail.setDateStarted(w3cDateNodeValue(node1, "date-started", null));
            detail.setDateCompleted(w3cDateNodeValue(node1, "date-started", null));
            final Node jobNode = node1.selectSingleNode("job");
            if (null != jobNode) {
                final String jobId = stringNodeValue(jobNode, "@id", null);
                StoredJobExecutionImpl job = new StoredJobExecutionImpl(jobId,
                        stringNodeValue(jobNode, "name", null), createJobURL(jobId),
                        stringNodeValue(jobNode, "group", null), stringNodeValue(jobNode, "description", null),
                        stringNodeValue(jobNode, "project", null),
                        longNodeValue(jobNode, "@averageDuration", -1));
                detail.setExecutionJob(job);
            }
            list.add(detail);
        }
    }
    return list;
}

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  ww .  j  a  v  a2 s. c  om
            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 2s .  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 ww.  ja  v a 2s  .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;
}