com.google.common.base.Predicates Java Examples

The following examples show how to use com.google.common.base.Predicates. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MongoDBClientSshDriver.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #2
Source File: RiakClusterImpl.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #3
Source File: GroovyDriverBuilder.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: RenderEventHandler.java    From enderutilities with GNU Lesser General Public License v3.0 6 votes vote down vote up
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);
}
 
Example #5
Source File: RetryerBuilderTest.java    From neural with MIT License 6 votes vote down vote up
@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));
}
 
Example #6
Source File: HaPolicyRebindTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #7
Source File: CppCheckstyle.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
@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$"))
          )
  );
}
 
Example #8
Source File: ServiceFailureDetectorStabilizationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #9
Source File: TestThresholdTrigger.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@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))));
}
 
Example #10
Source File: ExponentialBackoff.java    From retry with Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example #11
Source File: PanicAlarm.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
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()
	);
}
 
Example #12
Source File: UsageResource.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #13
Source File: BindingGraphValidator.java    From dagger2-sample with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #14
Source File: GenQuery.java    From bazel with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #15
Source File: ScheduledPolicyRebindTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #16
Source File: CollectionFunctionalsTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@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);
    
}
 
Example #17
Source File: AnnotatedSubsystemFactory.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
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;
      }
   };
}
 
Example #18
Source File: RealmApiResource.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@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);
}
 
Example #19
Source File: F5BigipStructuredGrammarTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Test
public void testVirtualMatchesIpProtocol() throws IOException {
  String hostname = "f5_bigip_structured_ltm_virtual_ip_protocol";
  Configuration c = parseConfig(hostname);
  Transformation incomingTransformation =
      c.getAllInterfaces().get("/Common/vlan1").getIncomingTransformation();
  Flow.Builder builder =
      Flow.builder()
          .setDstIp(Ip.parse("192.0.2.1"))
          .setDstPort(80)
          .setIngressInterface("/Common/SOME_VLAN")
          .setIngressNode(hostname)
          .setSrcIp(Ip.parse("8.8.8.8"))
          .setSrcPort(50000);

  Flow matchingFlow = builder.setIpProtocol(IpProtocol.TCP).build();
  Flow nonMatchingFlow = builder.setIpProtocol(IpProtocol.UDP).build();

  assertTrue(
      "Flow with correct IpProtocol TCP is matched by incoming transformation",
      eval(incomingTransformation, matchingFlow, "dummy", ImmutableMap.of(), ImmutableMap.of())
          .getTraceSteps().stream()
          .map(Step::getDetail)
          .filter(Predicates.instanceOf(TransformationStepDetail.class))
          .map(TransformationStepDetail.class::cast)
          .anyMatch(d -> d.getTransformationType() == TransformationType.DEST_NAT));
  assertFalse(
      "Flow with incorrect IpProtocol UDP is not matched by incoming transformation",
      eval(incomingTransformation, nonMatchingFlow, "dummy", ImmutableMap.of(), ImmutableMap.of())
          .getTraceSteps().stream()
          .map(Step::getDetail)
          .filter(Predicates.instanceOf(TransformationStepDetail.class))
          .map(TransformationStepDetail.class::cast)
          .anyMatch(d -> d.getTransformationType() == TransformationType.DEST_NAT));
}
 
Example #20
Source File: PlatformDispatcherFactory.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
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()));
   }
}
 
Example #21
Source File: ScheduledPolicyRebindTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
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);
            }
        }});
}
 
Example #22
Source File: GuavaFunctionalExamplesUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@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()));
}
 
Example #23
Source File: JCloudsPropertiesBuilder.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public JCloudsPropertiesBuilder setCustomJcloudsProperties() {
    Map<String, Object> extra = Maps.filterKeys(conf.getAllConfig(), Predicates.containsPattern("^jclouds\\."));
    if (extra.size() > 0) {
        String provider = getProviderFromConfig(conf);
        LOG.debug("Configuring custom jclouds property overrides for {}: {}", provider, Sanitizer.sanitize(extra));
    }
    properties.putAll(Maps.filterValues(extra, Predicates.notNull()));
    return this;
}
 
Example #24
Source File: GuavaFilterTransformCollectionsUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@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"));
}
 
Example #25
Source File: CatalogResource.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #26
Source File: ArchiveBuilderTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #27
Source File: RebindOsgiTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@DataProvider(name = "valInEntityDataProvider")
public Object[][] valInEntityDataProvider() {
    return new Object[][] {
        {Predicates.alwaysTrue(), false},
        {Predicates.alwaysTrue(), true},
        {OsFamily.CENTOS, false},
        {OsFamily.CENTOS, true},
    };
}
 
Example #28
Source File: ResourceDescriptionsBasedContainerTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@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));
}
 
Example #29
Source File: Sets.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns an unmodifiable <b>view</b> of the intersection of two sets. The
 * returned set contains all elements that are contained by both backing sets.
 * The iteration order of the returned set matches that of {@code set1}.
 *
 * <p>Results are undefined if {@code set1} and {@code set2} are sets based
 * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
 * and the keySet of an {@code IdentityHashMap} all are).
 *
 * <p><b>Note:</b> The returned view performs slightly better when {@code
 * set1} is the smaller of the two sets. If you have reason to believe one of
 * your sets will generally be smaller than the other, pass it first.
 * Unfortunately, since this method sets the generic type of the returned set
 * based on the type of the first set passed, this could in rare cases force
 * you to make a cast, for example: <pre>   {@code
 *
 *   Set<Object> aFewBadObjects = ...
 *   Set<String> manyBadStrings = ...
 *
 *   // impossible for a non-String to be in the intersection
 *   SuppressWarnings("unchecked")
 *   Set<String> badStrings = (Set) Sets.intersection(
 *       aFewBadObjects, manyBadStrings);}</pre>
 *
 * <p>This is unfortunate, but should come up only very rarely.
 */


public static <E> SetView<E> intersection(
  final Set<E> set1, final Set<?> set2) {
  checkNotNull(set1, "set1");
  checkNotNull(set2, "set2");
  final Predicate<Object> inSet2 = Predicates.in(set2);
  return new SetView<E>() {
    @Override
    public Iterator<E> iterator() {
      return Iterators.filter(set1.iterator(), inSet2);
    }

    @Override
    public int size() {
      return Iterators.size(iterator());
    }

    @Override
    public boolean isEmpty() {
      return !iterator().hasNext();
    }

    @Override
    public boolean contains(Object object) {
      return set1.contains(object) && set2.contains(object);
    }

    @Override
    public boolean containsAll(Collection<?> collection) {
      return set1.containsAll(collection) && set2.containsAll(collection);
    }
  };
}
 
Example #30
Source File: LocalhostExternalIpLoader.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static List<String> getIpAddressWebsites() {
    String file = new ResourceUtils(LocalhostExternalIpLoader.class)
            .getResourceAsString("classpath://org/apache/brooklyn/location/geo/external-ip-address-resolvers.txt");
    Iterable<String> lines = Splitter.on('\n')
            .omitEmptyStrings()
            .trimResults()
            .split(file);
    List<String> urls = Lists.newArrayList(Iterables.filter(lines, Predicates.not(StringPredicates.startsWith("#"))));
    Collections.shuffle(urls);
    return urls;
}