Java Code Examples for com.google.common.base.Predicate

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project AdServing, under directory /modules/db/src/main/java/net/mad/ads/db/condition/impl/.

Source file: DistanceCondition.java

  29 
vote

@Override public Predicate<AdDefinition> getFilterPredicate(final AdRequest request){
  Predicate<AdDefinition> predicate=new Predicate<AdDefinition>(){
    @Override public boolean apply(    AdDefinition type){
      if (!type.hasConditionDefinition(ConditionDefinitions.DISTANCE)) {
        return true;
      }
      DistanceConditionDefinition dcdef=(DistanceConditionDefinition)type.getConditionDefinition(ConditionDefinitions.DISTANCE);
      if (request.getGeoLocation() == null) {
        return true;
      }
      LatLng bannerPOS=new LatLng(dcdef.getGeoLocation().getLatitude(),dcdef.getGeoLocation().getLongitude());
      LatLng requestPOS=new LatLng(request.getGeoLocation().getLatitude(),request.getGeoLocation().getLongitude());
      double distance=LatLngTool.distance(bannerPOS,requestPOS,LengthUnit.KILOMETER);
      if (dcdef.getGeoRadius() >= distance) {
        return true;
      }
      return false;
    }
  }
;
  return predicate;
}
 

Example 2

From project agit, under directory /agit/src/main/java/com/madgag/android/notifications/.

Source file: StatusBarNotificationStyles.java

  29 
vote

private void discoverStyle(){
  try {
    Notification n=new Notification();
    n.setLatestEventInfo(context,TEXT_SEARCH_TITLE,TEXT_SEARCH_TEXT,null);
    new NotificationViewSearcher(n,context,new Predicate<View>(){
      public boolean apply(      View view){
        if (view instanceof TextView) {
          TextView tv=(TextView)view;
          if (tv.getText().toString().startsWith(TEXT_SEARCH_PREFIX)) {
            int textColour=tv.getTextColors().getDefaultColor();
            TextAppearance appearance=new TextAppearance(textColour,tv.getTextSize() / displayMetrics.scaledDensity);
            if (TEXT_SEARCH_TEXT.equals(tv.getText().toString())) {
              textAppearance=appearance;
            }
 else {
              titleAppearance=appearance;
            }
            return !needToSearch();
          }
        }
        return false;
      }
    }
).search();
  }
 catch (  Exception e) {
    if (titleAppearance == null)     titleAppearance=new TextAppearance(black,12);
    if (textAppearance == null)     textAppearance=new TextAppearance(black,11);
  }
}
 

Example 3

From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/helper/.

Source file: SelectSensorHelper.java

  29 
vote

private int selectedSensorIndex(List<Sensor> sensors){
  return indexOf(sensors,new Predicate<Sensor>(){
    @Override public boolean apply(    @Nullable Sensor input){
      return input.equals(sensorManager.getVisibleSensor());
    }
  }
);
}
 

Example 4

From project airlift, under directory /discovery/src/main/java/io/airlift/discovery/client/.

Source file: ServiceInventory.java

  29 
vote

public Iterable<ServiceDescriptor> getServiceDescriptors(final String type){
  return Iterables.filter(getServiceDescriptors(),new Predicate<ServiceDescriptor>(){
    @Override public boolean apply(    ServiceDescriptor serviceDescriptor){
      return serviceDescriptor.getType().equals(type);
    }
  }
);
}
 

Example 5

From project akubra, under directory /akubra-map/src/main/java/org/akubraproject/map/.

Source file: IdMappingBlobStoreConnection.java

  29 
vote

@Override public Iterator<URI> listBlobIds(final String filterPrefix) throws IOException {
  String intPrefix=null;
  Iterator<URI> intIterator;
  if (filterPrefix == null) {
    intIterator=delegate.listBlobIds(null);
  }
 else {
    intPrefix=mapper.getInternalPrefix(filterPrefix);
    intIterator=delegate.listBlobIds(intPrefix);
  }
  Iterator<URI> extIterator=Iterators.transform(intIterator,new Function<URI,URI>(){
    public URI apply(    URI uri){
      return mapper.getExternalId(uri);
    }
  }
);
  if (filterPrefix != null && intPrefix == null) {
    return Iterators.filter(extIterator,new Predicate<URI>(){
      public boolean apply(      URI uri){
        return uri.toString().startsWith(filterPrefix);
      }
    }
);
  }
 else {
    return extIterator;
  }
}
 

Example 6

From project android_external_guava, under directory /src/com/google/common/collect/.

Source file: Collections2.java

  29 
vote

/** 
 * Returns the elements of  {@code unfiltered} that satisfy a predicate. Thereturned collection is a live view of  {@code unfiltered}; changes to one affect the other. <p>The resulting collection's iterator does not support  {@code remove()}, but all other collection methods are supported. The collection's {@code add()} and {@code addAll()} methods throw an{@link IllegalArgumentException} if an element that doesn't satisfy thepredicate is provided. When methods such as  {@code removeAll()} and{@code clear()} are called on the filtered collection, only elements thatsatisfy the filter will be removed from the underlying collection. <p>The returned collection isn't threadsafe or serializable, even if {@code unfiltered} is.<p>Many of the filtered collection's methods, such as  {@code size()}, iterate across every element in the underlying collection and determine which elements satisfy the filter. When a live view is <i>not</i> needed, it may be faster to copy  {@code Iterables.filter(unfiltered, predicate)}and use the copy.
 */
public static <E>Collection<E> filter(Collection<E> unfiltered,Predicate<? super E> predicate){
  if (unfiltered instanceof FilteredCollection) {
    return ((FilteredCollection<E>)unfiltered).createCombined(predicate);
  }
  return new FilteredCollection<E>(checkNotNull(unfiltered),checkNotNull(predicate));
}
 

Example 7

From project annotare2, under directory /app/om/src/main/java/uk/ac/ebi/fg/annotare2/dao/dummy/.

Source file: SubmissionDaoDummy.java

  29 
vote

public List<Submission> getSubmissionsByType(User user,final SubmissionType type){
  return getSubmissions(user,new Predicate<Submission>(){
    public boolean apply(    @Nullable Submission input){
      return input.getType().equals(type);
    }
  }
);
}
 

Example 8

From project appdriver, under directory /android/src/com/google/android/testing/nativedriver/server/.

Source file: ElementFinder.java

  29 
vote

@Override public List<WebElement> findElementsById(String using){
  Preconditions.checkNotNull(using);
  Predicate<AndroidNativeElement> filter;
  if (idType(using) == IdType.LITERAL) {
    filter=new ByLiteralIdFilterCondition(using);
  }
 else {
    Integer androidId=parseAsAndroidId(using);
    if (androidId == null) {
      return ImmutableList.of();
    }
    filter=new ByAndroidIdFilterCondition(using,androidId);
  }
  return addElementsFromHierarchy(Lists.<WebElement>newArrayList(),scope.getChildren(),filter,Integer.MAX_VALUE);
}
 

Example 9

From project arquillian-extension-warp, under directory /extension/phaser-ftest/src/test/java/org/jboss/arquillian/warp/extension/phaser/ftest/lifecycle/.

Source file: TestPhaserLifecycle.java

  29 
vote

@Test @RunAsClient public void test(){
  ExecuteAllPhases executed=Warp.execute(new ClientAction(){
    public void action(){
      browser.navigate().to(contextPath + "index.jsf");
    }
  }
).verify(new ExecuteAllPhases());
  assertFalse(executed.isPostback());
  ExecuteAllPhases.verifyExecutedPhases(executed);
  executed=Warp.execute(new ClientAction(){
    public void action(){
      WebElement nameInput=browser.findElement(By.id("helloWorldJsf:nameInput"));
      nameInput.sendKeys("X");
      new WebDriverWait(browser,5).until(new Predicate<WebDriver>(){
        @Override public boolean apply(        WebDriver browser){
          WebElement output=browser.findElement(By.id("helloWorldJsf:output"));
          try {
            return output.getText().contains("JohnX");
          }
 catch (          StaleElementReferenceException e) {
            return false;
          }
        }
      }
);
    }
  }
).verify(new ExecuteAllPhases());
  assertTrue(executed.isPostback());
  ExecuteAllPhases.verifyExecutedPhases(executed);
}
 

Example 10

From project artifactory-plugin, under directory /src/main/java/org/jfrog/hudson/.

Source file: ArtifactoryRedeployPublisher.java

  29 
vote

private boolean isBuildFromM2ReleasePlugin(AbstractBuild<?,?> build){
  List<Cause> causes=build.getCauses();
  return !causes.isEmpty() && Iterables.any(causes,new Predicate<Cause>(){
    public boolean apply(    Cause input){
      return "org.jvnet.hudson.plugins.m2release.ReleaseCause".equals(input.getClass().getName());
    }
  }
);
}
 

Example 11

From project astyanax, under directory /src/main/java/com/netflix/astyanax/impl/.

Source file: FilteringHostSupplier.java

  29 
vote

@Override public Map<BigInteger,List<Host>> get(){
  Map<BigInteger,List<Host>> filterList=Maps.newHashMap();
  Map<BigInteger,List<Host>> sourceList;
  try {
    filterList=filterSupplier.get();
    sourceList=sourceSupplier.get();
  }
 catch (  RuntimeException e) {
    if (filterList != null)     return filterList;
    throw e;
  }
  final Map<String,Host> lookup=Maps.newHashMap();
  for (  Entry<BigInteger,List<Host>> token : filterList.entrySet()) {
    for (    Host host : token.getValue()) {
      lookup.put(host.getIpAddress(),host);
      for (      String addr : host.getAlternateIpAddresses()) {
        lookup.put(addr,host);
      }
    }
  }
  Map<BigInteger,List<Host>> response=Maps.newHashMap();
  for (  Entry<BigInteger,List<Host>> token : sourceList.entrySet()) {
    response.put(token.getKey(),Lists.newArrayList(Collections2.transform(Collections2.filter(token.getValue(),new Predicate<Host>(){
      @Override public boolean apply(      Host host){
        return lookup.containsKey(host.getIpAddress());
      }
    }
),new Function<Host,Host>(){
      @Override public Host apply(      Host host){
        return lookup.get(host.getIpAddress());
      }
    }
)));
  }
  return response;
}
 

Example 12

From project atlas, under directory /src/main/java/com/ning/atlas/base/.

Source file: MorePredicates.java

  29 
vote

public static <T>Predicate<T> beanPropertyEquals(final String name,final Object value){
  return new Predicate<T>(){
    public boolean apply(    T input){
      try {
        Method m=input.getClass().getMethod("get" + name.substring(0,1).toUpperCase() + name.substring(1,name.length()));
        return m.invoke(input).equals(value);
      }
 catch (      NoSuchMethodException e) {
        return false;
      }
catch (      InvocationTargetException e) {
        throw new IllegalArgumentException(e);
      }
catch (      IllegalAccessException e) {
        throw new IllegalArgumentException(e);
      }
    }
  }
;
}
 

Example 13

From project atlassian-rest-cli, under directory /rest-cli-runner/src/main/java/com/galeoconsulting/leonardinius/api/impl/.

Source file: ServletVelocityHelperImpl.java

  29 
vote

@Override public SessionBean getSessionBean(final String sessionId){
  if (StringUtils.isBlank(sessionId)) {
    return null;
  }
  Iterable<SessionBean> iterable=Iterables.filter(getAllSessionBeans(),new Predicate<SessionBean>(){
    @Override public boolean apply(    @Nullable SessionBean input){
      return StringUtils.equals(sessionId,input.getSessionId());
    }
  }
);
  return iterable.iterator().hasNext() ? iterable.iterator().next() : null;
}
 

Example 14

From project bamboo-sonar-integration, under directory /bamboo-sonar-common/src/main/java/com/marvelution/bamboo/plugins/sonar/common/predicates/.

Source file: SonarPredicates.java

  29 
vote

/** 
 * Get the Has Sonar Tasks  {@link Predicate}
 * @return the {@link Predicate}
 */
public static Predicate<Buildable> hasSonarTasks(){
  return new Predicate<Buildable>(){
    @Override public boolean apply(    Buildable buildable){
      return Iterables.any(buildable.getBuildDefinition().getTaskDefinitions(),isSonarTask());
    }
  }
;
}
 

Example 15

From project Betfair-Trickle, under directory /src/main/java/uk/co/onehp/trickle/controller/domain/.

Source file: DomainControllerImpl.java

  29 
vote

private List<Bet> betsFromTodayOrLater(List<Bet> bets){
  List<Bet> filteredBets;
  filteredBets=Lists.newArrayList(Iterables.filter(bets,new Predicate<Bet>(){
    @Override public boolean apply(    Bet bet){
      return bet.getHorse().getRace().getStartTime().isAfter(new LocalDateTime().withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0));
    }
  }
));
  return filteredBets;
}
 

Example 16

From project BHT-FPA, under directory /mailer-common/de.bht.fpa.mail.common/src/de/bht/fpa/mail/s000000/common/mail/testdata/.

Source file: FileSystemTestDataProvider.java

  29 
vote

private Predicate<Message> byNonNullEntries(){
  return new Predicate<Message>(){
    @Override public boolean apply(    Message input){
      return input != null;
    }
  }
;
}
 

Example 17

From project build-info, under directory /build-info-api/src/main/java/org/jfrog/build/api/builder/.

Source file: BuildInfoMavenBuilder.java

  29 
vote

private Module findModule(final String moduleKey){
  return Iterables.find(modules,new Predicate<Module>(){
    public boolean apply(    Module input){
      return input.getId().equals(moduleKey);
    }
  }
,null);
}
 

Example 18

From project bulk-builder-plugin, under directory /src/main/java/org/jenkinsci/plugins/bulkbuilder/model/.

Source file: Builder.java

  29 
vote

/** 
 * Build Jenkins projects
 */
protected int build(ArrayList filters){
  int i=0;
  Predicate<AbstractProject<?,?>> compositePredicate=Predicates.and(filters);
  List<AbstractProject<?,?>> projects=getProjects(this.view);
  Iterable<AbstractProject<?,?>> targetProjects=Iterables.filter(projects,compositePredicate);
  for (  AbstractProject<?,?> project : targetProjects) {
    LOGGER.log(Level.FINE,"Scheduling build for job '" + project.getDisplayName() + "'");
    if (performBuildProject(project)) {
      i++;
    }
  }
  return i;
}
 

Example 19

From project c10n, under directory /tools/src/main/java/c10n/tools/search/.

Source file: DefaultC10NInterfaceSearch.java

  29 
vote

@Override public Set<Class<?>> find(String packagePrefix,Class<? extends Annotation> annotationClass){
  final Predicate<String> filter=new FilterBuilder.Include(FilterBuilder.prefix(packagePrefix));
  Reflections reflections=new Reflections(new ConfigurationBuilder().setUrls(cp).filterInputsBy(filter).setScanners(new TypeAnnotationsScanner().filterResultsBy(filter),new SubTypesScanner().filterResultsBy(filter)));
  Set<String> types=reflections.getStore().getTypesAnnotatedWith(annotationClass.getName());
  URL[] urls=cp.toArray(new URL[cp.size()]);
  return ImmutableSet.copyOf(Reflections.forNames(types,new URLClassLoader(urls)));
}
 

Example 20

From project cdk, under directory /generator/src/main/java/org/richfaces/cdk/apt/.

Source file: TaskFactoryImpl.java

  29 
vote

private StandardJavaFileManager getFileManager(){
  if (fileManager == null) {
    fileManager=getJavaCompiler().getStandardFileManager(new DiagnosticListenerImplementation(log,locale),locale,charset);
    try {
      fileManager.setLocation(StandardLocation.CLASS_PATH,classPathLoader.getFiles());
      Iterable<File> outputFolders=outputFolder.getFolders();
      if (null != outputFolders) {
        Iterable<File> existedFolders=Iterables.filter(outputFolders,new Predicate<File>(){
          @Override public boolean apply(          File input){
            return input.exists();
          }
        }
);
        if (existedFolders.iterator().hasNext()) {
          fileManager.setLocation(StandardLocation.SOURCE_OUTPUT,outputFolders);
        }
      }
      fileManager.setLocation(StandardLocation.SOURCE_PATH,sourceFolders.getFolders());
    }
 catch (    IOException e) {
      throw new CdkException("Cannot configure JavaFileManager for compilator",e);
    }
  }
  return fileManager;
}
 

Example 21

From project Cinch, under directory /src/com/palantir/ptoss/cinch/core/.

Source file: BindingContext.java

  29 
vote

/** 
 * Returns the list of  {@link ModelUpdate} types in this binding context.
 * @param modelClass
 * @return the of {@link Class}es that implement  {@link ModelUpdate} in this binding context.
 */
public static List<Class<?>> findModelUpdateClass(final BindableModel modelClass){
  List<Class<?>> classes=Reflections.getTypesOfTypeForClassHierarchy(modelClass.getClass(),ModelUpdate.class);
  Predicate<Class<?>> isEnum=new Predicate<Class<?>>(){
    public boolean apply(    final Class<?> input){
      return input.isEnum();
    }
  }
;
  classes=Lists.newArrayList(Iterables.filter(classes,isEnum));
  for (  Class<?> iface : modelClass.getClass().getInterfaces()) {
    classes.addAll(Lists.newArrayList(Iterables.filter(Reflections.getTypesOfTypeForClassHierarchy(iface,ModelUpdate.class),isEnum)));
  }
  if (classes.size() == 0) {
    return null;
  }
  return classes;
}
 

Example 22

From project CIShell, under directory /core/org.cishell.utility.swt/src/org/cishell/utility/swt/model/field/validation/.

Source file: Utilities.java

  29 
vote

public static <T>Collection<FieldValidator<T>> allFieldValidatorsExcept(Collection<FieldValidator<T>> allValidators,final Collection<FieldValidator<T>> except){
  return Collections2.filter(allValidators,new Predicate<FieldValidator<T>>(){
    public boolean apply(    FieldValidator<T> input){
      return !except.contains(input);
    }
  }
);
}
 

Example 23

From project closure-templates, under directory /java/src/com/google/template/soy/jssrc/internal/.

Source file: GenerateSoyUtilsEscapingDirectiveCode.java

  29 
vote

/** 
 * Called reflectively when Ant sees  {@code <jsdefined>}.
 */
public void addConfiguredJsdefined(FunctionNamePredicate p){
  final Pattern namePattern=p.namePattern;
  if (namePattern == null) {
    throw new IllegalStateException("Please specify a pattern attribute for <jsdefined>");
  }
  availableJavaScript=Predicates.or(availableJavaScript,new Predicate<String>(){
    public boolean apply(    String javaScriptFunctionName){
      return namePattern.matcher(javaScriptFunctionName).matches();
    }
  }
);
}
 

Example 24

From project cloud-management, under directory /src/main/java/com/proofpoint/cloudmanagement/service/.

Source file: InstancesResource.java

  29 
vote

@POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createInstance(final InstanceCreationRequest request,@Context UriInfo uriInfo){
  checkNotNull(request);
  checkNotNull(uriInfo);
  if (!instanceConnectorMap.containsKey(request.getProvider())) {
    return Response.status(Status.BAD_REQUEST).entity(new InstanceCreationFailedResponse(request,PROVIDER_UNAVAILABLE)).build();
  }
  if (instanceConnectorMap.get(request.getProvider()).getLocation(request.getLocation()) == null) {
    return Response.status(Status.BAD_REQUEST).entity(new InstanceCreationFailedResponse(request,LOCATION_UNAVAILABLE)).build();
  }
  if (!Iterables.any(instanceConnectorMap.get(request.getProvider()).getLocation(request.getLocation()).getAvailableSizes(),new Predicate<Size>(){
    @Override public boolean apply(    @Nullable Size size){
      return size.getSize().equals(request.getSize());
    }
  }
)) {
    return Response.status(Status.BAD_REQUEST).entity(new InstanceCreationFailedResponse(request,SIZE_UNAVAILABLE)).build();
  }
  String instanceId=instanceConnectorMap.get(request.getProvider()).createInstance(request.getSize(),request.getNamePrefix(),request.getLocation());
  for (  InstanceCreationNotifier instanceCreationNotifier : instanceCreationNotifiers) {
    instanceCreationNotifier.notifyInstanceCreated(instanceId);
  }
  return Response.created(InstanceResource.constructSelfUri(uriInfo,instanceId)).build();
}
 

Example 25

From project cloudify, under directory /esc/src/main/java/org/cloudifysource/esc/driver/provisioning/jclouds/.

Source file: DefaultProvisioningDriver.java

  29 
vote

private MachineDetails[] getExistingManagementServers(final String managementMachinePrefix){
  final Set<? extends NodeMetadata> existingManagementServers=this.deployer.getServers(new Predicate<ComputeMetadata>(){
    @Override public boolean apply(    final ComputeMetadata input){
      final NodeMetadata node=(NodeMetadata)input;
      if (node.getGroup() == null) {
        return false;
      }
      if (node.getState() == NodeState.RUNNING || node.getState() == NodeState.PENDING) {
        return node.getGroup().toLowerCase().startsWith(managementMachinePrefix.toLowerCase());
      }
      return false;
    }
  }
);
  final MachineDetails[] result=new MachineDetails[existingManagementServers.size()];
  int i=0;
  for (  final NodeMetadata node : existingManagementServers) {
    result[i]=createMachineDetailsFromNode(node);
    result[i].setAgentRunning(true);
    result[i].setCloudifyInstalled(true);
    i++;
  }
  return result;
}
 

Example 26

From project clustermeister, under directory /provisioning/src/main/java/com/github/nethad/clustermeister/provisioning/ec2/.

Source file: AmazonNodeManager.java

  29 
vote

private AmazonNode getDriverForNode(final AmazonNode node){
  managedNodesMonitor.enter();
  try {
    return Iterables.find(drivers,new Predicate<AmazonNode>(){
      @Override public boolean apply(      AmazonNode driver){
        String driverAddress=Iterables.getFirst(driver.getPrivateAddresses(),null);
        checkNotNull(driverAddress);
        return node.getDriverAddress().equals(driverAddress);
      }
    }
,null);
  }
  finally {
    managedNodesMonitor.leave();
  }
}
 

Example 27

From project clutter, under directory /src/clutter/.

Source file: Suites.java

  29 
vote

private static Test makeSuite(Predicate<Class> predicate) throws ClassNotFoundException {
  TestSuite testSuite=new TestSuite();
  SimpleTestCollector testCollector=new SimpleTestCollector();
  Enumeration enumeration=testCollector.collectTests();
  while (enumeration.hasMoreElements()) {
    Class klass=Class.forName((String)enumeration.nextElement());
    if (predicate.apply(klass)) {
      testSuite.addTestSuite(klass);
    }
  }
  return testSuite;
}
 

Example 28

From project commons-j, under directory /src/main/java/nerds/antelax/commons/base/.

Source file: DecisionFunction.java

  29 
vote

/** 
 * Constructs a new  {@link Function} that delegates to other {@link Function}s based on the results of a  {@link Predicate}.
 * @param predicate the  {@link Predicate} on which to base the decision
 * @param successFunction the  {@link Function} to invoke if {@link #predicate} returns <code>true</code>
 * @param failureFunction the  {@link Function} to invoke if {@link #predicate} returns <code>false</code>
 */
DecisionFunction(final Predicate<F> predicate,final Function<F,T> successFunction,final Function<F,T> failureFunction){
  Preconditions.checkNotNull(predicate);
  Preconditions.checkNotNull(successFunction);
  Preconditions.checkNotNull(failureFunction);
  this.predicate=predicate;
  this.successFunction=successFunction;
  this.failureFunction=failureFunction;
}
 

Example 29

From project community-plugins, under directory /deployit-cli-plugins/mustachifier/src/main/java/ext/deployit/community/cli/mustachify/config/.

Source file: ConfigParser.java

  29 
vote

@Override public Map<String,String> apply(Map<String,String> from){
  KeyTransformer<String,String,String> prefixStripper=new KeyTransformer<String,String,String>(new Function<String,String>(){
    @Override public String apply(    String from){
      return substringAfter(from,indexedRulePrefix);
    }
  }
);
  return copyOf(prefixStripper.apply(filterKeys(from,new Predicate<String>(){
    @Override public boolean apply(    String input){
      return input.startsWith(indexedRulePrefix);
    }
  }
)));
}
 

Example 30

From project components-ness-httpclient, under directory /testing/src/main/java/com/nesscomputing/httpclient/testing/.

Source file: TestingHttpClientFactory.java

  29 
vote

private String getHeader(HttpClientRequest<?> request,final String header){
  Collection<HttpClientHeader> candidates=Collections2.filter(request.getHeaders(),new Predicate<HttpClientHeader>(){
    @Override public boolean apply(    HttpClientHeader h){
      return h.getName().equals(header);
    }
  }
);
  Preconditions.checkArgument(candidates.size() <= 1,"multiple " + header + " headers");
  if (candidates.isEmpty()) {
    return null;
  }
  return candidates.iterator().next().getValue();
}
 

Example 31

From project core_4, under directory /api/src/main/java/org/richfaces/component/.

Source file: ComponentIterators.java

  29 
vote

public static UIComponent getParent(UIComponent component,Predicate<UIComponent> predicat){
  if (component == null || predicat == null) {
    return null;
  }
  UIComponent parent=component.getParent();
  while (parent != null) {
    if (predicat.apply(parent)) {
      return parent;
    }
    parent=parent.getParent();
  }
  return null;
}
 

Example 32

From project cp-common-utils, under directory /src/com/clarkparsia/common/collect/.

Source file: Iterables2.java

  29 
vote

/** 
 * Same as  {@link Iterables#find} except it does not throw {@link NoSuchElementException} if the result is not found.
 * @param theIterable	the iterable to search
 * @param thePredicate	the predicate to use
 * @return true if an element in the Iterable satisfies the predicate, false otherwise
 */
public static <T>boolean find(final Iterable<T> theIterable,final Predicate<? super T> thePredicate){
  try {
    return Iterables.find(theIterable,thePredicate) != null;
  }
 catch (  NoSuchElementException e) {
    return false;
  }
}
 

Example 33

From project cp-openrdf-utils, under directory /core/src/com/clarkparsia/openrdf/.

Source file: Graphs.java

  29 
vote

/** 
 * Create a  {@link Predicate filtered} copy of the provided {@link Graph}
 * @param theGraph		the graph to filter
 * @param thePredicate	the predicate to use for filtering
 * @return				the filtered graph
 */
public static Graph filter(final Graph theGraph,final Predicate<Statement> thePredicate){
  final SetGraph aGraph=new SetGraph();
  for (  Statement aStmt : theGraph) {
    if (thePredicate.apply(aStmt)) {
      aGraph.add(aStmt);
    }
  }
  return aGraph;
}
 

Example 34

From project curator, under directory /curator-examples/src/main/java/discovery/.

Source file: DiscoveryExample.java

  29 
vote

private static void deleteInstance(String[] args,String command,List<ExampleServer> servers){
  if (args.length != 1) {
    System.err.println("syntax error (expected delete <name>): " + command);
    return;
  }
  final String serviceName=args[0];
  ExampleServer server=Iterables.find(servers,new Predicate<ExampleServer>(){
    @Override public boolean apply(    ExampleServer server){
      return server.getThisInstance().getName().endsWith(serviceName);
    }
  }
,null);
  if (server == null) {
    System.err.println("No servers found named: " + serviceName);
    return;
  }
  servers.remove(server);
  Closeables.closeQuietly(server);
  System.out.println("Removed a random instance of: " + serviceName);
}
 

Example 35

From project daleq, under directory /daleq-core/src/main/java/de/brands4friends/daleq/core/internal/types/.

Source file: CachingTableTypeRepository.java

  29 
vote

private TableType doGet(final TableTypeReference tableRef){
  final Optional<TableTypeResolver> resolver=Iterables.tryFind(resolvers,new Predicate<TableTypeResolver>(){
    @Override public boolean apply(    @Nullable final TableTypeResolver resolver){
      if (resolver == null) {
        return false;
      }
      return resolver.canResolve(tableRef);
    }
  }
);
  if (!resolver.isPresent()) {
    throw new DaleqBuildException("No TableTypeResolver registered for " + tableRef);
  }
  return resolver.get().resolve(tableRef);
}
 

Example 36

From project datasalt-utils, under directory /src/main/java/com/datasalt/utils/commons/.

Source file: RepoTool.java

  29 
vote

protected Path[] getPackages(Predicate<FileStatus> filter) throws IOException {
  FileStatus[] lfs=fs.listStatus(basePath);
  if (lfs == null) {
    return new Path[0];
  }
  ArrayList<String> paths=new ArrayList<String>();
  for (int i=0; i < lfs.length; i++) {
    FileStatus status=lfs[i];
    if (status.isDir()) {
      try {
        dateFormatter.parse(status.getPath().getName());
        if (!filter.apply(status)) {
          paths.add(status.getPath().toString());
        }
      }
 catch (      ParseException e) {
        continue;
      }
    }
  }
  Collections.sort(paths,Collections.reverseOrder());
  Path[] ret=new Path[paths.size()];
  for (int i=0; i < paths.size(); i++) {
    ret[i]=new Path(paths.get(i));
  }
  return ret;
}
 

Example 37

From project dev-examples, under directory /iteration-demo/src/main/java/org/richfaces/demo/.

Source file: RF10888.java

  29 
vote

public Object getFilteredData(){
  @SuppressWarnings("unchecked") List<Person> resultList=(List<Person>)persistenceService.getEntityManager().createQuery("SELECT p from Person as p").getResultList();
  List<Predicate<Person>> predicates=Lists.newArrayList();
  if (!Strings.isNullOrEmpty(name)) {
    predicates.add(contains(name,new Function<Person,CharSequence>(){
      public CharSequence apply(      Person input){
        return input.getName();
      }
    }
));
  }
  if (!Strings.isNullOrEmpty(surname)) {
    predicates.add(contains(surname,new Function<Person,CharSequence>(){
      public CharSequence apply(      Person input){
        return input.getSurname();
      }
    }
));
  }
  if (!Strings.isNullOrEmpty(email)) {
    predicates.add(contains(email,new Function<Person,CharSequence>(){
      public CharSequence apply(      Person input){
        return input.getEmail();
      }
    }
));
  }
  return Lists.newArrayList(Collections2.filter(resultList,Predicates.and(predicates)));
}
 

Example 38

From project DirectMemory, under directory /DirectMemory-Cache/src/main/java/org/apache/directmemory/memory/.

Source file: AbstractMemoryManager.java

  29 
vote

public void collectLFU(){
  int limit=pointers.size() / 10;
  Iterable<Pointer<V>> result=from(new Comparator<Pointer<V>>(){
    public int compare(    Pointer<V> o1,    Pointer<V> o2){
      float f1=o1.getFrequency();
      float f2=o2.getFrequency();
      return Float.compare(f1,f2);
    }
  }
).sortedCopy(limit(filter(pointers,new Predicate<Pointer<V>>(){
    @Override public boolean apply(    Pointer<V> input){
      return !input.isFree();
    }
  }
),limit));
  free(result);
}
 

Example 39

From project eclipse-task-editor, under directory /plugins/de.sebastianbenz.task.ui/src/de/sebastianbenz/task/ui/handlers/.

Source file: RemoveDoneTasks.java

  29 
vote

private List<Task> allDoneTasks(XtextResource state){
  Iterator<Task> allTasks=filter(state.getAllContents(),Task.class);
  return newArrayList(filter(allTasks,new Predicate<Task>(){
    public boolean apply(    Task task){
      return task.isDone();
    }
  }
));
}
 

Example 40

From project edna-rcp, under directory /org.edna.datamodel.transformations/src/org/edna/datamodel/transformations/m2m/.

Source file: Dsl2UmlTransformation.java

  29 
vote

/** 
 * Types which only contain elements, whose type is a primitive type, are considered as Datatype Wrapper. References to those types should be just a Property without association in the target UML model.
 */
private boolean isDataTypeWrapper(ComplexType type){
  return Iterables.all(type.getElements(),new Predicate<ElementDeclaration>(){
    public boolean apply(    ElementDeclaration input){
      return input.getRef() == null;
    }
  }
);
}
 

Example 41

From project EMF-IncQuery, under directory /plugins/org.eclipse.viatra2.emf.incquery.tooling.core/src/org/eclipse/viatra2/emf/incquery/core/project/.

Source file: ProjectGenerationHelper.java

  29 
vote

/** 
 * @param extensionMap
 * @param extension
 * @param id
 * @return
 */
private static boolean isExtensionInMap(Multimap<String,IPluginExtension> extensionMap,final IPluginExtension extension,String id){
  boolean extensionToCreateFound=false;
  if (extensionMap.containsKey(id)) {
    extensionToCreateFound=Iterables.any(extensionMap.get(id),new Predicate<IPluginExtension>(){
      @Override public boolean apply(      IPluginExtension ex){
        return ex.getPoint().equals(extension.getPoint());
      }
    }
);
  }
  return extensionToCreateFound;
}
 

Example 42

From project emite, under directory /src/main/java/com/calclab/emite/base/xml/.

Source file: XMLPacketImpl.java

  29 
vote

@Override public XMLPacket getFirstChild(final Predicate<XMLPacket> matcher){
  checkNotNull(matcher);
  for (  final XMLPacket packet : getChildren()) {
    if (matcher.apply(packet))     return packet;
  }
  return null;
}