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 Project: enderutilities   Author: maruohon   File: RenderEventHandler.java    License: 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 #2
Source Project: brooklyn-library   Author: apache   File: RiakClusterImpl.java    License: 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 Project: incubator-heron   Author: apache   File: CppCheckstyle.java    License: 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 #4
Source Project: brooklyn-server   Author: apache   File: ServiceFailureDetectorStabilizationTest.java    License: 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 #5
Source Project: brooklyn-server   Author: apache   File: UsageResource.java    License: 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 #6
Source Project: brooklyn-server   Author: apache   File: ScheduledPolicyRebindTest.java    License: 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 #7
Source Project: brooklyn-library   Author: apache   File: MongoDBClientSshDriver.java    License: 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 #8
Source Project: retry   Author: houbb   File: ExponentialBackoff.java    License: 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 #9
Source Project: arcusplatform   Author: arcus-smart-home   File: TestThresholdTrigger.java    License: 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 Project: arcusplatform   Author: arcus-smart-home   File: GroovyDriverBuilder.java    License: 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 #11
Source Project: neural   Author: yu120   File: RetryerBuilderTest.java    License: 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 #12
Source Project: brooklyn-server   Author: apache   File: HaPolicyRebindTest.java    License: 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 #13
Source Project: arcusplatform   Author: arcus-smart-home   File: AnnotatedSubsystemFactory.java    License: 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 #14
Source Project: brooklyn-server   Author: apache   File: CollectionFunctionalsTest.java    License: 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 #15
Source Project: bazel   Author: bazelbuild   File: GenQuery.java    License: 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 #16
Source Project: dagger2-sample   Author: yongjhih   File: BindingGraphValidator.java    License: 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 #17
Source Project: arcusplatform   Author: arcus-smart-home   File: PanicAlarm.java    License: 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 #18
Source Project: nexus-public   Author: sonatype   File: RealmApiResource.java    License: 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 Project: HiveRunner   Author: klarna   File: HiveRunnerExtension.java    License: Apache License 2.0 5 votes vote down vote up
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));
  }
}
 
Example #20
Source Project: buck   Author: facebook   File: CopyNativeLibrariesTest.java    License: Apache License 2.0 5 votes vote down vote up
@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"))));
}
 
Example #21
Source Project: presto   Author: prestosql   File: TestEffectivePredicateExtractor.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #22
Source Project: neural   Author: yu120   File: RetryerBuilderTest.java    License: MIT License 5 votes vote down vote up
@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());
}
 
Example #23
Source Project: brooklyn-server   Author: apache   File: CatalogScanTest.java    License: Apache License 2.0 5 votes vote down vote up
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()));
}
 
Example #24
Source Project: xtext-core   Author: eclipse   File: ResourceDescriptionsBasedContainerTest.java    License: 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 #25
Source Project: brooklyn-server   Author: apache   File: ArchiveBuilderTest.java    License: 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 #26
Source Project: brooklyn-server   Author: apache   File: CatalogResource.java    License: 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 #27
Source Project: tutorials   Author: eugenp   File: GuavaFilterTransformCollectionsUnitTest.java    License: 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 #28
Source Project: brooklyn-server   Author: apache   File: ScheduledPolicyRebindTest.java    License: 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 #29
Source Project: tutorials   Author: eugenp   File: GuavaFunctionalExamplesUnitTest.java    License: 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 #30
Source Project: arcusplatform   Author: arcus-smart-home   File: PlatformDispatcherFactory.java    License: 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()));
   }
}