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

The following examples show how to use com.google.common.base.Predicates#or() . 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: 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 2
Source File: BlueTestResultContainerImpl.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@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;
}
 
Example 3
Source File: BlueTestResultContainerImpl.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@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;
}
 
Example 4
Source File: SshMachineLocationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 5
Source File: ModuleSplitter.java    From bundletool with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 6
Source File: AnnotatedClass.java    From valdr-bean-validation with MIT License 5 votes vote down vote up
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);
}
 
Example 7
Source File: GroovyDriverBuilder.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 8
Source File: ConstraintSerializationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 9
Source File: InMemoryMessageBus.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@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);
       }
    });
}
 
Example 10
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 11
Source File: RetryerBuilder.java    From neural with MIT License 4 votes vote down vote up
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;
}
 
Example 12
Source File: TestSensorTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@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());
    }
}
 
Example 13
Source File: RetryerBuilder.java    From neural with MIT License 4 votes vote down vote up
public RetryerBuilder<V> retryIfRuntimeException() {
    rejectionPredicate = Predicates.or(rejectionPredicate, new ExceptionClassPredicate<V>(RuntimeException.class));
    return this;
}
 
Example 14
Source File: RetryerBuilder.java    From neural with MIT License 4 votes vote down vote up
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;
}
 
Example 15
Source File: HubServerModule.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@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);
    }
}
 
Example 16
Source File: RetryerBuilder.java    From neural with MIT License 4 votes vote down vote up
public RetryerBuilder<V> retryIfException() {
    rejectionPredicate = Predicates.or(rejectionPredicate, new ExceptionClassPredicate<V>(Exception.class));
    return this;
}
 
Example 17
Source File: RetryerBuilder.java    From neural with MIT License 4 votes vote down vote up
public RetryerBuilder<V> retryIfRuntimeException() {
    rejectionPredicate = Predicates.or(rejectionPredicate, new ExceptionClassPredicate<V>(RuntimeException.class));
    return this;
}
 
Example 18
Source File: ProjectTypePredicate.java    From n4js with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * 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)));
}
 
Example 19
Source File: TextFilters.java    From Lemur with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 *  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());
}
 
Example 20
Source File: EntityHttpClient.java    From brooklyn-server with Apache License 2.0 votes vote down vote up
public static Predicate<Integer> invalid() {return Predicates.or(Range.atMost(99), Range.atLeast(600));}