类com.google.common.base.Predicates源码实例Demo

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

源代码1 项目: enderutilities   文件: RenderEventHandler.java
private void renderItemExtras(World world, EntityPlayer usingPlayer, EntityPlayer clientPlayer, float partialTicks)
{
    ItemStack stack = EntityUtils.getHeldItemOfType(usingPlayer, EnderUtilitiesItems.BUILDERS_WAND);

    if (stack.isEmpty() == false && stack.getItem() == EnderUtilitiesItems.BUILDERS_WAND)
    {
        this.buildersWandRenderer.renderSelectedArea(world, usingPlayer, stack, clientPlayer, partialTicks);
    }

    stack = EntityUtils.getHeldItemOfType(usingPlayer, EnderUtilitiesItems.CHAIR_WAND);

    if (stack.isEmpty() == false)
    {
        List<EntityChair> chairs = world.getEntities(EntityChair.class, Predicates.alwaysTrue());

        for (Entity entity : chairs)
        {
            RenderUtils.renderEntityDebugBoundingBox(entity, partialTicks, false, false);
        }
    }

    this.rulerRenderer.renderAllPositionPairs(usingPlayer, clientPlayer, partialTicks);
}
 
源代码2 项目: brooklyn-library   文件: RiakClusterImpl.java
@Override
protected void doStart() {
    super.doStart();
    connectSensors();

    try {
        Duration delay = getConfig(DELAY_BEFORE_ADVERTISING_CLUSTER);
        Tasks.setBlockingDetails("Sleeping for "+delay+" before advertising cluster available");
        Time.sleep(delay);
    } finally {
        Tasks.resetBlockingDetails();
    }

    //FIXME: add a quorum to tolerate failed nodes before setting on fire.
    @SuppressWarnings("unchecked")
    Optional<Entity> anyNode = Iterables.tryFind(getMembers(), Predicates.and(
            Predicates.instanceOf(RiakNode.class),
            EntityPredicates.attributeEqualTo(RiakNode.RIAK_NODE_HAS_JOINED_CLUSTER, true),
            EntityPredicates.attributeEqualTo(RiakNode.SERVICE_UP, true)));
    if (anyNode.isPresent()) {
        sensors().set(IS_CLUSTER_INIT, true);
    } else {
        log.warn("No Riak Nodes are found on the cluster: {}. Initialization Failed", getId());
        ServiceStateLogic.setExpectedState(this, Lifecycle.ON_FIRE);
    }
}
 
源代码3 项目: incubator-heron   文件: CppCheckstyle.java
@SuppressWarnings("unchecked")
private static Collection<String> getSourceFiles(String extraActionFile) {

  ExtraActionInfo info = ExtraActionUtils.getExtraActionInfo(extraActionFile);
  CppCompileInfo cppInfo = info.getExtension(CppCompileInfo.cppCompileInfo);

  return Collections2.filter(
          cppInfo.getSourcesAndHeadersList(),
          Predicates.and(
                  Predicates.not(Predicates.containsPattern("external/")),
                  Predicates.not(Predicates.containsPattern("third_party/")),
                  Predicates.not(Predicates.containsPattern("config/heron-config.h")),
                  Predicates.not(Predicates.containsPattern(".*pb.h$")),
                  Predicates.not(Predicates.containsPattern(".*cc_wrapper.sh$")),
                  Predicates.not(Predicates.containsPattern(".*pb.cc$"))
          )
  );
}
 
@Test(groups="Integration") // Because slow
public void testFailuresThenUpDownResetsStabilisationCount() throws Exception {
    LOG.debug("Running testFailuresThenUpDownResetsStabilisationCount");
    final long stabilisationDelay = 1000;
    
    e1.enrichers().add(EnricherSpec.create(ServiceFailureDetector.class)
            .configure(ServiceFailureDetector.ENTITY_FAILED_STABILIZATION_DELAY, Duration.of(stabilisationDelay)));
    
    e1.sensors().set(TestEntity.SERVICE_UP, false);
    assertNoEventsContinually(Duration.of(stabilisationDelay - OVERHEAD));

    e1.sensors().set(TestEntity.SERVICE_UP, true);
    Thread.sleep(OVERHEAD);
    e1.sensors().set(TestEntity.SERVICE_UP, false);
    assertNoEventsContinually(Duration.of(stabilisationDelay - OVERHEAD));
    
    assertHasEventEventually(HASensors.ENTITY_FAILED, Predicates.<Object>equalTo(e1), null);
}
 
源代码5 项目: brooklyn-server   文件: UsageResource.java
@Override
public List<UsageStatistics> listApplicationsUsage(@Nullable String start, @Nullable String end) {
    log.debug("REST call to get application usage for all applications: dates {} -> {}", new Object[] {start, end});

    if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.USAGE, null))
        throw WebResourceUtils.forbidden("User '%s' is not authorized to perform this operation", Entitlements.getEntitlementContext().user());

    List<UsageStatistics> response = Lists.newArrayList();
    
    Date startDate = parseDate(start, new Date(0));
    Date endDate = parseDate(end, new Date());
    
    checkDates(startDate, endDate);

    Set<ApplicationUsage> usages = mgmtInternal().getUsageManager().getApplicationUsage(Predicates.alwaysTrue());

    for (ApplicationUsage usage : usages) {
        List<UsageStatistic> statistics = retrieveApplicationUsage(usage, startDate, endDate);
        if (statistics.size() > 0) {
            response.add(new UsageStatistics(statistics, ImmutableMap.<String,URI>of()));
        }
    }
    return response;
}
 
@Test
public void testShortPeriodicEffectorFiresAfterRebind() throws Exception {
    TestEntity origEntity = origApp.createAndManageChild(EntitySpec.create(TestEntity.class)
            .policy(PolicySpec.create(PeriodicEffectorPolicy.class)
                    .configure(PeriodicEffectorPolicy.EFFECTOR, "myEffector")
                    .configure(PeriodicEffectorPolicy.EFFECTOR_ARGUMENTS, ImmutableMap.of())
                    .configure(PeriodicEffectorPolicy.PERIOD, Duration.millis(1))
                    .configure(PeriodicEffectorPolicy.TIME, "immediately")
                    .configure(PeriodicEffectorPolicy.START_SENSOR, START)));

    origEntity.sensors().set(START, Boolean.TRUE);
    assertCallHistoryContainsEventually(origEntity, "myEffector");

    newApp = rebind(RebindOptions.create().terminateOrigManagementContext(true));

    TestEntity newEntity = (TestEntity) Iterables.find(newApp.getChildren(), Predicates.instanceOf(TestEntity.class));
    Policy newPolicy = Iterables.find(newEntity.policies(), Predicates.instanceOf(PeriodicEffectorPolicy.class));

    assertConfigEqualsEventually(newPolicy, PeriodicEffectorPolicy.RUNNING, true);
    int calls = newEntity.getCallHistory().size();
    assertCallHistoryEventually(newEntity, "myEffector", calls + 2);
}
 
源代码7 项目: brooklyn-library   文件: MongoDBClientSshDriver.java
private AbstractMongoDBServer getServer() {
    AbstractMongoDBServer server = entity.getConfig(MongoDBClient.SERVER);
    MongoDBShardedDeployment deployment = entity.getConfig(MongoDBClient.SHARDED_DEPLOYMENT);
    if (server == null) {
        Preconditions.checkNotNull(deployment, "Either server or shardedDeployment must be specified for %s", this);
        server = DependentConfiguration.builder()
                .attributeWhenReady(deployment.getRouterCluster(), MongoDBRouterCluster.ANY_ROUTER)
                .blockingDetails("any available router")
                .runNow();
        DependentConfiguration.builder()
                .attributeWhenReady(server, MongoDBRouter.SHARD_COUNT)
                .readiness(MathPredicates.<Integer>greaterThan(0))
                .runNow();
    } else {
        if (deployment != null) {
            log.warn("Server and ShardedDeployment defined for {}; using server ({} instead of {})", 
                    new Object[] {this, server, deployment});
        }
        DependentConfiguration.builder()
                .attributeWhenReady(server, Startable.SERVICE_UP)
                .readiness(Predicates.equalTo(true))
                .runNow();
    }
    return server;
}
 
源代码8 项目: retry   文件: ExponentialBackoff.java
public static void main(String[] args) {
    Callable<Boolean> callable = new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            // do something useful here
            LOGGER.info("call...");
            throw new RuntimeException();
        }
    };

    Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
            .retryIfResult(Predicates.isNull())
            .retryIfExceptionOfType(IOException.class)
            .retryIfRuntimeException()
            .withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS))
            .withStopStrategy(StopStrategies.stopAfterAttempt(3))
            .build();
    try {
        retryer.call(callable);
    } catch (RetryException | ExecutionException e) {
        e.printStackTrace();
    }
}
 
源代码9 项目: arcusplatform   文件: TestThresholdTrigger.java
@Test
public void testSatisfiable() {
 Model model2 = context.createModel("test", UUID.randomUUID());
 attributeName = "test:test";
 thresholdValue = 85.0;
 sensitivityValue = 5.0;
 Predicate<Address> source =  Predicates.equalTo(model.getAddress());
 trigger = new ThresholdTrigger(attributeName, thresholdValue, sensitivityValue, TriggerOn.GREATER_THAN, source);
	 
   trigger.activate(context);
   assertFalse(trigger.isSatisfiable(context));            
   
   model.setAttribute(attributeName, new Double(80));
   assertTrue(trigger.isSatisfiable(context));
   
   //valueChangeEvent = AttributeValueChangedEvent.create(model.getAddress(), attributeName, new Double(86.0), new Double(84.0));
   assertTrue(trigger.shouldFire(context, createValueChange(attributeName, new Double(80), new Double(86))));      
   assertFalse(trigger.shouldFire(context, createValueChange("test:bad", new Double(80), new Double(86))));  
   //source does not match
   assertFalse(trigger.shouldFire(context, createValueChange(model2, attributeName, new Double(80), new Double(86))));
}
 
源代码10 项目: arcusplatform   文件: GroovyDriverBuilder.java
public GroovyDriverBuilder addMatchers(Map<String, Object> values) {
   if(values != null && !values.isEmpty()) {
      List<Predicate<AttributeMap>> predicators = new LinkedList<Predicate<AttributeMap>>();
      for(Map.Entry<String, Object> e: values.entrySet()) {
         Predicate<AttributeMap> predicated = toMatcher(e.getKey(), e.getValue());
         if(predicated != null) {
            predicators.add(predicated);
         }
      }
      if(predicators.size() == 1) {
         attributeMatchers.add(predicators.get(0));
      }
      else if(predicators.size() > 1) {
         attributeMatchers.add(Predicates.and(predicators));
      }
   }
   return this;
}
 
源代码11 项目: neural   文件: RetryerBuilderTest.java
@Test
public void testMultipleRetryConditions() throws ExecutionException, RetryException {
    Callable<Boolean> callable = notNullResultOrIOExceptionOrRuntimeExceptionAfter5Attempts();
    Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
            .retryIfResult(Predicates.<Boolean>isNull())
            .retryIfExceptionOfType(IOException.class)
            .retryIfRuntimeException()
            .withStopStrategy(StopStrategies.stopAfterAttempt(3))
            .build();
    try {
        retryer.call(callable);
        fail("RetryException expected");
    } catch (RetryException e) {
        assertTrue(e.getLastFailedAttempt().hasException());
        assertTrue(e.getLastFailedAttempt().getExceptionCause() instanceof IllegalStateException);
        assertTrue(e.getCause() instanceof IllegalStateException);
    }

    callable = notNullResultOrIOExceptionOrRuntimeExceptionAfter5Attempts();
    retryer = RetryerBuilder.<Boolean>newBuilder()
            .retryIfResult(Predicates.<Boolean>isNull())
            .retryIfExceptionOfType(IOException.class)
            .retryIfRuntimeException()
            .build();
    assertTrue(retryer.call(callable));
}
 
源代码12 项目: brooklyn-server   文件: HaPolicyRebindTest.java
@Test
public void testServiceFailureDetectorWorksAfterRebind() throws Exception {
    origEntity.enrichers().add(EnricherSpec.create(ServiceFailureDetector.class));

    // rebind
    TestApplication newApp = rebind();
    final TestEntity newEntity = (TestEntity) Iterables.find(newApp.getChildren(), Predicates.instanceOf(TestEntity.class));

    newApp.getManagementContext().getSubscriptionManager().subscribe(newEntity, HASensors.ENTITY_FAILED, eventListener);

    newEntity.sensors().set(TestEntity.SERVICE_UP, true);
    ServiceStateLogic.setExpectedState(newEntity, Lifecycle.RUNNING);
    
    // trigger the failure
    newEntity.sensors().set(TestEntity.SERVICE_UP, false);

    assertHasEventEventually(HASensors.ENTITY_FAILED, Predicates.<Object>equalTo(newEntity), null);
    assertEquals(events.size(), 1, "events="+events);
}
 
源代码13 项目: arcusplatform   文件: AnnotatedSubsystemFactory.java
private static Predicate<SubsystemEventAndContext> isMessageFrom(String[] sources) {
   Set<Predicate<Address>> matchers = new HashSet<>(sources.length);
   for(String source: sources) {
      matchers.add(AddressMatchers.fromString(source));
   }
   final Predicate<Address> addressMatches = Predicates.or(matchers);
   return new Predicate<SubsystemEventAndContext>() {
      @Override
      public boolean apply(SubsystemEventAndContext input) {
         MessageReceivedEvent event = (MessageReceivedEvent) input.getEvent();
         return addressMatches.apply(event.getMessage().getSource());
      }
      
      @Override
      public String toString() {
         return "Message from " + addressMatches;
      }
   };
}
 
@Test
public void testAllAndAny() {
    Assert.assertEquals(CollectionFunctionals.all(Predicates.equalTo(1)).apply(
        MutableList.of(1, 1, 1)), true);
    Assert.assertEquals(CollectionFunctionals.all(Predicates.equalTo(1)).apply(
        MutableList.<Integer>of()), true);
    Assert.assertEquals(CollectionFunctionals.all(Predicates.equalTo(1)).apply(
        MutableList.of(1, 0, 1)), false);
    Assert.assertEquals(CollectionFunctionals.all(Predicates.equalTo(1)).apply(
        MutableList.of(0, 0, 0)), false);
    
    Assert.assertEquals(CollectionFunctionals.any(Predicates.equalTo(1)).apply(
        MutableList.of(1, 1, 1)), true);
    Assert.assertEquals(CollectionFunctionals.any(Predicates.equalTo(1)).apply(
        MutableList.<Integer>of()), false);
    Assert.assertEquals(CollectionFunctionals.any(Predicates.equalTo(1)).apply(
        MutableList.of(1, 0, 1)), true);
    Assert.assertEquals(CollectionFunctionals.any(Predicates.equalTo(1)).apply(
        MutableList.of(0, 0, 0)), false);
    
}
 
源代码15 项目: bazel   文件: GenQuery.java
@Nullable
private GenQueryResult executeQuery(
    RuleContext ruleContext, QueryOptions queryOptions, Collection<Label> scope, String query)
    throws InterruptedException {
  SkyFunction.Environment env = ruleContext.getAnalysisEnvironment().getSkyframeEnv();
  Pair<ImmutableMap<PackageIdentifier, Package>, ImmutableMap<Label, Target>> closureInfo;
  try {
    closureInfo = constructPackageMap(env, scope);
    if (closureInfo == null) {
      return null;
    }
  } catch (BrokenQueryScopeException e) {
    ruleContext.ruleError(e.getMessage());
    return null;
  }

  ImmutableMap<PackageIdentifier, Package> packageMap = closureInfo.first;
  ImmutableMap<Label, Target> validTargetsMap = closureInfo.second;
  PreloadedMapPackageProvider packageProvider =
      new PreloadedMapPackageProvider(packageMap, validTargetsMap);
  TargetPatternPreloader preloader = new SkyframeEnvTargetPatternEvaluator(env);
  Predicate<Label> labelFilter = Predicates.in(validTargetsMap.keySet());

  return doQuery(queryOptions, packageProvider, labelFilter, preloader, query, ruleContext);
}
 
源代码16 项目: dagger2-sample   文件: BindingGraphValidator.java
private void reportCycle(DependencyRequest request, Deque<ResolvedRequest> path,
    final ValidationReport.Builder<BindingGraph> reportBuilder) {
  ImmutableList<DependencyRequest> pathElements = ImmutableList.<DependencyRequest>builder()
      .add(request)
      .addAll(Iterables.transform(path, REQUEST_FROM_RESOLVED_REQUEST))
      .build();
  ImmutableList<String> printableDependencyPath = FluentIterable.from(pathElements)
      .transform(dependencyRequestFormatter)
      .filter(Predicates.not(Predicates.equalTo("")))
      .toList()
      .reverse();
  DependencyRequest rootRequest = path.getLast().request();
  TypeElement componentType =
      MoreElements.asType(rootRequest.requestElement().getEnclosingElement());
  // TODO(cgruber): Restructure to provide a hint for the start and end of the cycle.
  reportBuilder.addItem(
      String.format(ErrorMessages.CONTAINS_DEPENDENCY_CYCLE_FORMAT,
          componentType.getQualifiedName(),
          rootRequest.requestElement().getSimpleName(),
          Joiner.on("\n")
              .join(printableDependencyPath.subList(1, printableDependencyPath.size()))),
      rootRequest.requestElement());
}
 
源代码17 项目: arcusplatform   文件: PanicAlarm.java
public PanicAlarm() {
	// FIXME update the offline to take rule:state == DISABLED into account
	super(
			NAME,
			ExpressionCompiler.compile(
				"base:caps contains 'keypad' OR " +
				"(" +
					"rule:template == 'pendant-panic' OR " +
					"rule:template == 'button-panic' OR " +
					"rule:template == '01e7de' OR " +
					"rule:template == 'c2dd38'" +
				")"
			),
			Predicates.<Model>alwaysFalse()
	);
}
 
源代码18 项目: nexus-public   文件: RealmApiResource.java
@Path("active")
@PUT
@RequiresAuthentication
@RequiresPermissions("nexus:settings:update")
@Override
public void setActiveRealms(final List<String> realmIds) {
  Set<String> knownRealmIds = new HashSet<>();
  realmManager.getAvailableRealms().stream().map(SecurityRealm::getId).forEach(knownRealmIds::add);

  List<String> unknownRealms =
      realmIds.stream().filter(Predicates.not(knownRealmIds::contains)).collect(Collectors.toList());
  if (!unknownRealms.isEmpty()) {
    log.debug("Request to set realms with unknown IDs: " + unknownRealms);
    throw new WebApplicationMessageException(Status.BAD_REQUEST, "\"Unknown realmIds: " + unknownRealms + "\"");
  }

  RealmConfiguration configuration = realmManager.getConfiguration();
  configuration.setRealmNames(realmIds);
  realmManager.setConfiguration(configuration);
}
 
源代码19 项目: HiveRunner   文件: HiveRunnerExtension.java
private void setupConfig(Object target) {
  Set<Field> fields = ReflectionUtils.getAllFields(target.getClass(),
      Predicates.and(
          withAnnotation(HiveRunnerSetup.class),
          withType(HiveRunnerConfig.class)));

  Preconditions.checkState(fields.size() <= 1,
      "Only one field of type HiveRunnerConfig should be annotated with @HiveRunnerSetup");

  if (!fields.isEmpty()) {
    config.override(ReflectionUtils
        .getFieldValue(target, fields.iterator().next().getName(), HiveRunnerConfig.class));
  }
}
 
源代码20 项目: buck   文件: CopyNativeLibrariesTest.java
@Test
public void testCopyNativeLibrariesCopiesLibDirsInReverseTopoOrder() {
  BuildTarget target = BuildTargetFactory.newInstance("//:test");
  SourcePathRuleFinder ruleFinder = new TestActionGraphBuilder();
  CopyNativeLibraries copyNativeLibraries =
      new CopyNativeLibraries(
          target,
          new FakeProjectFilesystem(),
          ruleFinder,
          ImmutableSet.of(),
          ImmutableSet.of(),
          ImmutableSet.of(FakeSourcePath.of("lib1"), FakeSourcePath.of("lib2")),
          ImmutableSet.of(),
          ImmutableSet.of(),
          "dex");

  ImmutableList<Step> steps =
      copyNativeLibraries.getBuildSteps(
          FakeBuildContext.withSourcePathResolver(ruleFinder.getSourcePathResolver()),
          new FakeBuildableContext());

  Iterable<String> descriptions =
      Iterables.transform(steps, step -> step.getDescription(TestExecutionContext.newInstance()));
  assertThat(
      "lib1 contents should be copied *after* lib2",
      Iterables.indexOf(descriptions, Predicates.containsPattern("lib1")),
      Matchers.greaterThan(Iterables.indexOf(descriptions, Predicates.containsPattern("lib2"))));
}
 
源代码21 项目: presto   文件: TestEffectivePredicateExtractor.java
@Test
public void testInnerJoinWithFalseFilter()
{
    Map<Symbol, ColumnHandle> leftAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(A, B, C)));
    TableScanNode leftScan = tableScanNode(leftAssignments);

    Map<Symbol, ColumnHandle> rightAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(D, E, F)));
    TableScanNode rightScan = tableScanNode(rightAssignments);

    PlanNode node = new JoinNode(
            newId(),
            JoinNode.Type.INNER,
            leftScan,
            rightScan,
            ImmutableList.of(new JoinNode.EquiJoinClause(A, D)),
            leftScan.getOutputSymbols(),
            rightScan.getOutputSymbols(),
            Optional.of(FALSE_LITERAL),
            Optional.empty(),
            Optional.empty(),
            Optional.empty(),
            Optional.empty(),
            ImmutableMap.of(),
            Optional.empty());

    Expression effectivePredicate = effectivePredicateExtractor.extract(SESSION, node, TypeProvider.empty(), typeAnalyzer);

    assertEquals(effectivePredicate, FALSE_LITERAL);
}
 
源代码22 项目: neural   文件: RetryerBuilderTest.java
@Test
public void testWrap() throws ExecutionException, RetryException {
    Callable<Boolean> callable = notNullAfter5Attempts();
    Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
            .retryIfResult(Predicates.<Boolean>isNull())
            .build();
    Retryer.RetryerCallable<Boolean> wrapped = retryer.wrap(callable);
    assertTrue(wrapped.call());
}
 
源代码23 项目: brooklyn-server   文件: CatalogScanTest.java
private synchronized void loadTheDefaultCatalog(boolean lookOnDiskForDefaultCatalog) {
    if (defaultCatalog!=null) return;
    BrooklynProperties props = BrooklynProperties.Factory.newEmpty();
    props.put(BrooklynServerConfig.BROOKLYN_CATALOG_URL.getName(),
        // if default catalog is picked up from the system, we might get random stuff from ~/.brooklyn/ instead of the default;
        // useful as an integration check that we default correctly, but irritating for people to use if they have such a catalog installed
        (lookOnDiskForDefaultCatalog ? "" :
            "data:,"+Urls.encode(new ResourceUtils(this).getResourceAsString("classpath:/brooklyn/default.catalog.bom"))));
    LocalManagementContext mgmt = newManagementContext(props);
    defaultCatalog = mgmt.getCatalog();
    log.info("ENTITIES loaded for DEFAULT: "+defaultCatalog.getCatalogItems(Predicates.alwaysTrue()));
}
 
@Test public void testBug352214() {
	container.getResourceDescriptions(); // initialize uri map
	ResourceDescriptionChangeEvent event = new ResourceDescriptionChangeEvent(Collections.<IResourceDescription.Delta>singletonList(
			new ChangedResourceDescriptionDelta(resourceDescription, null)));
	container.descriptionsChanged(event);
	assertEquals(0, container.getResourceDescriptionCount());
	assertTrue(Iterables.all(container.getResourceDescriptions(), Predicates.notNull()));
	assertTrue(container.hasResourceDescription(uri)); // broken invariant in implementation
	assertNull(container.getResourceDescription(uri));
}
 
源代码25 项目: brooklyn-server   文件: ArchiveBuilderTest.java
@Test
public void testCreateZipFromTwoDirs() throws Exception {
    File archive = ArchiveBuilder.zip().addDirContentsAt(tmpDir, ".").addDirContentsAt(tmpDir2, ".").create();
    archive.deleteOnExit();

    List<ZipEntry> entries = Lists.newArrayList();
    ZipInputStream input = new ZipInputStream(new FileInputStream(archive));
    ZipEntry entry = input.getNextEntry();
    while (entry != null) {
        entries.add(entry);
        entry = input.getNextEntry();
    }
    assertEquals(entries.size(), 5);
    Iterable<ZipEntry> directories = Iterables.filter(entries, isDirectory);
    Iterable<ZipEntry> files = Iterables.filter(entries, Predicates.not(isDirectory));
    assertEquals(Iterables.size(directories), 1);
    assertEquals(Iterables.size(files), 4);
    String dirName = Iterables.getOnlyElement(directories).getName();
    assertEquals(dirName, "./");
    
    Set<String> names = MutableSet.of();
    for (ZipEntry file : files) {
        assertTrue(file.getName().startsWith(dirName));
        names.add(file.getName());
    }
    assertTrue(names.contains("./data01.txt"));
    assertTrue(names.contains("./data04.txt"));
    input.close();
}
 
源代码26 项目: brooklyn-server   文件: CatalogResource.java
@Override
@Deprecated
public List<CatalogEntitySummary> listEntities(String regex, String fragment, boolean allVersions) {
    Predicate<RegisteredType> filter =
            Predicates.and(
                    RegisteredTypePredicates.IS_ENTITY,
                    RegisteredTypePredicates.disabled(false));
    List<CatalogItemSummary> result = getCatalogItemSummariesMatchingRegexFragment(filter, regex, fragment, allVersions);
    return castList(result, CatalogEntitySummary.class);
}
 
@Test
public void whenRemoveNullFromCollection_thenRemoved() {
    final List<String> names = Lists.newArrayList("John", null, "Jane", null, "Adam", "Tom");
    final Collection<String> result = Collections2.filter(names, Predicates.notNull());

    assertEquals(4, result.size());
    assertThat(result, containsInAnyOrder("John", "Jane", "Adam", "Tom"));
}
 
private void assertCallHistoryEventually(TestEntity entity, String effector, int minSize) {
    Asserts.succeedsEventually(new Runnable() {
        public void run() {
            List<String> callHistory = entity.getCallHistory();
            synchronized (callHistory) {
                int size = Iterables.size(Iterables.filter(callHistory, Predicates.equalTo("myEffector")));
                assertTrue(size >= minSize, "size="+size);
            }
        }});
}
 
@Test
public final void givenCollectionContainsNulls_whenNullsAreFilteredOut_thenResultingCollectionsHasNoNulls() {
    final List<String> withNulls = Lists.newArrayList("a", "bc", null, "def");
    final Iterable<String> withoutNuls = Iterables.filter(withNulls, Predicates.notNull());

    assertTrue(Iterables.all(withoutNuls, Predicates.notNull()));
}
 
源代码30 项目: arcusplatform   文件: PlatformDispatcherFactory.java
private Predicate<Address> getMatcher(String[] from) {
   if(from.length == 0) {
      return Predicates.alwaysTrue();
   }
   else if(from.length == 1) {
      return AddressMatchers.fromString(from[0]);
   }
   else {
      return Predicates.or(Arrays.asList(from).stream().map(AddressMatchers::fromString).collect(Collectors.toList()));
   }
}