Java Code Examples for com.google.common.collect.Collections2#filter()

The following examples show how to use com.google.common.collect.Collections2#filter() . 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: AlertUtils.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
/**
 * Helper to convert a collection of email strings into {@code InternetAddress} instances, filtering
 * out invalid addresses and nulls.
 *
 * @param emailCollection collection of email address strings
 * @return filtered collection of InternetAddress objects
 */
public static Collection<InternetAddress> toAddress(Collection<String> emailCollection) {
  if (CollectionUtils.isEmpty(emailCollection)) {
    return Collections.emptySet();
  }
  return Collections2.filter(Collections2.transform(emailCollection,
      new Function<String, InternetAddress>() {
        @Override
        public InternetAddress apply(String s) {
          try {
            return InternetAddress.parse(s)[0];
          } catch (Exception e) {
            return null;
          }
        }
      }),
      new Predicate<InternetAddress>() {
        @Override
        public boolean apply(InternetAddress internetAddress) {
          return internetAddress != null;
        }
      });
}
 
Example 2
Source File: CppCheckstyle.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static Collection<String> getSourceFiles(String extraActionFile) {

  ExtraActionInfo info = ExtraActionUtils.getExtraActionInfo(extraActionFile);
  CppCompileInfo cppInfo = info.getExtension(CppCompileInfo.cppCompileInfo);

  return Collections2.filter(
          cppInfo.getSourcesAndHeadersList(),
          Predicates.and(
                  Predicates.not(Predicates.containsPattern("external/")),
                  Predicates.not(Predicates.containsPattern("third_party/")),
                  Predicates.not(Predicates.containsPattern("config/heron-config.h")),
                  Predicates.not(Predicates.containsPattern(".*pb.h$")),
                  Predicates.not(Predicates.containsPattern(".*cc_wrapper.sh$")),
                  Predicates.not(Predicates.containsPattern(".*pb.cc$"))
          )
  );
}
 
Example 3
Source File: CheckPluginDependencyVersions.java    From unleash-maven-plugin with Eclipse Public License 1.0 6 votes vote down vote up
private Multimap<ArtifactCoordinates, ArtifactCoordinates> getSnapshots(Profile profile,
    PomPropertyResolver propertyResolver) {
  this.log.debug("\t\tChecking direct plugin references of profile '" + profile.getId() + "'");
  Multimap<ArtifactCoordinates, ArtifactCoordinates> result = HashMultimap.create();
  BuildBase build = profile.getBuild();
  if (build != null) {
    for (Plugin plugin : build.getPlugins()) {
      Collection<Dependency> snapshots = Collections2.filter(plugin.getDependencies(),
          new IsSnapshotDependency(propertyResolver));
      if (!snapshots.isEmpty()) {
        result.putAll(PluginToCoordinates.INSTANCE.apply(plugin),
            Collections2.transform(snapshots, DependencyToCoordinates.INSTANCE));
      }
    }
  }
  return result;
}
 
Example 4
Source File: ProxyUtil.java    From streamline with Apache License 2.0 6 votes vote down vote up
public static Collection<Class<?>> loadAllClassesFromJar(final File jarFile, final Class<?> superTypeClass) throws IOException {
    List<Class<?>> classes = JarReader.findConcreteSubtypesOfClass(jarFile, superTypeClass);
    final ProxyUtil<?> proxyUtil = new ProxyUtil<>(superTypeClass);
    return Collections2.filter(classes, new Predicate<Class<?>>() {
        @Override
        public boolean apply(@Nullable Class<?> s) {
            try {
                proxyUtil.loadClassFromJar(jarFile.getAbsolutePath(), s.getName());
                return true;
            } catch (Throwable ex) {
                LOG.warn("class {} is concrete subtype of {}, but can't be initialized due to exception:", s, superTypeClass, ex);
                return false;
            }
        }
    });
}
 
Example 5
Source File: XtextAntlrUiGeneratorFragment.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
public static Collection<AbstractElement> getAllPredicatedElements(Grammar g) {
	Collection<AbstractElement> unfiltered = getAllElementsByType(g, AbstractElement.class);
	Collection<AbstractElement> result = Collections2.filter(unfiltered, new Predicate<AbstractElement>() {
		@Override
		public boolean apply(AbstractElement input) {
			return input.isPredicated() || input.isFirstSetPredicated();
		}
	});
	return result;
}
 
Example 6
Source File: BaselineFillingMergeWrapper.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@Override
protected List<MergedAnomalyResultDTO> merge(Collection<MergedAnomalyResultDTO> anomalies) {
  List<MergedAnomalyResultDTO> mergedAnomalies = super.merge(anomalies);

  // Refill current and baseline values for qualified parent anomalies
  // Ignore filling baselines for exiting parent anomalies and grouped anomalies
  Collection<MergedAnomalyResultDTO> parentAnomalies = Collections2.filter(mergedAnomalies,
      mergedAnomaly -> mergedAnomaly != null && !isExistingAnomaly(this.existingAnomalies, mergedAnomaly)
          && !StringUtils.isBlank(mergedAnomaly.getMetricUrn()));
  this.fillCurrentAndBaselineValue(new ArrayList<>(parentAnomalies));

  return mergedAnomalies;
}
 
Example 7
Source File: Database.java    From PlotMe-Core with GNU General Public License v3.0 5 votes vote down vote up
public List<Plot> getExpiredPlots(final IWorld world) {
    Collection<Plot> filter = Collections2.filter(plots.get(world).values(), new Predicate<Plot>() {
        @Override public boolean apply(Plot plot) {
            return plot.getExpiredDate() != null && Calendar.getInstance().getTime().after(plot.getExpiredDate()) && plot.getWorld().equals
                    (world);
        }
    });
    return ImmutableList.copyOf(filter);
}
 
Example 8
Source File: AnomalyFilterWrapper.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the nested pipelines and calls the isQualified method in the anomaly filter stage to check if an anomaly passes the filter.
 * @return the detection pipeline result
 * @throws Exception
 */
@Override
public final DetectionPipelineResult run() throws Exception {
  List<MergedAnomalyResultDTO> candidates = new ArrayList<>();
  List<PredictionResult> predictionResults = new ArrayList<>();
  Map<String, Object> diagnostics = new HashMap<>();
  List<EvaluationDTO> evaluations = new ArrayList<>();

  Set<Long> lastTimeStamps = new HashSet<>();
  for (Map<String, Object> properties : this.nestedProperties) {
    DetectionConfigDTO nestedConfig = new DetectionConfigDTO();

    Preconditions.checkArgument(properties.containsKey(PROP_CLASS_NAME), "Nested missing " + PROP_CLASS_NAME);
    HashMap<String, Object> nestedProp = new HashMap<>(properties);
    if (this.metricUrn != null){
      nestedProp.put(PROP_METRIC_URN, this.metricUrn);
    }
    nestedConfig.setId(this.config.getId());
    nestedConfig.setName(this.config.getName());
    nestedConfig.setDescription(this.config.getDescription());
    nestedConfig.setProperties(nestedProp);
    nestedConfig.setComponents(this.config.getComponents());
    DetectionPipeline pipeline = this.provider.loadPipeline(nestedConfig, this.startTime, this.endTime);

    DetectionPipelineResult intermediate = pipeline.run();
    lastTimeStamps.add(intermediate.getLastTimestamp());
    diagnostics.putAll(intermediate.getDiagnostics());
    evaluations.addAll(intermediate.getEvaluations());
    predictionResults.addAll(intermediate.getPredictions());
    candidates.addAll(intermediate.getAnomalies());
  }

  Collection<MergedAnomalyResultDTO> anomalies =
      Collections2.filter(candidates, mergedAnomaly -> mergedAnomaly != null && !mergedAnomaly.isChild() && anomalyFilter.isQualified(mergedAnomaly));

  return new DetectionPipelineResult(new ArrayList<>(anomalies), DetectionUtils.consolidateNestedLastTimeStamps(lastTimeStamps),
      predictionResults, evaluations).setDiagnostics(diagnostics);
}
 
Example 9
Source File: KcaExpeditionTableViewAdpater.java    From kcanotify with GNU General Public License v3.0 5 votes vote down vote up
public void setListViewItemList(JsonArray ship_list, final int area_no) {
    Type listType = new TypeToken<List<JsonObject>>() {}.getType();
    listViewItemList = new Gson().fromJson(ship_list, listType);
    listViewItemList = new ArrayList<>(Collections2.filter(listViewItemList, new Predicate<JsonObject>() {
        @Override
        public boolean apply(JsonObject input) {
            return (area_no == 0 || input.get("area").getAsInt() == area_no);
        }
    }));
}
 
Example 10
Source File: KillRewardMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
private Collection<KillReward> getRewards(@Nullable Event event, ParticipantState victim, DamageInfo damageInfo) {
    final DamageQuery query = DamageQuery.attackerDefault(event, victim, damageInfo);
    return Collections2.filter(killRewards, new Predicate<KillReward>() {
        @Override
        public boolean apply(KillReward killReward) {
            return killReward.filter.query(query).isAllowed();
        }
    });
}
 
Example 11
Source File: UDFCatalogResource.java    From streamline with Apache License 2.0 5 votes vote down vote up
private List<String> getArgTypes(Class<?> clazz, String methodname, int argStartIndex) {
    Method addMethod = findMethod(clazz, methodname);
    if (addMethod == null) {
        return Collections.emptyList();
    }
    final Class<?>[] params = addMethod.getParameterTypes();
    List<String> argTypes = new ArrayList<>();
    for (int i = argStartIndex; i < params.length; i++) {
        final Class<?> arg = params[i];
        try {
            argTypes.add(Schema.fromJavaType(arg).toString());
        } catch (ParserException ex) {
            Collection<Schema.Type> types = Collections2.filter(Arrays.asList(Schema.Type.values()), new Predicate<Schema.Type>() {
                public boolean apply(Schema.Type input) {
                    return arg.isAssignableFrom(input.getJavaType());
                }
            });
            if (types.isEmpty()) {
                LOG.error("Could not find a compatible type in schema for {} argument types", addMethod);
                return Collections.emptyList();
            } else {
                argTypes.add(Joiner.on("|").join(types));
            }
        }
    }
    return argTypes;
}
 
Example 12
Source File: IMediaManifest.java    From CameraV with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public List getAllByType(final String mimeType) {
	Collection<IMedia> media_ = Collections2.filter(listMedia, new Predicate<IMedia>() {
		@Override
		public boolean apply(IMedia m) {
			return m.dcimEntry.mediaType.equals(mimeType);
		}
	});
	
	return new ArrayList(media_);
}
 
Example 13
Source File: JavaCheckstyle.java    From twister2 with Apache License 2.0 5 votes vote down vote up
private static String[] getSourceFiles(String extraActionFile,
                                       Predicate<CharSequence> predicate) {
  ExtraActionInfo info = ExtraActionUtils.getExtraActionInfo(extraActionFile);
  JavaCompileInfo jInfo = info.getExtension(JavaCompileInfo.javaCompileInfo);

  Collection<String> sourceFiles = Collections2.filter(jInfo.getSourceFileList(), predicate);

  return sourceFiles.toArray(new String[sourceFiles.size()]);
}
 
Example 14
Source File: KcaExpeditionTableViewAdpater.java    From kcanotify_h5-master with GNU General Public License v3.0 5 votes vote down vote up
public void setListViewItemList(JsonArray ship_list, final int area_no) {
    Type listType = new TypeToken<List<JsonObject>>() {}.getType();
    listViewItemList = new Gson().fromJson(ship_list, listType);
    listViewItemList = new ArrayList<>(Collections2.filter(listViewItemList, new Predicate<JsonObject>() {
        @Override
        public boolean apply(JsonObject input) {
            return (area_no == 0 || input.get("area").getAsInt() == area_no);
        }
    }));
}
 
Example 15
Source File: CheckPluginVersions.java    From unleash-maven-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private Set<ArtifactCoordinates> getSnapshotsFromManagement(Profile profile, PomPropertyResolver propertyResolver) {
  this.log.debug("\t\tChecking managed plugins of profile '" + profile.getId() + "'");
  BuildBase build = profile.getBuild();
  if (build != null) {
    PluginManagement pluginManagement = build.getPluginManagement();
    if (pluginManagement != null) {
      Collection<Plugin> snapshots = Collections2.filter(pluginManagement.getPlugins(),
          new IsSnapshotPlugin(propertyResolver));
      return Sets.newHashSet(Collections2.transform(snapshots, PluginToCoordinates.INSTANCE));
    }
  }
  return Collections.emptySet();
}
 
Example 16
Source File: MethodFilters.java    From guice-persist-orient with MIT License 5 votes vote down vote up
/**
 * @param possibilities methods to reduce
 * @return extended method or null if no extended or more than one extended methods found
 */
public static MatchedMethod findSingleExtended(final Collection<MatchedMethod> possibilities) {
    final Collection<MatchedMethod> extended = Collections2.filter(possibilities,
            new Predicate<MatchedMethod>() {
                @Override
                public boolean apply(@Nonnull final MatchedMethod input) {
                    return input.extended;
                }
            });
    return extended.size() == 1 ? extended.iterator().next() : null;
}
 
Example 17
Source File: SQLApplicationWithAPITest.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception
{
  LocalMode lma = LocalMode.newInstance();
  Configuration conf = new Configuration(false);
  conf.addResource(this.getClass().getResourceAsStream("/META-INF/properties.xml"));
  conf.addResource(this.getClass().getResourceAsStream("/META-INF/properties-SQLApplicationWithAPI.xml"));

  SQLApplicationWithAPI app = new SQLApplicationWithAPI();

  lma.prepareDAG(app, conf);

  LocalMode.Controller lc = lma.getController();

  PrintStream originalSysout = System.out;
  final ByteArrayOutputStream baos = new ByteArrayOutputStream();
  System.setOut(new PrintStream(baos));

  lc.runAsync();
  SQLApplicationWithModelFileTest.waitTillStdoutIsPopulated(baos, 30000);
  lc.shutdown();

  System.setOut(originalSysout);

  String[] sout = baos.toString().split(System.lineSeparator());
  Collection<String> filter = Collections2.filter(Arrays.asList(sout), Predicates.containsPattern("Delta Record:"));

  String[] actualLines = filter.toArray(new String[filter.size()]);
  Assert.assertTrue(actualLines[0].contains("RowTime=Mon Feb 15 10:15:00 GMT 2016, Product=paint1"));
  Assert.assertTrue(actualLines[1].contains("RowTime=Mon Feb 15 10:16:00 GMT 2016, Product=paint2"));
  Assert.assertTrue(actualLines[2].contains("RowTime=Mon Feb 15 10:17:00 GMT 2016, Product=paint3"));
  Assert.assertTrue(actualLines[3].contains("RowTime=Mon Feb 15 10:18:00 GMT 2016, Product=paint4"));
  Assert.assertTrue(actualLines[4].contains("RowTime=Mon Feb 15 10:19:00 GMT 2016, Product=paint5"));
  Assert.assertTrue(actualLines[5].contains("RowTime=Mon Feb 15 10:10:00 GMT 2016, Product=abcde6"));
}
 
Example 18
Source File: ProjectUriResourceMap.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Collection<Resource> values() {
	if (localContents.isEmpty()) {
		return Collections.emptyList();
	}
	// Nasty ... we have to support values().iterator().remove()
	Collection<Resource> base = super.values();
	Collection<Resource> delegate = Collections2.filter(base,
			resource -> localContents.contains(resource.getURI()));
	return new ForwardingCollection<>() {

		@Override
		protected Collection<Resource> delegate() {
			return delegate;
		}

		@Override
		public Iterator<Resource> iterator() {
			Iterator<URI> delegateIterator = localContents.iterator();
			Iterator<Resource> resourceIterator = Iterators.transform(delegateIterator, globalMap::get);
			return new ForwardingIterator<>() {

				private URI prev = null;

				@Override
				protected Iterator<Resource> delegate() {
					return resourceIterator;
				}

				public Resource next() {
					Resource result = super.next();
					prev = result.getURI();
					return result;
				}

				public void remove() {
					super.remove();
					globalMap.remove(prev);
				}
			};
		}
	};
}
 
Example 19
Source File: EffectiveStatementMixins.java    From yangtools with Eclipse Public License 1.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
default <T> Collection<? extends T> filterEffectiveStatements(final Class<T> type) {
    // Yeah, this is not nice, but saves one transformation
    return (Collection<? extends T>) Collections2.filter(effectiveSubstatements(), type::isInstance);
}
 
Example 20
Source File: TimeGraphLegend.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Creates a states group
 *
 * @param composite
 *            the parent composite
 * @since 3.3
 */
private void addStateGroups(Composite composite) {

    StateItem[] stateTable = fProvider.getStateTable();
    if (stateTable == null) {
        return;
    }
    List<StateItem> stateItems = Arrays.asList(stateTable);
    Collection<StateItem> linkStates = Collections2.filter(stateItems, TimeGraphLegend::isLinkState);

    ScrolledComposite sc = new ScrolledComposite(composite, SWT.V_SCROLL | SWT.H_SCROLL);
    sc.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    sc.setExpandHorizontal(true);
    sc.setExpandVertical(true);
    sc.setLayout(GridLayoutFactory.swtDefaults().margins(200, 0).create());

    Composite innerComposite = new Composite(sc, SWT.NONE);
    fInnerComposite = innerComposite;
    GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
    innerComposite.setLayoutData(gd);
    innerComposite.setLayout(new GridLayout());
    innerComposite.addControlListener(new ControlAdapter() {
        @Override
        public void controlResized(ControlEvent e) {
            /*
             * Find the highest number of columns that fits in the new width
             */
            Point size = innerComposite.getSize();
            List<GridLayout> gridLayouts = getGridLayouts(innerComposite);
            Point minSize = new Point(0, 0);
            for (int columns = 8; columns > 0; columns--) {
                final int numColumns = columns;
                gridLayouts.forEach(gl -> gl.numColumns = numColumns);
                minSize = innerComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT);
                if (minSize.x <= size.x) {
                    break;
                }
            }
            sc.setMinSize(0, minSize.y);
        }
    });

    sc.setContent(innerComposite);

    createStatesGroup(innerComposite);
    createLinkGroup(linkStates, innerComposite);

    sc.setMinSize(0, innerComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
}