类com.google.common.collect.Ranges源码实例Demo

下面列出了怎么用com.google.common.collect.Ranges的API类实例代码及写法,或者点击链接到github查看源代码。

@Test
public void testUnboundedRangeIsRejected() {
    try {
        final Restriction ageRestrictionInt = doInJPA(new JPATransactionFunction<Restriction>() {
            @Override
            public Restriction apply(EntityManager entityManager) {
                Restriction restriction = new Restriction();
                restriction.setRangeInt(Ranges.<Integer>all());
                entityManager.persist(restriction);

                return restriction;
            }
        });
        fail("An unbounded range should throw an exception!");
    } catch (Exception e) {
        Throwable rootCause = Throwables.getRootCause(e);
        assertTrue(rootCause instanceof IllegalArgumentException);
        assertTrue(rootCause.getMessage().contains("doesn't have any upper or lower bound!"));
    }
}
 
@Test
public void testUnboundedRangeIsRejected() {
    try {
        final Restriction ageRestrictionInt = doInJPA(new JPATransactionFunction<Restriction>() {
            @Override
            public Restriction apply(EntityManager entityManager) {
                Restriction restriction = new Restriction();
                restriction.setRangeInt(Ranges.<Integer>all());
                entityManager.persist(restriction);

                return restriction;
            }
        });
        fail("An unbounded range should throw an exception!");
    } catch (Exception e) {
        Throwable rootCause = Throwables.getRootCause(e);
        assertTrue(rootCause instanceof IllegalArgumentException);
        assertTrue(rootCause.getMessage().contains("doesn't have any upper or lower bound!"));
    }
}
 
@Test
public void testUnboundedRangeIsRejected() {
    try {
        final Restriction ageRestrictionInt = doInJPA(new JPATransactionFunction<Restriction>() {
            @Override
            public Restriction apply(EntityManager entityManager) {
                Restriction restriction = new Restriction();
                restriction.setRangeInt(Ranges.<Integer>all());
                entityManager.persist(restriction);

                return restriction;
            }
        });
        fail("An unbounded range should throw an exception!");
    } catch (Exception e) {
        Throwable rootCause = Throwables.getRootCause(e);
        assertTrue(rootCause instanceof IllegalArgumentException);
        assertTrue(rootCause.getMessage().contains("doesn't have any upper or lower bound!"));
    }
}
 
@Test
public void testSingleBoundedRanges() {
    PostgreSQLGuavaRangeType instance = PostgreSQLGuavaRangeType.INSTANCE;

    assertEquals("(,)", instance.asString(Ranges.all()));
    assertEquals("(1,)", instance.asString(Ranges.greaterThan(1)));
    assertEquals("[2,)", instance.asString(Ranges.atLeast(2)));
    assertEquals("(,3)", instance.asString(Ranges.lessThan(3)));
    assertEquals("(,4]", instance.asString(Ranges.atMost(4)));

    assertEquals(Ranges.greaterThan(5), instance.integerRange("(5,)"));
    assertEquals(Ranges.atLeast(6), instance.integerRange("[6,)"));
    assertEquals(Ranges.lessThan(7), instance.integerRange("(,7)"));
    assertEquals(Ranges.atMost(8), instance.integerRange("(,8]"));
}
 
@Test
public void testSingleBoundedRanges() {
    PostgreSQLGuavaRangeType instance = PostgreSQLGuavaRangeType.INSTANCE;

    assertEquals("(,)", instance.asString(Ranges.all()));
    assertEquals("(1,)", instance.asString(Ranges.greaterThan(1)));
    assertEquals("[2,)", instance.asString(Ranges.atLeast(2)));
    assertEquals("(,3)", instance.asString(Ranges.lessThan(3)));
    assertEquals("(,4]", instance.asString(Ranges.atMost(4)));

    assertEquals(Ranges.greaterThan(5), instance.integerRange("(5,)"));
    assertEquals(Ranges.atLeast(6), instance.integerRange("[6,)"));
    assertEquals(Ranges.lessThan(7), instance.integerRange("(,7)"));
    assertEquals(Ranges.atMost(8), instance.integerRange("(,8]"));
}
 
@Test
public void testSingleBoundedRanges() {
    PostgreSQLGuavaRangeType instance = PostgreSQLGuavaRangeType.INSTANCE;

    assertEquals("(,)", instance.asString(Ranges.all()));
    assertEquals("(1,)", instance.asString(Ranges.greaterThan(1)));
    assertEquals("[2,)", instance.asString(Ranges.atLeast(2)));
    assertEquals("(,3)", instance.asString(Ranges.lessThan(3)));
    assertEquals("(,4]", instance.asString(Ranges.atMost(4)));

    assertEquals(Ranges.greaterThan(5), instance.integerRange("(5,)"));
    assertEquals(Ranges.atLeast(6), instance.integerRange("[6,)"));
    assertEquals(Ranges.lessThan(7), instance.integerRange("(,7)"));
    assertEquals(Ranges.atMost(8), instance.integerRange("(,8]"));
}
 
@SuppressWarnings("unchecked")
public static <T extends Comparable> Range<T> ofString(String str, Function<String, T> converter, Class<T> cls) {
    BoundType lowerBound = str.charAt(0) == '[' ? BoundType.CLOSED : BoundType.OPEN;
    BoundType upperBound = str.charAt(str.length() - 1) == ']' ? BoundType.CLOSED : BoundType.OPEN;

    int delim = str.indexOf(',');

    if (delim == -1) {
        throw new IllegalArgumentException("Cannot find comma character");
    }

    String lowerStr = str.substring(1, delim);
    String upperStr = str.substring(delim + 1, str.length() - 1);

    T lower = null;
    T upper = null;

    if (lowerStr.length() > 0) {
        lower = converter.apply(lowerStr);
    }

    if (upperStr.length() > 0) {
        upper = converter.apply(upperStr);
    }

    if (lower == null && upper == null) {
        throw new IllegalArgumentException("Cannot find bound type");
    }

    if (lowerStr.length() == 0) {
        return upperBound == BoundType.CLOSED ?
            Ranges.atMost(upper) :
            Ranges.lessThan(upper);
    } else if (upperStr.length() == 0) {
        return lowerBound == BoundType.CLOSED ?
            Ranges.atLeast(lower) :
            Ranges.greaterThan(lower);
    } else {
        return Ranges.range(lower, lowerBound, upper, upperBound);
    }
}
 
@SuppressWarnings("unchecked")
public static <T extends Comparable> Range<T> ofString(String str, Function<String, T> converter, Class<T> cls) {
    BoundType lowerBound = str.charAt(0) == '[' ? BoundType.CLOSED : BoundType.OPEN;
    BoundType upperBound = str.charAt(str.length() - 1) == ']' ? BoundType.CLOSED : BoundType.OPEN;

    int delim = str.indexOf(',');

    if (delim == -1) {
        throw new IllegalArgumentException("Cannot find comma character");
    }

    String lowerStr = str.substring(1, delim);
    String upperStr = str.substring(delim + 1, str.length() - 1);

    T lower = null;
    T upper = null;

    if (lowerStr.length() > 0) {
        lower = converter.apply(lowerStr);
    }

    if (upperStr.length() > 0) {
        upper = converter.apply(upperStr);
    }

    if (lower == null && upper == null) {
        throw new IllegalArgumentException("Cannot find bound type");
    }

    if (lowerStr.length() == 0) {
        return upperBound == BoundType.CLOSED ?
            Ranges.atMost(upper) :
            Ranges.lessThan(upper);
    } else if (upperStr.length() == 0) {
        return lowerBound == BoundType.CLOSED ?
            Ranges.atLeast(lower) :
            Ranges.greaterThan(lower);
    } else {
        return Ranges.range(lower, lowerBound, upper, upperBound);
    }
}
 
@SuppressWarnings("unchecked")
public static <T extends Comparable> Range<T> ofString(String str, Function<String, T> converter, Class<T> cls) {
    BoundType lowerBound = str.charAt(0) == '[' ? BoundType.CLOSED : BoundType.OPEN;
    BoundType upperBound = str.charAt(str.length() - 1) == ']' ? BoundType.CLOSED : BoundType.OPEN;

    int delim = str.indexOf(',');

    if (delim == -1) {
        throw new IllegalArgumentException("Cannot find comma character");
    }

    String lowerStr = str.substring(1, delim);
    String upperStr = str.substring(delim + 1, str.length() - 1);

    T lower = null;
    T upper = null;

    if (lowerStr.length() > 0) {
        lower = converter.apply(lowerStr);
    }

    if (upperStr.length() > 0) {
        upper = converter.apply(upperStr);
    }

    if (lower == null && upper == null) {
        throw new IllegalArgumentException("Cannot find bound type");
    }

    if (lowerStr.length() == 0) {
        return upperBound == BoundType.CLOSED ?
            Ranges.atMost(upper) :
            Ranges.lessThan(upper);
    } else if (upperStr.length() == 0) {
        return lowerBound == BoundType.CLOSED ?
            Ranges.atLeast(lower) :
            Ranges.greaterThan(lower);
    } else {
        return Ranges.range(lower, lowerBound, upper, upperBound);
    }
}
 
源代码10 项目: twill   文件: ApplicationMasterService.java
/**
 * Helper method to restart instances of runnables.
 */
private void restartRunnableInstances(final String runnableName, @Nullable final Set<Integer> instanceIds,
                                      final Runnable completion) {
  instanceChangeExecutor.execute(new Runnable() {
    @Override
    public void run() {
      LOG.debug("Begin restart runnable {} instances.", runnableName);
      int runningCount = runningContainers.count(runnableName);
      Set<Integer> instancesToRemove = instanceIds == null ? null : ImmutableSet.copyOf(instanceIds);
      if (instancesToRemove == null) {
        instancesToRemove = Ranges.closedOpen(0, runningCount).asSet(DiscreteDomains.integers());
      }

      LOG.info("Restarting instances {} for runnable {}", instancesToRemove, runnableName);
      RunnableContainerRequest containerRequest =
        createRunnableContainerRequest(runnableName, instancesToRemove.size(), false);
      runnableContainerRequests.add(containerRequest);

      for (int instanceId : instancesToRemove) {
        LOG.debug("Stop instance {} for runnable {}", instanceId, runnableName);
        try {
          runningContainers.stopByIdAndWait(runnableName, instanceId);
        } catch (Exception ex) {
          // could be thrown if the container already stopped.
          LOG.info("Exception thrown when stopping instance {} probably already stopped.", instanceId);
        }
      }

      LOG.info("All instances in {} for runnable {} are stopped. Ready to provision",
               instancesToRemove, runnableName);

      // set the container request to be ready
      containerRequest.setReadyToBeProvisioned();

      // For all runnables that needs to re-request for containers, update the expected count timestamp
      // so that the EventHandler would be triggered with the right expiration timestamp.
      expectedContainers.updateRequestTime(Collections.singleton(runnableName));

      completion.run();
    }
  });
}
 
源代码11 项目: kite-examples   文件: GenerateSimpleLogs.java
@Override
public int run(String[] args) throws Exception {
  // going to generate a lot of random log messages
  final Random rand = new Random();

  // data is written to the staging dataset
  Dataset<Record> staging = Datasets.load(
      "dataset:file:/tmp/data/logs_staging", Record.class);

  // this is going to build our simple log records
  GenericRecordBuilder builder = new GenericRecordBuilder(
      staging.getDescriptor().getSchema());

  // generate timestamps 1 second apart starting 1 day ago
  final Calendar now = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
  final long yesterday = now.getTimeInMillis() - DAY_IN_MILLIS;

  DatasetWriter<Record> writer = null;
  try {
    writer = staging.newWriter();

    // generate 15,000 messages, each 5 seconds apart, starting 24 hours ago
    // this is a little less than 24 hours worth of messages
    for (int second : Ranges.closed(0, 15000).asSet(DiscreteDomains.integers())) {
      LOG.info("Generating log message " + second);

      builder.set("timestamp", yesterday + second * 5000);
      builder.set("component", "GenerateSimpleLogs");

      int level = rand.nextInt(LOG_LEVELS.length);
      builder.set("level", LOG_LEVELS[level]);
      builder.set("message", LOG_MESSAGES[level]);

      writer.write(builder.build());
    }

    if (writer instanceof Flushable) {
      ((Flushable) writer).flush();
    }
  } finally {
    if (writer != null) {
      writer.close();
    }
  }

  return 0;
}
 
源代码12 项目: kangaroo   文件: ZkUtils.java
/**
 * Checks whether the provided partition exists on the {@link Broker}.
 * 
 * @param broker
 *            the broker.
 * @param topic
 *            the topic.
 * @param partId
 *            the partition id.
 * @return true if this partition exists on the {@link Broker}, false otherwise.
 */
public boolean partitionExists(final Broker broker, final String topic, final int partId) {
    final String parts = client.readData(getTopicBrokerIdPath(topic, broker.getId()), true);
    return !Strings.isNullOrEmpty(parts) && Ranges.closedOpen(0, Integer.parseInt(parts)).contains(partId);
}
 
 类方法
 同包方法