下面列出了com.google.common.base.Predicates#or ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testDoesNotLogPasswordsInEnvironmentVariables() {
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.or(
EventPredicates.containsMessage("DB_PASSWORD"),
EventPredicates.containsMessage("mypassword"));
try (LogWatcher watcher = new LogWatcher(loggerNames, logLevel, filter)) {
host.execCommands("mySummary", ImmutableList.of("true"), ImmutableMap.of("DB_PASSWORD", "mypassword"));
watcher.assertHasEventEventually();
Optional<ILoggingEvent> eventWithPasswd = Iterables.tryFind(watcher.getEvents(), EventPredicates.containsMessage("mypassword"));
assertFalse(eventWithPasswd.isPresent(), "event="+eventWithPasswd);
}
}
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;
}
};
}
@VisibleForTesting
public static Predicate<BlueTestResult> filterByState(String state) {
String[] stateAtoms = StringUtils.split(state, ',');
Predicate<BlueTestResult> predicate = Predicates.alwaysFalse();
if (stateAtoms == null || stateAtoms.length == 0) {
throw new BadRequestException("state not provided");
}
for (String stateString : stateAtoms) {
Predicate<BlueTestResult> statePredicate;
try {
if (stateString.startsWith("!")) {
statePredicate = Predicates.not(new StatePredicate(State.valueOf(stateString.toUpperCase().substring(1))));
} else {
statePredicate = new StatePredicate(State.valueOf(stateString.toUpperCase()));
}
} catch (IllegalArgumentException e) {
throw new BadRequestException("bad state " + state, e);
}
predicate = Predicates.or(predicate, statePredicate);
}
return predicate;
}
@VisibleForTesting
public static Predicate<BlueTestResult> filterByStatus(String status) {
String[] statusAtoms = StringUtils.split(status, ',');
Predicate<BlueTestResult> predicate = Predicates.alwaysFalse();
if (statusAtoms == null || statusAtoms.length == 0) {
throw new BadRequestException("status not provided");
}
for (String statusString : statusAtoms) {
Predicate<BlueTestResult> statusPredicate;
try {
if (statusString.startsWith("!")) {
statusPredicate = Predicates.not(new StatusPredicate(Status.valueOf(statusString.toUpperCase().substring(1))));
} else {
statusPredicate = new StatusPredicate(Status.valueOf(statusString.toUpperCase()));
}
} catch (IllegalArgumentException e) {
throw new BadRequestException("bad status " + status, e);
}
predicate = Predicates.or(predicate, statusPredicate );
}
return predicate;
}
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()));
}
}
@Override
public Subscription addBroadcastMessageListener(Set<AddressMatcher> matchers, MessageListener<T> listener) {
final Predicate<Address> p = Predicates.or(matchers);
return addMessageListener((m) -> {
if( AddressMatchers.BROADCAST_MESSAGE_MATCHER.apply(m.getDestination()) && p.apply(m.getSource())) {
listener.onMessage(m);
}
else {
LOGGER.debug("Ignoring message to [{}], does not match [{}]", m.getDestination(), p);
}
});
}
@Test
public void testOr() {
Predicate<String> p = Predicates.<String>or(
StringPredicates.matchesRegex("my.*first"),
StringPredicates.matchesRegex("my.*second"));
List<?> json = MutableList.of(
MutableMap.of("any", MutableList.of(
MutableMap.of("regex", "my.*first"),
MutableMap.of("regex", "my.*second"))));
assertPredJsonBidi(p, json);
}
protected Predicate<AttributeMap> doCreateMatchers() {
if(attributeMatchers.isEmpty()) {
GroovyValidator.error("No valid match conditions were found, this driver won't match any devices");
return Predicates.alwaysFalse();
}
return Predicates.or(attributeMatchers);
}
private SplittingPipeline createResourcesSplittingPipeline() {
ImmutableList.Builder<ModuleSplitSplitter> resourceSplitters = ImmutableList.builder();
ImmutableSet<ResourceId> masterPinnedResourceIds =
apkGenerationConfiguration.getMasterPinnedResourceIds();
ImmutableSet<String> masterPinnedResourceNames =
apkGenerationConfiguration.getMasterPinnedResourceNames();
ImmutableSet<ResourceId> baseManifestReachableResources =
apkGenerationConfiguration.getBaseManifestReachableResources();
if (apkGenerationConfiguration
.getOptimizationDimensions()
.contains(OptimizationDimension.SCREEN_DENSITY)) {
resourceSplitters.add(
new ScreenDensityResourcesSplitter(
bundleVersion,
/* pinWholeResourceToMaster= */ masterPinnedResourceIds::contains,
/* pinLowestBucketOfResourceToMaster= */ baseManifestReachableResources::contains,
PIN_LOWEST_DENSITY_OF_EACH_STYLE_TO_MASTER.enabledForVersion(bundleVersion)));
}
if (apkGenerationConfiguration
.getOptimizationDimensions()
.contains(OptimizationDimension.LANGUAGE)) {
Predicate<ResourceTableEntry> pinLangResourceToMaster =
Predicates.or(
// Resources that are unconditionally in the master split.
entry -> masterPinnedResourceIds.contains(entry.getResourceId()),
entry -> masterPinnedResourceNames.contains(entry.getEntry().getName()),
// Resources reachable from the AndroidManifest.xml should have at least one config
// in the master split (ie. either the default config, or all configs).
entry ->
baseManifestReachableResources.contains(entry.getResourceId())
&& !hasDefaultConfig(entry));
resourceSplitters.add(new LanguageResourcesSplitter(pinLangResourceToMaster));
}
return new SplittingPipeline(resourceSplitters.build());
}
private Predicate<? super Field> buildAnnotationsPredicate() {
Collection<Predicate<? super Field>> predicates = Lists.newArrayList();
for (Class<? extends Annotation> annotationClass : relevantAnnotationClasses) {
predicates.add(ReflectionUtils.withAnnotation(annotationClass));
}
return Predicates.or(predicates);
}
@Provides
@Named(DefaultHubMessageFilterImpl.ADMIN_ONLY_MESSAGES_PROP)
@Singleton
public Predicate<String> getHubAdminOnlyMessages(@Named("hub.bridge.admin.only.messages") String adminOnlyMessages) {
List<Predicate<String>> components = new ArrayList<>();
for (String msg : Splitter.on(',').omitEmptyStrings().trimResults().split(adminOnlyMessages)) {
List<String> parts = Splitter.on(':').splitToList(msg);
switch (parts.size()) {
case 2:
if (parts.get(1).isEmpty() || "*".equals(parts.get(1))) {
final String capMatch = parts.get(0) + ":";
log.warn("adding all commands to admin only list: {}", parts.get(0));
components.add(new Predicate<String>() {
@Override
public boolean apply(String msgType) {
return msgType != null && msgType.startsWith(capMatch);
}
});
} else {
log.warn("adding command to admin only list: {}", msg);
components.add(Predicates.equalTo(msg));
}
break;
default:
log.warn("adding non-conforming command to admin only list: {}", msg);
components.add(Predicates.equalTo(msg));
break;
}
}
switch (components.size()) {
case 0:
return Predicates.alwaysFalse();
case 1:
return components.get(0);
default:
return Predicates.or(components);
}
}
@Test
public void testDoesNotLogStacktraceRepeatedly() throws Exception {
final long time = System.currentTimeMillis();
final String sensorValue = String.format("%s%s%s", Identifiers.makeRandomId(8), time, Identifiers.makeRandomId(8));
// Test case will repeatedly fail until we have finished our logging assertions.
// Then we'll let it complete by setting the sensor.
TestSensor testCase = app.createAndManageChild(EntitySpec.create(TestSensor.class)
.configure(TestSensor.TIMEOUT, Asserts.DEFAULT_LONG_TIMEOUT)
.configure(TestSensor.BACKOFF_TO_PERIOD, Duration.millis(1))
.configure(TestSensor.TARGET_ENTITY, app)
.configure(TestSensor.SENSOR_NAME, STRING_SENSOR.getName())
.configure(TestSensor.ASSERTIONS, newListAssertion("matches", String.format(".*%s.*", time))));
String loggerName = Repeater.class.getName();
ch.qos.logback.classic.Level logLevel = ch.qos.logback.classic.Level.DEBUG;
Predicate<ILoggingEvent> repeatedFailureMsgMatcher = EventPredicates.containsMessage("repeated failure; excluding stacktrace");
Predicate<ILoggingEvent> stacktraceMatcher = EventPredicates.containsExceptionStackLine(TestFrameworkAssertions.class, "checkActualAgainstAssertions");
Predicate<ILoggingEvent> filter = Predicates.or(repeatedFailureMsgMatcher, stacktraceMatcher);
try (LogWatcher watcher = new LogWatcher(loggerName, logLevel, filter)) {
// Invoke async; will let it complete after we see the log messages we expect
Task<?> task = Entities.invokeEffector(app, app, Startable.START, ImmutableMap.of("locations", locs));
// Expect "excluding stacktrace" message at least once
List<ILoggingEvent> repeatedFailureMsgEvents = watcher.assertHasEventEventually(repeatedFailureMsgMatcher);
assertTrue(repeatedFailureMsgEvents.size() > 0, "repeatedFailureMsgEvents="+repeatedFailureMsgEvents.size());
// Expect stacktrace just once
List<ILoggingEvent> stacktraceEvents = watcher.assertHasEventEventually(stacktraceMatcher);
assertEquals(Integer.valueOf(stacktraceEvents.size()), Integer.valueOf(1), "stacktraceEvents="+stacktraceEvents.size());
//Set STRING sensor
app.sensors().set(STRING_SENSOR, sensorValue);
task.get(Asserts.DEFAULT_LONG_TIMEOUT);
assertTestSensorSucceeds(testCase);
// And for good measure (in case we just checked too early last time), check again
// that we didn't get another stacktrace
stacktraceEvents = watcher.getEvents(stacktraceMatcher);
assertEquals(Integer.valueOf(stacktraceEvents.size()), Integer.valueOf(1), "stacktraceEvents="+stacktraceEvents.size());
}
}
public RetryerBuilder<V> retryIfRuntimeException() {
rejectionPredicate = Predicates.or(rejectionPredicate, new ExceptionClassPredicate<V>(RuntimeException.class));
return this;
}
public RetryerBuilder<V> retryIfException(Predicate<Throwable> exceptionPredicate) {
Preconditions.checkNotNull(exceptionPredicate, "exceptionPredicate may not be null");
rejectionPredicate = Predicates.or(rejectionPredicate, new ExceptionPredicate<V>(exceptionPredicate));
return this;
}
public RetryerBuilder<V> retryIfException() {
rejectionPredicate = Predicates.or(rejectionPredicate, new ExceptionClassPredicate<V>(Exception.class));
return this;
}
public RetryerBuilder<V> retryIfRuntimeException() {
rejectionPredicate = Predicates.or(rejectionPredicate, new ExceptionClassPredicate<V>(RuntimeException.class));
return this;
}
public RetryerBuilder<V> retryIfExceptionOfType(Class<? extends Throwable> exceptionClass) {
Preconditions.checkNotNull(exceptionClass, "exceptionClass may not be null");
rejectionPredicate = Predicates.or(rejectionPredicate, new ExceptionClassPredicate<V>(exceptionClass));
return this;
}
/**
* Returns a predicate that returns true for alpha or numeric characters
* is in Character.isLetterOrDigit().
*/
public static Predicate<Character> isLetterOrDigit() {
return Predicates.or(isLetter(), isDigit());
}
/**
* Sugar for creating a new predicate that is the logical disjunction of the given predicates.
*
* @param first
* the first predicate.
* @param second
* the second predicate.
* @param others
* the rest of the predicates. Optional, can be omitted, but when given must not contain {@code null}.
* @return a logical disjunction of the predicates.
*/
public static ProjectTypePredicate or(ProjectTypePredicate first, ProjectTypePredicate second,
ProjectTypePredicate... others) {
return new ProjectTypePredicate(Predicates.or(Lists.asList(first, second, others)));
}
public static Predicate<Integer> invalid() {return Predicates.or(Range.atMost(99), Range.atLeast(600));}