/**
  * Returns the description of the {@code number}. This method distinguishes the case of an invalid
  * prefix and a prefix for which the name is not available in the current language. If the
  * description is not available in the current language an empty string is returned. If no
  * description was found for the provided number, null is returned.
  *
  * @param number the phone number to look up
  * @return the description of the number
  */
 String lookup(long number) {
   int numOfEntries = phonePrefixMapStorage.getNumOfEntries();
   if (numOfEntries == 0) {
     return null;
   }
   long phonePrefix = number;
   int currentIndex = numOfEntries - 1;
   SortedSet<Integer> currentSetOfLengths = phonePrefixMapStorage.getPossibleLengths();
   while (currentSetOfLengths.size() > 0) {
     Integer possibleLength = currentSetOfLengths.last();
     String phonePrefixStr = String.valueOf(phonePrefix);
     if (phonePrefixStr.length() > possibleLength) {
       phonePrefix = Long.parseLong(phonePrefixStr.substring(0, possibleLength));
     }
     currentIndex = binarySearch(0, currentIndex, phonePrefix);
     if (currentIndex < 0) {
       return null;
     }
     int currentPrefix = phonePrefixMapStorage.getPrefix(currentIndex);
     if (phonePrefix == currentPrefix) {
       return phonePrefixMapStorage.getDescription(currentIndex);
     }
     currentSetOfLengths = currentSetOfLengths.headSet(possibleLength);
   }
   return null;
 }
示例#2
0
  public void test_headSetLjava_lang_Object() {
    // Test for method java.util.SortedSet
    // java.util.TreeSet.headSet(java.lang.Object)
    Set s = ts.headSet(new Integer(100));
    assertEquals("Returned set of incorrect size", 100, s.size());
    for (int i = 0; i < 100; i++) assertTrue("Returned incorrect set", s.contains(objArray[i]));

    SortedSet sort = ts.headSet(new Integer(100));
    try {
      sort.headSet(new Integer(101));
      fail("IllegalArgumentException expected");
    } catch (IllegalArgumentException e) {
      // expected
    }

    try {
      ts.headSet(this);
      fail("ClassCastException expected");
    } catch (ClassCastException e) {
      // expected
    }

    try {
      ts.headSet(null);
      fail("NullPointerException expected");
    } catch (NullPointerException e) {
      // expected
    }
  }
示例#3
0
 /** @tests java.util.TreeSet#headSet(java.lang.Object) */
 public void test_headSetLjava_lang_Object() {
   // Test for method java.util.SortedSet
   // java.util.TreeSet.headSet(java.lang.Object)
   Set s = ts.headSet(new Integer(100));
   assertEquals("Returned set of incorrect size", 100, s.size());
   for (int i = 0; i < 100; i++) assertTrue("Returned incorrect set", s.contains(objArray[i]));
 }
 /**
  * {@inheritDoc}
  *
  * @see java.util.SortedSet#headSet(java.lang.Object)
  */
 public SortedSet<E> headSet(final E toElement) {
   lockRead();
   try {
     return m_set.headSet(toElement);
   } finally {
     unlockRead();
   }
 }
示例#5
0
 /**
  * the command that is run and retried for actually obtaining the lock
  *
  * @return if the command was successful or not
  */
 public boolean execute() throws KeeperException, InterruptedException {
   do {
     if (id == null) {
       long sessionId = zookeeper.getSessionId();
       String prefix = "x-" + sessionId + "-";
       // lets try look up the current ID if we failed
       // in the middle of creating the znode
       findPrefixInChildren(prefix, zookeeper, dir);
       idName = new ZNodeName(id);
     }
     if (id != null) {
       List<String> names = zookeeper.getChildren(dir, false);
       if (names.isEmpty()) {
         LOG.warn(
             "No children in: "
                 + dir
                 + " when we've just "
                 + "created one! Lets recreate it...");
         // lets force the recreation of the id
         id = null;
       } else {
         // lets sort them explicitly (though they do seem to come back in order ususally :)
         SortedSet<ZNodeName> sortedNames = new TreeSet<ZNodeName>();
         for (String name : names) {
           sortedNames.add(new ZNodeName(dir + "/" + name));
         }
         ownerId = sortedNames.first().getName();
         SortedSet<ZNodeName> lessThanMe = sortedNames.headSet(idName);
         if (!lessThanMe.isEmpty()) { // 存在比当前节点小的节点,在这些节点中监听最大的节点,目的是避免羊群效应
           ZNodeName lastChildName = lessThanMe.last();
           lastChildId = lastChildName.getName();
           if (LOG.isDebugEnabled()) {
             LOG.debug("watching less than me node: " + lastChildId);
           }
           Stat stat = zookeeper.exists(lastChildId, new LockWatcher());
           if (stat != null) {
             return Boolean.FALSE;
           } else {
             LOG.warn(
                 "Could not find the" + " stats for less than me: " + lastChildName.getName());
           }
         } else { // 如果不存在比当前节点小的节点,那么获得锁,调用callback回调执行
           if (isOwner()) { // 进一步根据id和ownerid判断是否获得锁
             if (callback != null) {
               callback.lockAcquired();
             }
             return Boolean.TRUE;
           }
         }
       }
     }
   } while (id == null);
   return Boolean.FALSE;
 }
示例#6
0
  // assumes o is in satisfiers \ exceptions
  private int getIndexInPOPApp(ObjectSet satisfiers, Set exceptions, Object o) {
    SortedSet exceptionIndices = new TreeSet();
    for (Iterator iter = exceptions.iterator(); iter.hasNext(); ) {
      Object exception = iter.next();
      exceptionIndices.add(new Integer(satisfiers.indexOf(exception)));
    }

    int origIndex = satisfiers.indexOf(o);
    int numExceptionsBefore = exceptionIndices.headSet(new Integer(origIndex)).size();
    return (origIndex - numExceptionsBefore);
  }
  /*
   * Get the Pre Processed Content Specification for a ID and Revision
   */
  public RESTTopicV1 getPreContentSpecById(final Integer id, final Integer revision) {
    final RESTTopicV1 cs = getContentSpecById(id, revision);
    final List<Object[]> specRevisions = getContentSpecRevisionsById(id);

    if (specRevisions == null) return null;

    // Create a sorted set of revision ids that are less the the current
    // revision
    final SortedSet<Integer> sortedSpecRevisions = new TreeSet<Integer>();
    for (final Object[] specRev : specRevisions) {
      if ((Integer) specRev[0] <= cs.getRevision()) {
        sortedSpecRevisions.add((Integer) specRev[0]);
      }
    }

    if (sortedSpecRevisions.size() == 0) return null;

    // Find the Pre Content Spec from the revisions
    RESTTopicV1 preContentSpec = null;
    Integer specRev = sortedSpecRevisions.last();
    while (specRev != null) {
      final RESTTopicV1 contentSpecRev = getContentSpecById(id, specRev);
      if (ComponentBaseRESTEntityWithPropertiesV1
                  .<RESTTopicV1, RESTTopicCollectionV1>returnProperty(
                      contentSpecRev, CSConstants.CSP_TYPE_PROPERTY_TAG_ID)
              != null
          && ComponentBaseRESTEntityWithPropertiesV1.returnProperty(
                  contentSpecRev, CSConstants.CSP_TYPE_PROPERTY_TAG_ID)
              .getValue()
              .equals(CSConstants.CSP_PRE_PROCESSED_STRING)) {
        preContentSpec = contentSpecRev;
        break;
      }
      specRev =
          sortedSpecRevisions.headSet(specRev).isEmpty()
              ? null
              : sortedSpecRevisions.headSet(specRev).last();
    }
    return preContentSpec;
  }
 private SortedSet<E> getSubSet(final SortedSet<E> set) {
   final E[] elements = AbstractSortedSetTest.this.getFullElements();
   switch (m_Type) {
     case TYPE_SUBSET:
       return set.subSet(elements[m_LowBound], elements[m_HighBound]);
     case TYPE_HEADSET:
       return set.headSet(elements[m_HighBound]);
     case TYPE_TAILSET:
       return set.tailSet(elements[m_LowBound]);
     default:
       return null;
   }
 }
示例#9
0
    @Override
    public int previousTab(int position) {
      int tabStop = 0;

      // Search for the first tab stop before the given position...
      SortedSet<Integer> headSet = myTabStops.headSet(Integer.valueOf(position));
      if (!headSet.isEmpty()) {
        tabStop = headSet.last();
      }

      // Don't go beyond the start of the line...
      return Math.max(0, tabStop);
    }
示例#10
0
 // The marker has the last time stamp (milli since 1970) and hence is the last transaction for any
 // days
 public SortedSet<TransactionElement> headTransactionsTo(
     Date currentStartDate, Date currentEndDate) {
   if (currentStartDate == null || currentStartDate.equals(DateFactory.dateAtZero())) {
     return transactions.headSet(
         new TransactionElement(null, null, null, currentEndDate, null, null, null));
   } else {
     Calendar currentDateCal = Calendar.getInstance();
     currentDateCal.setTime(currentStartDate);
     currentDateCal.add(Calendar.DAY_OF_YEAR, -1);
     return transactions.subSet(
         new TransactionElement(null, null, null, currentDateCal.getTime(), null, null, null),
         new TransactionElement(null, null, null, currentEndDate, null, null, null));
   }
 }
  public void testElementSetSortedSetMethods() {
    TreeMultiset<String> ms = TreeMultiset.create();
    ms.add("c", 1);
    ms.add("a", 3);
    ms.add("b", 2);
    SortedSet<String> elementSet = ms.elementSet();

    assertEquals("a", elementSet.first());
    assertEquals("c", elementSet.last());
    assertEquals(Ordering.natural(), elementSet.comparator());

    ASSERT.that(elementSet.headSet("b")).has().exactly("a").inOrder();
    ASSERT.that(elementSet.tailSet("b")).has().exactly("b", "c").inOrder();
    ASSERT.that(elementSet.subSet("a", "c")).has().exactly("a", "b").inOrder();
  }
示例#12
0
 private int getAppointmentNumber(AppointmentBlock appointmentBlock) {
   final long blockStart = appointmentBlock.getEnd();
   final Date end = new Date(blockStart);
   final Appointment appointment = appointmentBlock.getAppointment();
   final Reservation reservation = appointment.getReservation();
   final Date start = reservation.getFirstDate();
   SortedSet<AppointmentBlock> blocks = new TreeSet<AppointmentBlock>();
   for (Appointment app : reservation.getAppointments()) {
     app.createBlocks(start, end, blocks);
   }
   final SortedSet<AppointmentBlock> headSet = blocks.headSet(appointmentBlock);
   final int size = headSet.size();
   //                final long appoimtmentStart = reservation.getFirstDate().getTime();
   //                if (appoimtmentStart ==  start)
   //                {
   //                    return 1;
   //                }
   return size + 1;
 }
示例#13
0
 public static void main(String[] args) {
   SortedSet<String> sortedSet = new TreeSet<String>();
   Collections.addAll(sortedSet, "one two three four five six seven eight".split(" "));
   print(sortedSet);
   String low = sortedSet.first();
   String high = sortedSet.last();
   print(low);
   print(high);
   Iterator<String> it = sortedSet.iterator();
   for (int i = 0; i <= 6; i++) {
     if (i == 3) low = it.next();
     if (i == 6) high = it.next();
     else it.next();
   }
   print(low);
   print(high);
   print(sortedSet.subSet(low, high));
   print(sortedSet.headSet(high));
   print(sortedSet.tailSet(low));
 }
  public AttributeSet[] getTreeChildren() {
    int attrAmount = attributes.size();
    if (attrAmount <= 1) {
      return new AttributeSet[0];
    }

    final AttributeSet[] children = new AttributeSet[attrAmount];
    Iterator<Attribute> it = attributes.iterator();
    Attribute attr = it.next();
    for (int i = 0; ; ++i) {
      SortedSet<Attribute> childAttr = attributes.headSet(attr);
      if (it.hasNext()) {
        attr = it.next();
        childAttr = new TreeSet<>(childAttr);
        childAttr.addAll(attributes.tailSet(attr));
        children[i] = AttributeSet.getSet(childAttr);
      } else {
        children[i] = AttributeSet.getSet(childAttr);
        return children;
      }
    }
  }
示例#15
0
  private <T> SortedSet<T> getElementsByRange(SortedSet<T> total, int beginIndex, int endIndex) {
    // Redis command: ZRANGE
    T beginElement = getElementByIndex(total, beginIndex);
    T endElement = getElementByIndex(total, endIndex);

    SortedSet<T> newSet = new ConcurrentSkipListSet<T>();
    SortedSet<T> subSet = null;
    if (null == beginElement && null == endElement) {
      return null;
    } else if (null == beginElement) {
      subSet = total.headSet(endElement);
      newSet.add(endElement);
    } else if (null == endElement) {
      subSet = total.tailSet(beginElement);
    } else {
      subSet = total.subSet(beginElement, endElement);
      newSet.add(endElement);
    }
    if (null != subSet) newSet.addAll(subSet);

    return newSet;
  }
示例#16
0
 /** Gets the sorted set of regions less than r. */
 public SortedSet<R> getHeadSet(R r) {
   SortedSet<R> oddRegions = _regions.get(r.getDocument());
   if (oddRegions == null || oddRegions.isEmpty()) return emptySet();
   return oddRegions.headSet(r);
 }
 @Override
 public SortedSet<E> headSet(E toElement) {
   return constrainedSortedSet(delegate.headSet(toElement), constraint);
 }
示例#18
0
 /**
  * Checks if a peeraddress is within the replication range. This means that the peer should also
  * receive a replica.
  *
  * @param locationKey The locationKey
  * @param peerAddress The peeraddress to check if its within the replication range
  * @param replicationFactor The replication factor
  * @return True if the peer is within replication range, otherwise false.
  */
 private boolean isInReplicationRange(
     final Number160 locationKey, final PeerAddress peerAddress, final int replicationFactor) {
   SortedSet<PeerAddress> tmp = peerMap.closePeers(locationKey, replicationFactor);
   return tmp.headSet(peerAddress).size() < replicationFactor;
 }
示例#19
0
  private <T> void verify(SortedSet<T> immutableSet, SortedSet<T> mutableSet, T value1, T value2) {
    try {
      immutableSet.add(value1);
      Assert.fail();
    } catch (UnsupportedOperationException e) {
    }

    try {
      immutableSet.addAll(java.util.Collections.singleton(value1));
      Assert.fail();
    } catch (UnsupportedOperationException e) {
    }

    try {
      immutableSet.clear();

      Assert.assertTrue(mutableSet.isEmpty());
    } catch (UnsupportedOperationException e) {
      Assert.assertFalse(mutableSet.isEmpty());
    }

    Assert.assertEquals(immutableSet.contains(value1), mutableSet.contains(value1));
    Assert.assertEquals(immutableSet.contains(value2), mutableSet.contains(value2));

    Assert.assertEquals(
        immutableSet.containsAll(java.util.Collections.emptySet()),
        mutableSet.containsAll(java.util.Collections.emptySet()));
    Assert.assertEquals(
        immutableSet.containsAll(java.util.Collections.singleton(0)),
        mutableSet.containsAll(java.util.Collections.singleton(0)));
    Assert.assertEquals(
        immutableSet.containsAll(java.util.Collections.singleton(1)),
        mutableSet.containsAll(java.util.Collections.singleton(1)));

    Iterator<T> iterator = immutableSet.iterator();

    if (!mutableSet.isEmpty()) {
      Assert.assertTrue(iterator.hasNext());

      Assert.assertEquals(iterator.next(), mutableSet.iterator().next());
    }

    Assert.assertFalse(iterator.hasNext());

    try {
      iterator.next();
      Assert.fail();
    } catch (NoSuchElementException e) {
    }

    Assert.assertEquals(immutableSet.isEmpty(), mutableSet.isEmpty());

    try {
      immutableSet.remove(value1);
    } catch (UnsupportedOperationException e) {
    }

    try {
      immutableSet.removeAll(java.util.Collections.singleton(value1));
    } catch (UnsupportedOperationException e) {
    }

    try {
      immutableSet.retainAll(java.util.Collections.singleton(value1));
    } catch (UnsupportedOperationException e) {
    }

    Assert.assertEquals(immutableSet.size(), mutableSet.size());

    Assert.assertArrayEquals(immutableSet.toArray(), mutableSet.toArray());

    Assert.assertSame(immutableSet.comparator(), mutableSet.comparator());

    if (!mutableSet.isEmpty()) {
      Assert.assertEquals(immutableSet.first(), mutableSet.first());
      Assert.assertEquals(immutableSet.last(), mutableSet.last());
    } else {
      try {
        immutableSet.first();
        Assert.fail();
      } catch (NoSuchElementException e) {
      }

      try {
        immutableSet.last();
        Assert.fail();
      } catch (NoSuchElementException e) {
      }
    }

    Assert.assertEquals(immutableSet.headSet(value1), mutableSet.headSet(value1));
    Assert.assertEquals(immutableSet.headSet(value2), mutableSet.headSet(value2));

    Assert.assertEquals(immutableSet.subSet(value1, value2), mutableSet.subSet(value1, value2));

    Assert.assertEquals(immutableSet.tailSet(value1), mutableSet.tailSet(value1));
    Assert.assertEquals(immutableSet.tailSet(value2), mutableSet.tailSet(value2));
  }
示例#20
0
 private <T> boolean removePrecedingElements(SortedSet<T> set, T element) {
   set.headSet(element).clear();
   set.remove(element);
   return true;
 }
  public Collection<Element> trim(Element element, Collection<Point> cutPoints, Point click)
      throws NullArgumentException {

    if (element == null || cutPoints == null) {
      throw new NullArgumentException();
    }

    InfiniteLine line = (InfiniteLine) element;
    Collection<Element> trimResult = new ArrayList<Element>();

    SortedSet<ComparablePoint> sortedPointSet =
        getSortedPointSet(line, line.getInitialPoint(), cutPoints);

    Vector direction = new Vector(line.getInitialPoint(), line.getEndingPoint());

    Vector clickVector = new Vector(line.getInitialPoint(), click);
    double key = direction.dotProduct(clickVector);
    ComparablePoint clickPoint = null;
    try {
      clickPoint = new ComparablePoint(click, new DoubleKey(key));
    } catch (NullArgumentException e) {
      // Should never reach
      e.printStackTrace();
    }

    SortedSet<ComparablePoint> headSet = sortedPointSet.headSet(clickPoint);
    SortedSet<ComparablePoint> tailSet = sortedPointSet.tailSet(clickPoint);

    try {

      if (tailSet.size() > 0 && tailSet.first().getPoint().equals(clickPoint.getPoint())) {

        Point initialPoint = tailSet.first().getPoint();

        if (line.getInitialPoint().compareTo(line.getEndingPoint()) < 0) {
          direction = new Vector(line.getInitialPoint(), line.getEndingPoint());
        } else {
          direction = new Vector(line.getEndingPoint(), line.getInitialPoint());
        }

        clickPoint.getPoint().setX(clickPoint.getPoint().getX() + direction.getX());
        clickPoint.getPoint().setY(clickPoint.getPoint().getY() + direction.getY());

        Element trimmedLine = generateSemiline(clickPoint, initialPoint);
        trimmedLine.setLayer(line.getLayer());
        trimResult.add(trimmedLine);

      } else if (headSet.size() == 0 && tailSet.size() > 0) {
        Point initialPoint = tailSet.first().getPoint();
        Element trimmedLine = generateSemiline(clickPoint, initialPoint);
        trimmedLine.setLayer(line.getLayer());
        trimResult.add(trimmedLine);

      } else if (tailSet.size() == 0 && headSet.size() > 0) {
        Point initialPoint = headSet.last().getPoint();
        Element trimmedLine = generateSemiline(clickPoint, initialPoint);
        trimmedLine.setLayer(line.getLayer());
        trimResult.add(trimmedLine);

      } else if (headSet.size() > 0 && tailSet.size() > 0) {

        Point initialPoint = headSet.last().getPoint();
        Element trimmedLine = generateSemiline(clickPoint, initialPoint);
        trimmedLine.setLayer(line.getLayer());
        trimResult.add(trimmedLine);

        initialPoint = tailSet.first().getPoint();
        trimmedLine = generateSemiline(clickPoint, initialPoint);
        trimmedLine.setLayer(line.getLayer());
        trimResult.add(trimmedLine);
      }
    } catch (Exception e) {
      // Should not catch any exception
      e.printStackTrace();
    }

    return trimResult;
  }