下面列出了com.google.common.base.Predicates#alwaysTrue ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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();
}
@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);
}
}
@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"));
}
}
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);
}
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;
}
}
}
@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));
}
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();
}
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;
}
@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);
}
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);
}
@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());
}
/** 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();
};
}
@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));
}
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;
}
@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);
}
@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));
}
@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());
}
@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;
}
@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;
}
protected Predicate<IndividualCandidacyProcess> getChildProcessSelectionPredicate(final CandidacyProcess process,
HttpServletRequest request) {
return Predicates.alwaysTrue();
}