List of usage examples for java.util SortedSet last
E last();
From source file:edu.brown.utils.CollectionUtil.java
/** * Return the last item in an Iterable//from w w w . j a v a2 s. co m * * @param <T> * @param items * @return */ public static <T> T last(Iterable<T> items) { T last = null; if (items instanceof List<?>) { List<T> list = (List<T>) items; last = (list.isEmpty() ? null : list.get(list.size() - 1)); } else if (items instanceof SortedSet<?>) { SortedSet<T> set = (SortedSet<T>) items; last = (set.isEmpty() ? null : set.last()); } else { for (T t : items) { last = t; } } return (last); }
From source file:org.fao.geonet.component.csw.GetDomain.java
/** * Create value element for each item of the string array *//*ww w . j av a2 s. com*/ private static List<Element> createValuesElement(SortedSet<String> sortedValues, boolean isRange) { List<Element> valuesList = new ArrayList<Element>(); if (!isRange) { for (String value : sortedValues) { valuesList.add(new Element("Value", Csw.NAMESPACE_CSW).setText(value)); } } else { valuesList.add(new Element("MinValue", Csw.NAMESPACE_CSW).setText(sortedValues.first())); valuesList.add(new Element("MaxValue", Csw.NAMESPACE_CSW).setText(sortedValues.last())); } return valuesList; }
From source file:org.artifactory.maven.MavenModelUtils.java
public static Metadata buildReleasesMavenMetadata(String organization, String module, SortedSet<String> sortedVersions) { Metadata metadata = new Metadata(); metadata.setGroupId(organization);/*from www.j a v a2 s. com*/ metadata.setArtifactId(module); if (!sortedVersions.isEmpty()) { metadata.setVersion(sortedVersions.first()); Versioning versioning = new Versioning(); metadata.setVersioning(versioning); versioning.setVersions(Lists.newArrayList(sortedVersions)); versioning.setLastUpdatedTimestamp(new Date()); versioning.setLatest(sortedVersions.last()); versioning.setRelease(sortedVersions.last()); } return metadata; }
From source file:net.java.sip.communicator.impl.history.HistoryReaderImpl.java
/** * Used to limit the files if any starting or ending date exist * So only few files to be searched.//from www .ja v a2 s. co m * * @param filelist Iterator * @param startDate Date * @param endDate Date * @param reverseOrder reverse order of files * @return Vector */ static Vector<String> filterFilesByDate(Iterator<String> filelist, Date startDate, Date endDate, final boolean reverseOrder) { if (startDate == null && endDate == null) { // no filtering needed then just return the same list Vector<String> result = new Vector<String>(); while (filelist.hasNext()) { result.add(filelist.next()); } Collections.sort(result, new Comparator<String>() { public int compare(String o1, String o2) { if (reverseOrder) return o2.compareTo(o1); else return o1.compareTo(o2); } }); return result; } // first convert all files to long TreeSet<Long> files = new TreeSet<Long>(); while (filelist.hasNext()) { String filename = filelist.next(); files.add(Long.parseLong(filename.substring(0, filename.length() - 4))); } TreeSet<Long> resultAsLong = new TreeSet<Long>(); // Temporary fix of a NoSuchElementException if (files.size() == 0) { return new Vector<String>(); } Long startLong; Long endLong; if (startDate == null) startLong = Long.MIN_VALUE; else startLong = startDate.getTime(); if (endDate == null) endLong = Long.MAX_VALUE; else endLong = endDate.getTime(); // get all records inclusive the one before the startdate for (Long f : files) { if (startLong <= f && f <= endLong) { resultAsLong.add(f); } } // get the subset before the start date, to get its last element // if exists if (!files.isEmpty() && files.first() <= startLong) { SortedSet<Long> setBeforeTheInterval = files.subSet(files.first(), true, startLong, true); if (!setBeforeTheInterval.isEmpty()) resultAsLong.add(setBeforeTheInterval.last()); } Vector<String> result = new Vector<String>(); Iterator<Long> iter = resultAsLong.iterator(); while (iter.hasNext()) { Long item = iter.next(); result.add(item.toString() + ".xml"); } Collections.sort(result, new Comparator<String>() { public int compare(String o1, String o2) { if (reverseOrder) return o2.compareTo(o1); else return o1.compareTo(o2); } }); return result; }
From source file:com.ngdata.hbaseindexer.util.zookeeper.ZkLock.java
/** * Try to get a lock, waits until this succeeds. * * @param lockPath path in ZooKeeper below which the ephemeral lock nodes will be created. This path should * exist prior to calling this method. * * @return a string identifying this lock, needs to be supplied to {@link ZkLock#unlock}. *//*from w w w. j a v a 2 s. com*/ public static String lock(final ZooKeeperItf zk, final String lockPath) throws ZkLockException { if (zk.isCurrentThreadEventThread()) { throw new RuntimeException("ZkLock should not be used from within the ZooKeeper event thread."); } try { final long threadId = Thread.currentThread().getId(); // Quote from ZK lock recipe: // 1. Call create( ) with a pathname of "_locknode_/lock-" and the sequence and ephemeral flags set. zk.retryOperation(new ZooKeeperOperation<String>() { @Override public String execute() throws KeeperException, InterruptedException { return zk.create(lockPath + "/lock-" + threadId + "-", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); } }); while (true) { // Quote from ZK lock recipe: // 2. Call getChildren( ) on the lock node without setting the watch flag (this is important to avoid // the herd effect). List<ZkLockNode> children = parseChildren(zk.retryOperation(new ZooKeeperOperation<List<String>>() { @Override public List<String> execute() throws KeeperException, InterruptedException { return zk.getChildren(lockPath, null); } })); ZkLockNode myLockNode = null; String myLockName = null; String myLockPath = null; for (ZkLockNode child : children) { // if the child has the same thread id and session id as us, then it is our lock if (child.getThreadId() == threadId) { final String childPath = lockPath + "/" + child.getName(); Stat stat = zk.retryOperation(new ZooKeeperOperation<Stat>() { @Override public Stat execute() throws KeeperException, InterruptedException { return zk.exists(childPath, false); } }); if (stat != null && stat.getEphemeralOwner() == zk.getSessionId()) { if (myLockName != null) { // We have found another lock node which belongs to us. // This means that the lock creation above was executed twice, which can occur // in case of connection loss. Delete this node to avoid that otherwise it would // never be released. zk.retryOperation(new ZooKeeperOperation<Object>() { @Override public Object execute() throws KeeperException, InterruptedException { try { zk.delete(childPath, -1); } catch (KeeperException.NoNodeException e) { // ignore } return null; } }); } else { myLockNode = child; myLockName = child.getName(); myLockPath = childPath; } } } } if (myLockName == null) { throw new ZkLockException("Unexpected problem: did not find our lock node."); } // Idea to use SortedSets seen in a ZK recipe SortedSet<ZkLockNode> sortedChildren = new TreeSet<ZkLockNode>(children); SortedSet<ZkLockNode> lowerThanMe = sortedChildren.headSet(myLockNode); // Quote from ZK lock recipe: // 3. If the pathname created in step 1 has the lowest sequence number suffix, the client has the lock // and the client exits the protocol. if (lowerThanMe.isEmpty()) { // We have the lock return myLockPath; } // Quote from ZK lock recipe: // 4. The client calls exists( ) with the watch flag set on the path in the lock directory with the // next lowest sequence number. final String pathToWatch = lockPath + "/" + lowerThanMe.last().name; final Object condition = new Object(); final MyWatcher watcher = new MyWatcher(pathToWatch, condition); Stat stat = zk.retryOperation(new ZooKeeperOperation<Stat>() { @Override public Stat execute() throws KeeperException, InterruptedException { return zk.exists(pathToWatch, watcher); } }); if (stat == null) { // Quote from ZK lock recipe: // 5a. if exists( ) returns false, go to step 2. // This means (I think) that the lock was removed (explicitly or through session expiration) between // the moment we queried for the children and the moment we called exists() // If the node does not exist, the watcher will still be left, does not seem so tidy, hopefully // this situation does not occur often. // Let's log it to keep an eye on it LogFactory.getLog(ZkLock.class).warn("Next lower lock node does not exist: " + pathToWatch); } else { // Quote from ZK lock recipe: // 5b. Otherwise, wait for a notification for the pathname from the previous step before going // to step 2. synchronized (condition) { while (!watcher.gotNotified) { condition.wait(); } } } } } catch (Throwable t) { throw new ZkLockException("Error obtaining lock, path: " + lockPath, t); } }
From source file:org.ngrinder.perftest.repository.PerfTestRepositoryTest.java
@SuppressWarnings("serial") @Test/*from w w w .j a v a 2 s . co m*/ public void testPerfTestTag() { PerfTest entity = new PerfTest(); entity.setTestName("test1"); entity.setTags(new TreeSet<Tag>() { { add(new Tag("hello")); add(new Tag("world")); } }); entity = perfTestRepository.save(entity); PerfTest findOne = perfTestRepository.findOne(entity.getId()); SortedSet<Tag> tags = findOne.getTags(); assertThat(tags.first(), is(new Tag("hello"))); assertThat(tags.last(), is(new Tag("world"))); }
From source file:org.ngrinder.perftest.repository.PerfTestRepositoryTest.java
@SuppressWarnings("serial") @Test/*from www. j a v a 2 s. c o m*/ public void testPerfTestTag2() { final Tag hello = tagRepository.save(new Tag("hello")); final Tag world = tagRepository.save(new Tag("world")); final Tag world2 = tagRepository.save(new Tag("world2")); PerfTest entity = new PerfTest(); entity.setTestName("test1"); entity.setTags(new TreeSet<Tag>() { { add(hello); add(world); } }); entity = perfTestRepository.save(entity); SortedSet<Tag> tags2 = entity.getTags(); assertThat(tags2.first(), is(hello)); assertThat(tags2.last(), is(world)); PerfTest entity2 = new PerfTest(); entity2.setTestName("test1"); entity2.setTags(new TreeSet<Tag>() { { add(hello); add(world2); } }); perfTestRepository.save(entity2); assertThat(tagRepository.findAll().size(), is(3)); assertThat(perfTestRepository.findAll(PerfTestSpecification.hasTag("world")).size(), is(1)); assertThat(perfTestRepository.findAll(PerfTestSpecification.hasTag("hello")).size(), is(2)); assertThat(tagRepository.findAll().size(), is(3)); }
From source file:org.apache.hadoop.hbase.zookeeper.lock.ZKInterProcessReadLock.java
/** * {@inheritDoc}/*w w w . java 2s . com*/ */ @Override protected String getLockPath(String createdZNode, List<String> children) throws IOException { TreeSet<String> writeChildren = new TreeSet<String>(ZNodeComparator.COMPARATOR); for (String child : children) { if (isChildWriteLock(child)) { writeChildren.add(child); } } if (writeChildren.isEmpty()) { return null; } SortedSet<String> lowerChildren = writeChildren.headSet(createdZNode); if (lowerChildren.isEmpty()) { return null; } String pathToWatch = lowerChildren.last(); String nodeHoldingLock = lowerChildren.first(); String znode = ZKUtil.joinZNode(parentLockNode, nodeHoldingLock); handleLockMetadata(znode); return pathToWatch; }
From source file:com.joliciel.jochre.search.CoordinateStorageImpl.java
public List<Rectangle> getNearestRectangles(int offset) { int nearestOffset = -1; SortedSet<Integer> tailSet = wordOffsets.tailSet(offset); if (tailSet.size() > 0) { nearestOffset = tailSet.first(); } else {//from ww w. j a va2 s. c om SortedSet<Integer> headSet = wordOffsets.headSet(offset); nearestOffset = headSet.last(); } if (nearestOffset >= 0) { return this.getRectangles(nearestOffset); } return null; }
From source file:org.jahia.services.render.filter.cache.PrincipalAcl.java
private void fillValidRoles(String nodePath, Map<String, SortedSet<String>> roles, Set<String> validRoles) { for (Map.Entry<String, SortedSet<String>> entry : roles.entrySet()) { if (entry.getValue() == null) { // No path denied validRoles.add(entry.getKey()); } else if (entry.getValue().contains(nodePath)) { // Current node path is explicitely denied } else {//from w ww.ja v a2 s . c o m // Look for a possible denied parent path SortedSet<String> s = entry.getValue().headSet(nodePath); if (s.isEmpty() || !nodePath.startsWith(s.last())) { validRoles.add(entry.getKey()); } } } }