Java Code Examples for com.google.common.base.Predicates#alwaysTrue()

The following examples show how to use com.google.common.base.Predicates#alwaysTrue() . 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: BuildLanguageInfoItem.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static AllowedRuleClassInfo getAllowedRuleClasses(
    Collection<RuleClass> ruleClasses, Attribute attr) {
  AllowedRuleClassInfo.Builder info = AllowedRuleClassInfo.newBuilder();
  info.setPolicy(AllowedRuleClassInfo.AllowedRuleClasses.ANY);

  if (attr.isStrictLabelCheckingEnabled()
      && attr.getAllowedRuleClassesPredicate() != Predicates.<RuleClass>alwaysTrue()) {
    info.setPolicy(AllowedRuleClassInfo.AllowedRuleClasses.SPECIFIED);
    Predicate<RuleClass> filter = attr.getAllowedRuleClassesPredicate();
    for (RuleClass otherClass : Iterables.filter(ruleClasses, filter)) {
      if (!isAbstractRule(otherClass)) {
        info.addAllowedRuleClass(otherClass.getName());
      }
    }
  }

  return info.build();
}
 
Example 2
Source File: MachineEntityRebindTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoLogWarningsWhenRebindToMachineEntity() throws Exception {
    String loggerName = InternalFactory.class.getName();
    ch.qos.logback.classic.Level logLevel = ch.qos.logback.classic.Level.WARN;
    Predicate<ILoggingEvent> filter = Predicates.alwaysTrue();
    try (LogWatcher watcher = new LogWatcher(loggerName, logLevel, filter)) {
        origApp.createAndManageChild(EntitySpec.create(MachineEntity.class)
                .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, true));
        origApp.start(ImmutableList.of(origMachine));
        
        rebind();
    
        List<ILoggingEvent> events = watcher.getEvents();
        assertTrue(events.isEmpty(), "events="+events);
    }
}
 
Example 3
Source File: SshMachineLocationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testLogsStdoutAndStderr() {
    RecordingSshTool.setCustomResponse(".*mycommand.*", new CustomResponse(0, "mystdout1\nmystdout2", "mystderr1\nmystderr2"));
    List<String> loggerNames = ImmutableList.of(
            SshMachineLocation.class.getName(), 
            BrooklynLogging.SSH_IO, 
            SshjTool.class.getName());
    ch.qos.logback.classic.Level logLevel = ch.qos.logback.classic.Level.DEBUG;
    Predicate<ILoggingEvent> filter = Predicates.alwaysTrue();
    try (LogWatcher watcher = new LogWatcher(loggerNames, logLevel, filter)) {
        host.execCommands("mySummary", ImmutableList.of("mycommand"));
        
        watcher.assertHasEvent(EventPredicates.containsMessage("[1.2.3.4:22:stdout] mystdout1"));
        watcher.assertHasEvent(EventPredicates.containsMessage("[1.2.3.4:22:stdout] mystdout2"));
        watcher.assertHasEvent(EventPredicates.containsMessage("[1.2.3.4:22:stderr] mystderr1"));
        watcher.assertHasEvent(EventPredicates.containsMessage("[1.2.3.4:22:stderr] mystderr2"));
    }
}
 
Example 4
Source File: Methods.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public MethodDiscoverer build() {
   List<Predicate<Method>> predicates = new ArrayList<Predicate<Method>>();
   if(name != null) {
      predicates.add(new MethodNamed(name));
   }
   for(Class<? extends Annotation> annotation: annotations) {
      predicates.add(new AnnotatedWith(annotation));
   }
   if(predicate != null) {
      predicates.add(predicate);
   }
   
   Predicate<Method> delegate;
   if(predicates.isEmpty()) {
      delegate = Predicates.alwaysTrue();
   }
   else if(predicates.size() == 1) {
      delegate = predicates.get(0);
   }
   else {
      delegate = Predicates.and(predicates);
   }
   return new MethodDiscoverer(delegate);
}
 
Example 5
Source File: TestAddressesAttributeBinder.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveAllOnInit() {
   AddressesAttributeBinder binder = new AddressesAttributeBinder(Predicates.alwaysTrue(), attributeName);
   
   // add addresses that aren't in the context
   Set<String> addresses = ImmutableSet.of(
         Addresses.toObjectAddress("dev", UUID.randomUUID().toString()),
         Addresses.toObjectAddress("dev", UUID.randomUUID().toString()),
         Addresses.toObjectAddress("dev", UUID.randomUUID().toString())
   );
   context.model().setAttribute(attributeName, addresses);
   
   binder.bind(context);
   
   assertEquals(ImmutableSet.of(), context.model().getAttribute(attributeName));
}
 
Example 6
Source File: ApkMatcher.java    From bundletool with Apache License 2.0 6 votes vote down vote up
private Predicate<String> getModuleNameMatcher(Variant variant, Version bundleVersion) {
  if (requestedModuleNames.isPresent()) {
    ImmutableMultimap<String, String> moduleDependenciesMap = buildAdjacencyMap(variant);

    HashSet<String> dependencyModules = new HashSet<>(requestedModuleNames.get());
    for (String requestedModuleName : requestedModuleNames.get()) {
      addModuleDependencies(requestedModuleName, moduleDependenciesMap, dependencyModules);
    }

    if (matchInstant) {
      return dependencyModules::contains;
    } else {
      return Predicates.or(
          buildModulesDeliveredInstallTime(variant, bundleVersion)::contains,
          dependencyModules::contains);
    }
  } else {
    if (matchInstant) {
      // For instant matching, by default all instant modules are matched.
      return Predicates.alwaysTrue();
    } else {
      // For conventional matching, only install-time modules are matched.
      return buildModulesDeliveredInstallTime(variant, bundleVersion)::contains;
    }
  }
}
 
Example 7
Source File: ConstraintSerialization.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private <T> Predicate<?> and(Iterable<Predicate<? super T>> preds) {
    Iterator<Predicate<? super T>> pi = preds.iterator();
    if (!pi.hasNext()) return Predicates.alwaysTrue();
    Predicate<?> first = pi.next();
    if (!pi.hasNext()) return first;
    return Predicates.and(preds);
}
 
Example 8
Source File: ContextQueryTemplate.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public Condition generate(Map<String, Object> values) {
	Preconditions.checkNotNull(getCondition(), "Must specify a delegate condition");
	Preconditions.checkNotNull(matcher, "Must specify a matcher");
	
	Predicate<Model> selectorPred = Predicates.alwaysTrue();
	if(selector != null) {
		selectorPred = selector.apply(values);
	}
	Predicate<Model> matcherPred = matcher.apply(values);
	Condition condition = getCondition().generate(values);
	
	return new MatcherFilter(condition, new ModelPredicateMatcher(selectorPred, matcherPred));
}
 
Example 9
Source File: QueryChangeTemplate.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public Condition generate(Map<String, Object> values) {
   Preconditions.checkNotNull(condition);

   Predicate<Model> conditionPred = Predicates.alwaysTrue();
   Predicate<Model> queryPred = Predicates.alwaysTrue();
   
   if(query!=null){
      queryPred = query.apply(values);
   }
   conditionPred = condition.apply(values);
   return new QueryChangeTrigger(queryPred,conditionPred);
}
 
Example 10
Source File: ReadOnlySchedulerImpl.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
private Map<IJobKey, IJobConfiguration> getJobs(
    Optional<String> ownerRole,
    Multimap<IJobKey, IScheduledTask> tasks) {

  // We need to synthesize the JobConfiguration from the the current tasks because the
  // ImmediateJobManager doesn't store jobs directly and ImmediateJobManager#getJobs always
  // returns an empty Collection.
  Map<IJobKey, IJobConfiguration> jobs = Maps.newHashMap();

  jobs.putAll(Maps.transformEntries(tasks.asMap(),
      (jobKey, tasks1) -> {

        // Pick the latest transitioned task for each immediate job since the job can be in the
        // middle of an update or some shards have been selectively created.
        TaskConfig mostRecentTaskConfig =
            Tasks.getLatestActiveTask(tasks1).getAssignedTask().getTask().newBuilder();

        return IJobConfiguration.build(new JobConfiguration()
            .setKey(jobKey.newBuilder())
            .setOwner(mostRecentTaskConfig.getOwner())
            .setTaskConfig(mostRecentTaskConfig)
            .setInstanceCount(tasks1.size()));
      }));

  // Get cron jobs directly from the manager. Do this after querying the task store so the real
  // template JobConfiguration for a cron job will overwrite the synthesized one that could have
  // been created above.
  Predicate<IJobConfiguration> configFilter = ownerRole.isPresent()
      ? Predicates.compose(Predicates.equalTo(ownerRole.get()), JobKeys::getRole)
      : Predicates.alwaysTrue();
  jobs.putAll(Maps.uniqueIndex(
      FluentIterable.from(Storage.Util.fetchCronJobs(storage)).filter(configFilter),
      IJobConfiguration::getKey));

  return jobs;
}
 
Example 11
Source File: TestAddressesAttributeBinder.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddThenRemove() {
   AddressesAttributeBinder binder = new AddressesAttributeBinder(Predicates.alwaysTrue(), attributeName);
   binder.bind(context);
   
   assertEquals(ImmutableSet.of(), context.model().getAttribute(attributeName));
   
   Set<String> addresses = addAll();
   assertEquals(addresses, context.model().getAttribute(attributeName));
}
 
Example 12
Source File: LinkableListFilterFactory.java    From buck with Apache License 2.0 5 votes vote down vote up
/** Creates a predicate to filter resources that will be included in an apple_bundle. */
@Nonnull
public static Predicate<BuildTarget> resourcePredicateFrom(
    CxxBuckConfig cxxBuckConfig,
    Optional<String> resourceGroup,
    Optional<ImmutableList<CxxLinkGroupMapping>> mapping,
    TargetGraph graph) {
  if (!cxxBuckConfig.getLinkGroupsEnabled() || !mapping.isPresent()) {
    return Predicates.alwaysTrue();
  }

  Map<BuildTarget, String> targetToGroupMap =
      getCachedBuildTargetToLinkGroupMap(mapping.get(), graph);

  return (BuildTarget target) -> {
    if (!targetToGroupMap.containsKey(target)) {
      // Ungrouped targets belong to the unlabelled bundle (by def)
      return !resourceGroup.isPresent();
    }

    String targetGroup = targetToGroupMap.get(target);
    if (targetGroup.equals(MATCH_ALL_LINK_GROUP_NAME)) {
      return true;
    }

    return (resourceGroup.map(group -> group.equals(targetGroup)).orElse(false)).booleanValue();
  };
}
 
Example 13
Source File: JdtBasedSimpleTypeScopeTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
	projectProvider = new MockJavaProjectProvider();
	factory = new JdtTypeProviderFactory(projectProvider);
	resourceSet = new ResourceSetImpl();
	typeScope = new JdtBasedSimpleTypeScope(factory.createTypeProvider(resourceSet), new IQualifiedNameConverter.DefaultImpl(),Predicates.<IEObjectDescription>alwaysTrue());
}
 
Example 14
Source File: TestForEachModelAction.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleMatchingModels() {
   mockAction.execute(context);
   EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
      @Override
      public Object answer() throws Throwable {
         // verify that the address has been changed
         assertEquals(model1.getAddress(), context.getVariable(targetVariable));
         return null;
      }
   });
   mockAction.execute(context);
   EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
      @Override
      public Object answer() throws Throwable {
         // verify that the address has been changed
         assertEquals(model2.getAddress(), context.getVariable(targetVariable));
         return null;
      }
   });
   mockAction.execute(context);
   EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
      @Override
      public Object answer() throws Throwable {
         // verify that the address has been changed
         assertEquals(model3.getAddress(), context.getVariable(targetVariable));
         return null;
      }
   });
   
   EasyMock.replay(mockAction);
   
   ForEachModelAction selector = new ForEachModelAction(mockAction, Predicates.<Model>alwaysTrue(), "address");
   selector.execute(context);
   assertNull(context.getVariable(targetVariable));
   
   EasyMock.verify(mockAction);
}
 
Example 15
Source File: AddressSelectorWrapper.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
VerifierBuilder resolveAllUriAsync_ForceRefresh(boolean forceRefresh) {
    methodName(resolveAllUriAsync);

    Condition alwaysTrue = new Condition(Predicates.alwaysTrue(), "no condition");
    Condition forceRefreshCond = new Condition(Predicates.equalTo(forceRefresh), String.format("%b (forceRefresh)", forceRefresh));

    resolveAllUriAsync(alwaysTrue, alwaysTrue, forceRefreshCond);
    return this;
}
 
Example 16
Source File: CurrentAndFlatListHolder.java    From celerio with Apache License 2.0 5 votes vote down vote up
public CurrentAndFlatListHolder(H node, ListGetter<T, H> listGetter) {
    notNull(node, "the node must not be null");
    notNull(listGetter, "the listGetter must not be null");
    this.node = node;
    this.listGetter = listGetter;
    this.predicate = Predicates.<T>alwaysTrue();
}
 
Example 17
Source File: ClasspathBasedTypeScopeTest.java    From xtext-extras with Eclipse Public License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
	factory = new ClasspathTypeProviderFactory(getClass().getClassLoader(), null);
	resourceSet = new ResourceSetImpl();
	typeScope = new ClasspathBasedTypeScope(factory.createTypeProvider(resourceSet), new IQualifiedNameConverter.DefaultImpl(),Predicates.<IEObjectDescription>alwaysTrue());
}
 
Example 18
Source File: SetAttributeActionConfig.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Override
public StatefulAction createAction(Map<String, Object> variables) {
   Preconditions.checkState(address != null, "Must specify an address");
   Preconditions.checkState(attributeName != null, "Must specify an attributeName");
   Preconditions.checkState(attributeValue != null, "Must specify an attributeValue");
   Preconditions.checkState(attributeType != null, "Must specify an attributeType");
   SetAndRestore action = null;
   if(reevaluateCondition) {
 	  action = new ConditionalSetAndRestore(
         FunctionFactory.toActionContextFunction(
               TemplatedValue.transform(
                     FunctionFactory.INSTANCE.getToAddress(), 
                     address.toTemplate()
               )
         ),
         FunctionFactory.INSTANCE.createConstant(attributeName),
         FunctionFactory.toActionContextFunction(
               TemplatedValue.transform(
                     FunctionFactory.createCoerceFunction(attributeType), 
                     attributeValue.toTemplate()
               )
         ),
         unit.toMillis(duration),
         conditionQuery==null?null:FunctionFactory.toModelPredicate(this.conditionQuery.toTemplate(), variables)
      );
   }else {    	  
 	  action = new SetAndRestore(
 		         FunctionFactory.toActionContextFunction(
 		               TemplatedValue.transform(
 		                     FunctionFactory.INSTANCE.getToAddress(), 
 		                     address.toTemplate()
 		               )
 		         ),
 		         FunctionFactory.INSTANCE.createConstant(attributeName),
 		         FunctionFactory.toActionContextFunction(
 		               TemplatedValue.transform(
 		                     FunctionFactory.createCoerceFunction(attributeType), 
 		                     attributeValue.toTemplate()
 		               )
 		         ),
 		         unit.toMillis(duration),
 		         conditionQuery==null?Predicates.alwaysTrue():FunctionFactory.toModelPredicate(this.conditionQuery.toTemplate(), variables)
 		      );
   }
   return action;
}
 
Example 19
Source File: ListTeamsCommand.java    From UHC with MIT License 4 votes vote down vote up
@Override
protected boolean runCommand(CommandSender sender, OptionSet options) {
    final int page = pageSpec.value(options);
    final boolean emptyOnly = options.has(emptyOnlySpec);
    final boolean showAll = options.has(showAllSpec);

    if (showAll && emptyOnly) {
        sender.sendMessage(ChatColor.RED + "You must provide -e OR -a, you cannot supply both");
        return true;
    }

    final Predicate<Team> predicate;
    final String type;

    if (emptyOnly) {
        type = "(empty teams)";
        predicate = Predicates.not(FunctionalUtil.TEAMS_WITH_PLAYERS);
    } else if (showAll) {
        type = "(all teams)";
        predicate = Predicates.alwaysTrue();
    } else {
        type = "(with players)";
        predicate = FunctionalUtil.TEAMS_WITH_PLAYERS;
    }

    final List<Team> teams = Lists.newArrayList(Iterables.filter(teamModule.getTeams().values(), predicate));

    if (teams.size() == 0) {
        sender.sendMessage(ChatColor.RED + "No results found for query " + type);
        return true;
    }

    final List<List<Team>> partitioned = Lists.partition(teams, COUNT_PER_PAGE);

    if (page > partitioned.size()) {
        sender.sendMessage(ChatColor.RED + "Page " + page + " does not exist");
        return true;
    }

    final List<Team> pageItems = partitioned.get(page - 1);

    final Map<String, Object> context = ImmutableMap.<String, Object>builder()
            .put("page", page)
            .put("pages", partitioned.size())
            .put("type", type)
            .put("count", pageItems.size())
            .put("teams", teams.size())
            .put("multiple", partitioned.size() > 1)
            .build();

    sender.sendMessage(messages.evalTemplate("header", context));

    final Joiner joiner = Joiner.on(", ");
    for (final Team team : pageItems) {
        final String memberString;
        final Set<OfflinePlayer> members = team.getPlayers();

        if (members.size() == 0) {
            memberString = NO_MEMBERS;
        } else {
            memberString = joiner.join(Iterables.transform(team.getPlayers(), FunctionalUtil.PLAYER_NAME_FETCHER));
        }

        sender.sendMessage(
                String.format(FORMAT, team.getPrefix() + team.getDisplayName(), team.getName(), memberString)
        );
    }

    return true;
}
 
Example 20
Source File: CandidacyProcessDA.java    From fenixedu-academic with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected Predicate<IndividualCandidacyProcess> getChildProcessSelectionPredicate(final CandidacyProcess process,
        HttpServletRequest request) {
    return Predicates.alwaysTrue();
}