Example usage for java.util TreeSet isEmpty

List of usage examples for java.util TreeSet isEmpty

Introduction

In this page you can find the example usage for java.util TreeSet isEmpty.

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this set contains no elements.

Usage

From source file:org.zaproxy.zap.extension.ascanrulesBeta.HPP.java

/**
 * Main method of the class. It is executed for each page. Determined whether the page in
 * vulnerable to HPP or not./* ww w  .j a  va 2s. c  o m*/
 */
@Override
public void scan() {

    try {
        log.debug("Targeting " + getBaseMsg().getRequestHeader().getURI());

        // pages are not vulnerable if not proved otherwise
        List<String> vulnLinks = new ArrayList<String>();

        // We parse the HTML of the response and get all its parameters
        Source s = new Source(getBaseMsg().getResponseBody().toString());
        List<Element> inputTags = s.getAllElements(HTMLElementName.INPUT);
        TreeSet<HtmlParameter> tags = this.getParams(s, inputTags);

        /* If there are input fields, they can potentially be polluted */
        if (!inputTags.isEmpty()) {
            if (!tags.isEmpty()) {

                // We send the request with the injected payload in the parameters
                log.debug("Injecting payload...");
                HttpMessage newMsg = getNewMsg();
                newMsg.setGetParams(tags);
                try {
                    sendAndReceive(newMsg);
                } catch (IllegalStateException | UnknownHostException ex) {
                    if (log.isDebugEnabled())
                        log.debug("Caught " + ex.getClass().getName() + " " + ex.getMessage()
                                + " when accessing: " + newMsg.getRequestHeader().getURI().toString()
                                + "\n The target may have replied with a poorly formed redirect due to our input.");
                    return;
                }

                // We check all the links of the response to find our payload
                s = new Source(newMsg.getResponseBody().toString());
                List<Element> links = s.getAllElements(HTMLElementName.A);
                if (!links.isEmpty()) {
                    vulnLinks = this.findPayload(s, inputTags, vulnLinks);

                    // If vulnerable, generates the alert
                    if (!vulnLinks.isEmpty()) {
                        this.generateReport(vulnLinks);
                    }
                }
            }
        }
        if (vulnLinks.isEmpty()) {
            log.debug("Page not vulnerable to HPP attacks");
        }
    } catch (URIException e) {
        if (log.isDebugEnabled()) {
            log.debug("Failed to send HTTP message, cause: " + e.getMessage());
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:org.wso2.andes.server.slot.SlotManager.java

/**
 * Get a new slot from slotIDMap//from  w  ww. j  a  va 2  s. c o m
 *
 * @param queueName name of the queue
 * @return slot object
 */
private Slot getFreshSlot(String queueName) {
    Slot slotToBeAssigned = null;
    TreeSetLongWrapper wrapper = slotIDMap.get(queueName);
    TreeSet<Long> messageIDSet;
    if (wrapper != null) {
        messageIDSet = wrapper.getLongTreeSet();
        if (messageIDSet != null && !messageIDSet.isEmpty()) {
            slotToBeAssigned = new Slot();
            Long lastAssignedId = queueToLastAssignedIDMap.get(queueName);
            if (lastAssignedId != null) {
                slotToBeAssigned.setStartMessageId(lastAssignedId + 1);
            } else {
                slotToBeAssigned.setStartMessageId(0L);
            }
            slotToBeAssigned.setEndMessageId(messageIDSet.pollFirst());
            slotToBeAssigned.setStorageQueueName(queueName);
            wrapper.setLongTreeSet(messageIDSet);
            slotIDMap.set(queueName, wrapper);
            if (log.isDebugEnabled()) {
                log.debug(slotToBeAssigned.getEndMessageId() + " removed to slotIdMap. Current " + "values in "
                        + "map " + messageIDSet);
            }
            queueToLastAssignedIDMap.set(queueName, slotToBeAssigned.getEndMessageId());
        }
    }
    return slotToBeAssigned;

}

From source file:com.springsource.hq.plugin.tcserver.plugin.serverconfig.FileSettingsRepository.java

public void revertToPreviousConfiguration(ConfigResponse config) throws PluginException {
    TreeSet<String> backupSet = (TreeSet<String>) fileUtility
            .getLatestBackupDirectories(config.getValue("installpath"));
    if (!backupSet.isEmpty()) {
        try {/*from ww  w.  j av a  2s . co m*/
            fileUtility.revertToBackupFiles(config.getValue("installpath"), backupSet.last());
        } catch (FileUtilityException e) {
            throw new PluginException(e.getMessage());
        }
    } else {
        throw new PluginException("Unable to revert to backup files: No backup directories found in "
                + new File(config.getValue("installpath"), "backup").getAbsolutePath());
    }
}

From source file:org.openqa.selenium.TakesScreenshotTest.java

private void compareColors(Set<String> expectedColors, Set<String> actualColors) {
    TreeSet<String> c = new TreeSet<String>(expectedColors);
    c.removeAll(actualColors);//from   w  w w .  j a v a  2  s.com
    if (!c.isEmpty()) {
        fail("Unknown expected color is generated: " + c.toString() + ", \n" + " actual colors are: "
                + actualColors.toString());
    }

    if (actualColors.containsAll(expectedColors)) {
        // all is ok
    } else {
        actualColors.removeAll(expectedColors);
        fail("Unknown colors are presented at screenshot: " + actualColors.toString() + " \n"
                + " expected colors are excluded: " + expectedColors.toString());
    }
}

From source file:org.wso2.andes.server.slot.SlotManager.java

/**
 * Get a slot by giving the queue name. This method first lookup the free slot pool for slots
 * and if there are no slots in the free slot pool then return a newly created slot
 *
 * @param queueName name of the queue/*ww w .  j av a  2  s.c o m*/
 * @return Slot object
 */
public Slot getSlot(String queueName, String nodeId) {
    Slot slotToBeAssigned;
    Gson gson = new GsonBuilder().create();
    /**
     *First look in the unassigned slots pool for free slots. These slots are previously own by
     * other nodes
     */
    String lockKey = queueName + SlotManager.class;
    synchronized (lockKey.intern()) {
        TreeSetStringWrapper treeSetStringWrapper = unAssignedSlotMap.get(queueName);
        if (treeSetStringWrapper != null) {
            TreeSet<String> slotsFromUnassignedSlotMap = treeSetStringWrapper.getStringTreeSet();
            if (slotsFromUnassignedSlotMap != null && !slotsFromUnassignedSlotMap.isEmpty()) {
                slotToBeAssigned = gson.fromJson(slotsFromUnassignedSlotMap.pollFirst(), (Type) Slot.class);
                //update hazelcast map
                treeSetStringWrapper.setStringTreeSet(slotsFromUnassignedSlotMap);
                unAssignedSlotMap.set(queueName, treeSetStringWrapper);
                if (log.isDebugEnabled()) {
                    log.debug("Slot Manager - giving a slot from unAssignedSlotMap. Slot= " + slotToBeAssigned);
                }
            } else {
                slotToBeAssigned = getFreshSlot(queueName);
                if (log.isDebugEnabled()) {
                    log.debug("Slot Manager - giving a slot from fresh pool. Slot= " + slotToBeAssigned);
                }
            }
        } else {
            slotToBeAssigned = getFreshSlot(queueName);
            if (log.isDebugEnabled()) {
                log.debug("Slot Manager - giving a slot from fresh pool. Slot= " + slotToBeAssigned);
            }
        }
        if (null != slotToBeAssigned) {
            updateSlotAssignmentMap(queueName, slotToBeAssigned, nodeId);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Slot Manager - returns empty slot for the queue: " + queueName);
            }
        }
        return slotToBeAssigned;
    }

}

From source file:net.sourceforge.fenixedu.applicationTier.Servico.student.AddStudentToFinalDegreeWorkStudentGroup.java

private static Registration findSomeRegistration(final String username) {
    User user = User.findByUsername(username);
    if (user != null) {
        final Person person = user.getPerson();
        if (person != null) {
            final Student student = person.getStudent();
            final TreeSet<Registration> registrations = new TreeSet<Registration>(
                    new Comparator<Registration>() {

                        @Override
                        public int compare(final Registration r1, final Registration r2) {
                            final DegreeType dt1 = r1.getDegreeType();
                            final DegreeType dt2 = r2.getDegreeType();
                            return 0 - dt1.compareTo(dt2);
                        }/*from   w  w w  . ja  va2 s.  co m*/

                    }) {

                @Override
                public boolean add(final Registration r) {
                    final DegreeType degreeType = r.getDegreeType();
                    return isValidDegreeType(degreeType) && super.add(r);
                }

                private boolean isValidDegreeType(DegreeType degreeType) {
                    return degreeType == DegreeType.BOLONHA_MASTER_DEGREE
                            || degreeType == DegreeType.BOLONHA_INTEGRATED_MASTER_DEGREE
                            || degreeType == DegreeType.BOLONHA_DEGREE;
                }

            };
            registrations.addAll(student.getRegistrationsSet());
            return registrations.isEmpty() ? null : registrations.first();
        }
    }
    return null;
}

From source file:org.jamocha.dn.ConflictSet.java

/**
 * Deletes all revoked asserts and all retracts.
 *//*from   w ww  .  j a v  a  2 s  .c  o m*/
public synchronized void deleteRevokedEntries() {
    for (final Iterator<Entry<Integer, TreeSet<RuleAndToken>>> entryIterator = this.rulesAndTokensBySalience
            .entrySet().iterator(); entryIterator.hasNext();) {
        final Entry<Integer, TreeSet<RuleAndToken>> entry = entryIterator.next();
        final TreeSet<RuleAndToken> rulesAndTokens = entry.getValue();
        final Iterator<RuleAndToken> iterator = rulesAndTokens.iterator();
        while (iterator.hasNext()) {
            final RuleAndToken nodeAndToken = iterator.next();
            final AssertOrRetract<?> token = nodeAndToken.getToken();
            if (token.isRevokedOrMinus() || 0 == token.getMem().size()) {
                iterator.remove();
            }
        }
        if (rulesAndTokens.isEmpty()) {
            entryIterator.remove();
        }
    }
}

From source file:org.pdfsam.console.business.pdf.handlers.SplitCmdExecutor.java

/**
 * Execute the split of a pdf document when split type is S_BLEVEL
 * /*  ww  w . ja v  a 2s .  c om*/
 * @param inputCommand
 * @param bookmarksTable
 *            bookmarks table. It's populated only when splitting by bookmarks. If null or empty it's ignored
 * @throws Exception
 */
private void executeSplit(SplitParsedCommand inputCommand, Hashtable bookmarksTable) throws Exception {
    pdfReader = PdfUtility.readerFor(inputCommand.getInputFile());
    pdfReader.removeUnusedObjects();
    pdfReader.consolidateNamedDestinations();

    int n = pdfReader.getNumberOfPages();
    BookmarksProcessor bookmarkProcessor = new BookmarksProcessor(SimpleBookmark.getBookmark(pdfReader), n);
    int fileNum = 0;
    LOG.info("Found " + n + " pages in input pdf document.");

    Integer[] limits = inputCommand.getSplitPageNumbers();
    // limits list validation end clean
    TreeSet limitsList = validateSplitLimits(limits, n);
    if (limitsList.isEmpty()) {
        throw new SplitException(SplitException.ERR_NO_PAGE_LIMITS);
    }

    // HERE I'M SURE I'VE A LIMIT LIST WITH VALUES, I CAN START BOOKMARKS
    int currentPage;
    Document currentDocument = new Document(pdfReader.getPageSizeWithRotation(1));
    int relativeCurrentPage = 0;
    int endPage = n;
    int startPage = 1;
    PdfImportedPage importedPage;
    File tmpFile = null;
    File outFile = null;

    Iterator itr = limitsList.iterator();
    if (itr.hasNext()) {
        endPage = ((Integer) itr.next()).intValue();
    }
    for (currentPage = 1; currentPage <= n; currentPage++) {
        relativeCurrentPage++;
        // check if i've to read one more page or to open a new doc
        if (relativeCurrentPage == 1) {
            LOG.debug("Creating a new document.");
            fileNum++;
            tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile());
            String bookmark = null;
            if (bookmarksTable != null && bookmarksTable.size() > 0) {
                bookmark = (String) bookmarksTable.get(new Integer(currentPage));
            }
            FileNameRequest request = new FileNameRequest(currentPage, fileNum, bookmark);
            outFile = new File(inputCommand.getOutputFile(), prefixParser.generateFileName(request));
            startPage = currentPage;
            currentDocument = new Document(pdfReader.getPageSizeWithRotation(currentPage));

            pdfWriter = new PdfSmartCopy(currentDocument, new FileOutputStream(tmpFile));

            // set creator
            currentDocument.addCreator(ConsoleServicesFacade.CREATOR);

            setCompressionSettingOnWriter(inputCommand, pdfWriter);
            setPdfVersionSettingOnWriter(inputCommand, pdfWriter, Character.valueOf(pdfReader.getPdfVersion()));

            currentDocument.open();
        }

        importedPage = pdfWriter.getImportedPage(pdfReader, currentPage);
        pdfWriter.addPage(importedPage);

        // if it's time to close the document
        if (currentPage == endPage) {
            LOG.info("Temporary document " + tmpFile.getName() + " done, now adding bookmarks...");
            // manage bookmarks
            List bookmarks = bookmarkProcessor.processBookmarks(startPage, endPage);
            if (bookmarks != null) {
                pdfWriter.setOutlines(bookmarks);
            }
            relativeCurrentPage = 0;
            currentDocument.close();
            FileUtility.renameTemporaryFile(tmpFile, outFile, inputCommand.isOverwrite());
            LOG.debug("File " + outFile.getCanonicalPath() + " created.");
            endPage = (itr.hasNext()) ? ((Integer) itr.next()).intValue() : n;
        }
        setPercentageOfWorkDone((currentPage * WorkDoneDataModel.MAX_PERGENTAGE) / n);
    }
    pdfReader.close();
    LOG.info("Split " + inputCommand.getSplitType() + " done.");
}

From source file:org.accada.epcis.repository.query.Schedule.java

/**
 * Sets the field of a GregorianCalender to its minimum, which is defined as
 * the minimal possible value according to the calendar type possibly
 * superseded by the defined values in the schedule we have. Returns whether
 * the new value has been set and is valid.
 * /*  w  w w  . j  a  v  a  2 s .c  o m*/
 * @param cal
 *            Calendar to adjust.
 * @param field
 *            Field to adjust.
 * @return Returns whether the new value has been set and is valid.
 * @throws ImplementationException
 *             Almost any error.
 */
private boolean setFieldToMinimum(final GregorianCalendar cal, final int field)
        throws ImplementationExceptionResponse {
    int min;
    TreeSet<Integer> values = getValues(field);
    if (values.isEmpty()) {
        min = cal.getActualMinimum(field);
    } else {
        min = Math.max(values.first().intValue(), cal.getActualMinimum(field));
        if (min > cal.getActualMaximum(field)) {
            min = cal.getActualMaximum(field);
            if (!values.contains(Integer.valueOf(min)) || min < cal.getActualMinimum(field)
                    || min > cal.getActualMaximum(field)) {
                return false;
            }
        }
    }
    cal.set(field, min);
    return true;
}

From source file:org.accada.epcis.repository.query.Schedule.java

/**
 * Sets the specified field of the given callendar to the next scheduled
 * value. Returns whether the new value has been set and is valid.
 * /*from ww  w. j  a  va 2  s .c o m*/
 * @param cal
 *            Calendar to adjust.
 * @param field
 *            Field to adjust.
 * @return Returns whether the new value has been set and is valid.
 * @throws ImplementationException
 *             Almost any error.
 */
private boolean setToNextScheduledValue(final GregorianCalendar cal, final int field)
        throws ImplementationExceptionResponse {
    int next;
    TreeSet<Integer> vals = getValues(field);
    if (vals.isEmpty()) {
        next = cal.get(field) + 1;
    } else {
        try {
            // get next scheduled value which is bigger than current
            int incrValue = cal.get(field) + 1;
            next = vals.tailSet(new Integer(incrValue)).first().intValue();
        } catch (NoSuchElementException nse) {
            // there is no bigger scheduled value
            return false;
        }
    }
    if (next > cal.getActualMaximum(field) || next < cal.getActualMinimum(field)) {
        return false;
    }
    // all is well, set it to next
    cal.set(field, next);
    return true;
}