Example usage for java.util SortedSet add

List of usage examples for java.util SortedSet add

Introduction

In this page you can find the example usage for java.util SortedSet add.

Prototype

boolean add(E e);

Source Link

Document

Adds the specified element to this set if it is not already present (optional operation).

Usage

From source file:com.alibaba.otter.shared.arbitrate.impl.zookeeper.lock.DistributedLock.java

/**
 * lock??watch????lock?/*from ww w  . j  a  v a 2s .c  om*/
 */
private Boolean acquireLock(final BooleanMutex mutex) {
    try {
        do {
            if (id == null) {// ?lock
                long sessionId = getSessionId();
                String prefix = "x-" + sessionId + "-";
                // 
                String path = zookeeper.create(root + "/" + prefix, data, CreateMode.EPHEMERAL_SEQUENTIAL);
                int index = path.lastIndexOf("/");
                id = StringUtils.substring(path, index + 1);
                idName = new LockNode(id);
            }

            if (id != null) {
                List<String> names = zookeeper.getChildren(root);
                if (names.isEmpty()) {
                    logger.warn("lock lost with scene:empty list, id[] and node[]", id, idName);
                    unlock();// ??
                } else {
                    // ?
                    SortedSet<LockNode> sortedNames = new TreeSet<LockNode>();
                    for (String name : names) {
                        sortedNames.add(new LockNode(name));
                    }

                    if (sortedNames.contains(idName) == false) {
                        logger.warn("lock lost with scene:not contains ,id[] and node[]", id, idName);
                        unlock();// ??
                        continue;
                    }

                    // ?ownerId
                    ownerId = sortedNames.first().getName();
                    if (mutex != null && isOwner()) {
                        mutex.set(true);// ?
                        return true;
                    } else if (mutex == null) {
                        return isOwner();
                    }

                    SortedSet<LockNode> lessThanMe = sortedNames.headSet(idName);
                    if (!lessThanMe.isEmpty()) {
                        // ?
                        LockNode lastChildName = lessThanMe.last();
                        lastChildId = lastChildName.getName();
                        // watcher?
                        IZkConnection connection = zookeeper.getConnection();
                        // zkclient?zk?lock??watcher?zk?
                        ZooKeeper orginZk = ((ZooKeeperx) connection).getZookeeper();
                        Stat stat = orginZk.exists(root + "/" + lastChildId, new AsyncWatcher() {

                            public void asyncProcess(WatchedEvent event) {
                                if (!mutex.state()) { // ?????lock
                                    acquireLock(mutex);
                                } else {
                                    logger.warn("locked successful.");
                                }
                            }

                        });

                        if (stat == null) {
                            acquireLock(mutex);// ????watcher?
                        }
                    } else {
                        if (isOwner()) {
                            mutex.set(true);
                        } else {
                            logger.warn("lock lost with scene:no less ,id[] and node[]", id, idName);
                            unlock();// ?idownerId??
                        }
                    }
                }
            }
        } while (id == null);
    } catch (KeeperException e) {
        exception = e;
        if (mutex != null) {
            mutex.set(true);
        }
    } catch (InterruptedException e) {
        interrupt = e;
        if (mutex != null) {
            mutex.set(true);
        }
    } catch (Throwable e) {
        other = e;
        if (mutex != null) {
            mutex.set(true);
        }
    }

    if (isOwner() && mutex != null) {
        mutex.set(true);
    }
    return Boolean.FALSE;
}

From source file:io.yields.plugins.kpi.KPIReportProjectAction.java

public SortedSet<String> getTestNames() {
    SortedSet<String> testNames = new TreeSet<String>();
    for (KPIReport kpiReport : getKPIReports()) {
        for (ScoreResult scoreResult : kpiReport.getKpiScores()) {
            if (scoreResult.isOfficial()) {
                testNames.add(scoreResult.getName());
            }/*from ww  w  .  j ava 2  s  .  c  o m*/
        }
    }
    return testNames;
}

From source file:de.clusteval.serverclient.BackendClientCompleter.java

@SuppressWarnings("unused")
@Override//from www . j av  a  2  s.c o  m
public int complete(String buffer, int cursor, List<CharSequence> candidates) {
    SortedSet<String> strings = new TreeSet<String>();
    strings.add("performRun");
    strings.add("resumeRun");
    strings.add("terminateRun");
    strings.add("getRunStatus");
    strings.add("getOptRunStatus");
    strings.add("shutdown");
    strings.add("getRuns");
    strings.add("getQueue");
    strings.add("getRunResumes");
    strings.add("getDataSets");
    strings.add("getPrograms");
    strings.add("getRunResults");
    strings.add("generateDataSet");
    strings.add("randomizeDataConfig");
    strings.add("getActiveThreads");

    boolean exception = true;
    while (exception) {
        exception = false;
        try {
            if (buffer == null) {
                candidates.addAll(strings);
            } else if (buffer.equals("performRun ")) {
                this.updateRuns();
                candidates.addAll(runs);
                return buffer.length();
            } else if (buffer.equals("resumeRun ")) {
                this.updateRunResumes();
                candidates.addAll(runResumes);
                return buffer.length();
            } else if (buffer.equals("getRunResults ")) {
                this.updateRunResults();
                candidates.addAll(runResults);
                return buffer.length();
            } else if (buffer.equals("getRunResumes ")) {
                this.updateRunResumes();
                candidates.addAll(runResumes);
                return buffer.length();
            } else if (buffer.equals("terminateRun ") || buffer.equals("getRunStatus ")
                    || buffer.equals("getOptRunStatus ")) {
                this.updateRunningRuns();
                candidates.addAll(runningRuns);
                return buffer.length();
            } else if (buffer.startsWith("performRun ")) {
                updateRuns();
                int posSpace = buffer.indexOf(' ');
                for (String match : runs.tailSet(buffer.substring(posSpace + 1))) {
                    if (!match.startsWith(buffer.substring(posSpace + 1))) {
                        break;
                    }

                    candidates.add(match);
                }

                return posSpace + 1;
            } else if (buffer.startsWith("resumeRun ")) {
                this.updateRunResumes();
                int posSpace = buffer.indexOf(' ');
                for (String match : runResumes.tailSet(buffer.substring(posSpace + 1))) {
                    if (!match.startsWith(buffer.substring(posSpace + 1))) {
                        break;
                    }

                    candidates.add(match);
                }

                return posSpace + 1;
            } else if (buffer.startsWith("getRunResults ")) {
                this.updateRunResults();
                int posSpace = buffer.indexOf(' ');
                for (String match : runResults.tailSet(buffer.substring(posSpace + 1))) {
                    if (!match.startsWith(buffer.substring(posSpace + 1))) {
                        break;
                    }

                    candidates.add(match);
                }

                return posSpace + 1;
            } else if (buffer.startsWith("getRunResumes ")) {
                this.updateRunResumes();
                int posSpace = buffer.indexOf(' ');
                for (String match : runResumes.tailSet(buffer.substring(posSpace + 1))) {
                    if (!match.startsWith(buffer.substring(posSpace + 1))) {
                        break;
                    }

                    candidates.add(match);
                }

                return posSpace + 1;
            } else if (buffer.startsWith("generateDataSet ")) {
                this.updateDataSetGenerators();
                int posSpace = buffer.indexOf(' ');
                for (String match : dataSetGenerators.tailSet(buffer.substring(posSpace + 1))) {
                    if (!match.startsWith(buffer.substring(posSpace + 1))) {
                        break;
                    }

                    candidates.add(match);
                }

                return posSpace + 1;
            } else if (buffer.startsWith("randomizeDataConfig ")) {
                this.updateDataRandomizers();
                int posSpace = buffer.indexOf(' ');
                for (String match : dataRandomizers.tailSet(buffer.substring(posSpace + 1))) {
                    if (!match.startsWith(buffer.substring(posSpace + 1))) {
                        break;
                    }

                    candidates.add(match);
                }

                return posSpace + 1;
            } else if (buffer.startsWith("generateDataSet ")) {
                this.updateDataSetGenerators();
                candidates.addAll(dataSetGenerators);
                return buffer.length();
            } else if (buffer.startsWith("terminateRun ") || buffer.startsWith("getRunStatus ")) {
                this.updateRunningRuns();
                int posSpace = buffer.indexOf(' ');
                for (String match : runningRuns.tailSet(buffer.substring(posSpace + 1))) {
                    if (!match.startsWith(buffer.substring(posSpace + 1))) {
                        break;
                    }

                    candidates.add(match);
                }

                return posSpace + 1;
            } else {
                for (String match : strings.tailSet(buffer)) {
                    if (!match.startsWith(buffer)) {
                        break;
                    }

                    candidates.add(match);
                }
            }
        } catch (RemoteException e) {
            exception = true;
            try {
                // client = new EvalClient(new String[]{"-clientId",
                // clientId});
                client = new BackendClient(newArgs);
            } catch (ConnectException e1) {
                // e1.printStackTrace();
            } catch (ParseException e1) {
                // e1.printStackTrace();
            }
            // return -1;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }

        if (candidates.size() == 1) {
            candidates.set(0, candidates.get(0) + " ");
        }
    }

    return candidates.isEmpty() ? -1 : 0;
}

From source file:sample.portlet.MyBooksEditController.java

private SortedSet<Book> loadMyBooks(PortletRequest request) {
    SortedSet<Book> myBooks = new TreeSet<Book>();
    PortletPreferences prefs = request.getPreferences();
    String[] keys = prefs.getValues("myBooks", null);
    if (keys != null) {
        for (int i = 0; i < keys.length; i++) {
            try {
                Integer key = Integer.valueOf(keys[i]);
                Book book = bookService.getBook(key);
                if (book != null)
                    myBooks.add(book);
            } catch (NumberFormatException ex) {
            }//from  w w  w. j  a  v  a2  s . co  m
        }
    }
    return myBooks;
}

From source file:edu.northwestern.bioinformatics.studycalendar.domain.PlannedActivity.java

public SortedSet<String> getLabelsForRepetition(int rep) {
    SortedSet<String> labels = new TreeSet<String>(LabelComparator.INSTANCE);
    for (PlannedActivityLabel paLabel : getPlannedActivityLabels()) {
        if (paLabel.appliesToRepetition(rep)) {
            labels.add(paLabel.getLabel());
        }/*from  w w  w  . jav  a2s.  c om*/
    }
    return labels;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.internationalRelatOffice.internship.InternshipCandidacyDA.java

private SortedSet<InternshipCandidacyBean> filterCandidates(CandidateSearchBean search) {
    SortedSet<InternshipCandidacyBean> candidates = new TreeSet<InternshipCandidacyBean>();
    if (search.getSession() != null) {
        for (InternshipCandidacy candidacy : search.getSession().getInternshipCandidacySet()) {
            if (isIncluded(candidacy, search)) {
                candidates.add(new InternshipCandidacyBean(candidacy));
            }//from w w  w  . ja v a2  s .co m
        }
    }
    return candidates;
}

From source file:ch.puzzle.itc.mobiliar.business.generator.control.extracted.ResourceDependencyResolverServiceTest.java

@Test
public void testFindNearestRelease() {
    // given// w  w  w  .  jav a  2  s.  co m
    Calendar cal = new GregorianCalendar();

    cal.set(2001, Calendar.JANUARY, 1);
    ReleaseEntity release1 = createRelease(1, new Date(cal.getTimeInMillis()));

    cal.set(2013, Calendar.JANUARY, 1);
    ReleaseEntity release2 = createRelease(2, new Date(cal.getTimeInMillis()));

    cal.set(2013, Calendar.JANUARY, 23);
    ReleaseEntity release3 = createRelease(3, new Date(cal.getTimeInMillis()));

    cal.set(2013, Calendar.AUGUST, 8);
    ReleaseEntity release4 = createRelease(4, new Date(cal.getTimeInMillis()));

    cal.set(2013, Calendar.DECEMBER, 31);
    ReleaseEntity release5 = createRelease(5, new Date(cal.getTimeInMillis()));

    cal.set(2014, Calendar.NOVEMBER, 10);
    ReleaseEntity release6 = createRelease(6, new Date(cal.getTimeInMillis()));

    SortedSet<ReleaseEntity> releases = new TreeSet<ReleaseEntity>();

    // when only past release exists
    releases.add(release1);
    cal.set(2013, Calendar.JANUARY, 10);
    ReleaseEntity nearestRelease = service.findMostRelevantRelease(releases, new Date(cal.getTimeInMillis()));

    // then
    assertEquals(release1.getId(), nearestRelease.getId());

    // when there are multiple past releases
    releases.add(release2);
    releases.add(release3);
    cal.set(2013, Calendar.FEBRUARY, 10);
    nearestRelease = service.findMostRelevantRelease(releases, new Date(cal.getTimeInMillis()));

    // then
    assertEquals(release3.getId(), nearestRelease.getId());

    // when there is one future release
    releases.add(release4);
    cal.set(2013, Calendar.FEBRUARY, 10);
    nearestRelease = service.findMostRelevantRelease(releases, new Date(cal.getTimeInMillis()));

    // then
    assertEquals(release4.getId(), nearestRelease.getId());

    // when there are multiple future releases
    cal.set(2013, Calendar.AUGUST, 9);
    releases.add(release5);
    releases.add(release6);
    nearestRelease = service.findMostRelevantRelease(releases, new Date(cal.getTimeInMillis()));

    // then
    Assert.assertEquals(release5.getId(), nearestRelease.getId());
}

From source file:org.sakaiproject.component.app.postem.GradebookManagerImpl.java

public SortedSet getGradebooksByContext(final String context, final String sortBy, final boolean ascending) {
    if (context == null) {
        throw new IllegalArgumentException("Null Argument");
    } else {/*from   w ww  .ja  v  a  2s  .  c o m*/
        HibernateCallback hcb = new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {

                Criteria crit = session.createCriteria(GradebookImpl.class)
                        .add(Expression.eq(CONTEXT, context));

                List gbs = crit.list();

                Comparator gbComparator = determineComparator(sortBy, ascending);

                SortedSet gradebooks = new TreeSet(gbComparator);

                Iterator gbIterator = gbs.iterator();

                while (gbIterator.hasNext()) {
                    gradebooks.add((Gradebook) gbIterator.next());

                }

                return gradebooks;
            }
        };

        return (SortedSet) getHibernateTemplate().execute(hcb);
    }
}

From source file:org.sakaiproject.component.app.postem.GradebookManagerImpl.java

public SortedSet getReleasedGradebooksByContext(final String context, final String sortBy,
        final boolean ascending) {
    if (context == null) {
        throw new IllegalArgumentException("Null Argument");
    } else {/*ww  w  . j  a  v  a  2 s .  c  o m*/
        HibernateCallback hcb = new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {

                Criteria crit = session.createCriteria(GradebookImpl.class).add(Expression.eq(CONTEXT, context))
                        .add(Expression.eq(RELEASED, new Boolean(true)));

                List gbs = crit.list();

                Comparator gbComparator = determineComparator(sortBy, ascending);

                SortedSet gradebooks = new TreeSet(gbComparator);

                Iterator gbIterator = gbs.iterator();

                while (gbIterator.hasNext()) {
                    gradebooks.add((Gradebook) gbIterator.next());

                }

                return gradebooks;
            }
        };

        return (SortedSet) getHibernateTemplate().execute(hcb);
    }
}