com.google.common.base.Predicate Java Examples
The following examples show how to use
com.google.common.base.Predicate.
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: jMutRepair_003_s.java From coming with MIT License | 6 votes |
/** * Apply the supplied predicate against * all possible result Nodes of the expression. */ static boolean anyResultsMatch(Node n, Predicate<Node> p) { switch (n.getType()) { case Token.ASSIGN: case Token.COMMA: return anyResultsMatch(n.getLastChild(), p); case Token.AND: case Token.OR: return anyResultsMatch(n.getFirstChild(), p) || anyResultsMatch(n.getLastChild(), p); case Token.HOOK: return anyResultsMatch(n.getFirstChild().getNext(), p) || anyResultsMatch(n.getLastChild(), p); default: return p.apply(n); } }
Example #2
Source File: SshMachineLocationTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
@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 #3
Source File: ObjectMapperProvider.java From hraven with Apache License 2.0 | 6 votes |
@Override public void serialize(Configuration conf, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { SerializationContext context = RestResource.serializationContext .get(); Predicate<String> configFilter = context.getConfigurationFilter(); Iterator<Map.Entry<String, String>> keyValueIterator = conf.iterator(); jsonGenerator.writeStartObject(); // here's where we can filter out keys if we want while (keyValueIterator.hasNext()) { Map.Entry<String, String> kvp = keyValueIterator.next(); if (configFilter == null || configFilter.apply(kvp.getKey())) { jsonGenerator.writeFieldName(kvp.getKey()); jsonGenerator.writeString(kvp.getValue()); } } jsonGenerator.writeEndObject(); }
Example #4
Source File: FormatJavaValidator.java From dsl-devkit with Eclipse Public License 1.0 | 6 votes |
/** * Verify that only rule self directives are used for terminal, enum and data type rules. * * @param model * the GrammarRule */ @Check public void checkDataTypeOrEnumRule(final GrammarRule model) { if (model.getTargetRule() instanceof TerminalRule || model.getTargetRule() instanceof EnumRule || (model.getTargetRule() instanceof ParserRule && GrammarUtil.isDatatypeRule((ParserRule) model.getTargetRule()))) { Iterator<EObject> grammarElementAccessors = collectGrammarElementAccessors(model); boolean selfAccessOnly = Iterators.all(grammarElementAccessors, new Predicate<EObject>() { @Override public boolean apply(final EObject input) { return input instanceof GrammarElementReference && ((GrammarElementReference) input).getSelf() != null; } }); if (!selfAccessOnly) { error(NLS.bind("For data type, enum or terminal rule {0} only ''rule'' directive may be used", model.getTargetRule().getName()), FormatPackage.Literals.GRAMMAR_RULE__DIRECTIVES, ILLEGAL_DIRECTIVE_CODE); } } }
Example #5
Source File: IssueServiceImpl.java From putnami-web-toolkit with GNU Lesser General Public License v3.0 | 6 votes |
@Override public List<Issue> searchIssues(final String name, final String label) { Iterable<Issue> filteredIterable = Iterables.filter(issues.values(), new Predicate<Issue>() { @Override public boolean apply(Issue issue) { boolean result = true; if (name != null) { result = issue.getName() != null && issue.getName().toLowerCase().contains(name.toLowerCase()); } if (result && label != null) { Iterable<String> filteredLabels = Iterables.filter(issue.getLabels(), new Predicate<String>() { @Override public boolean apply(String issueLabel) { return issueLabel != null && issueLabel.toLowerCase().contains(label.toLowerCase()); } }); result = result && filteredLabels.iterator().hasNext(); } return result; } }); return Lists.newArrayList(filteredIterable); }
Example #6
Source File: ImportSystemOutputToAnnotationStore.java From tac-kbp-eal with MIT License | 6 votes |
private static void trueMain(final String[] argv) throws IOException { if (argv.length == 1) { final Parameters params = Parameters.loadSerifStyle(new File(argv[0])); log.info(params.dump()); final Function<DocumentSystemOutput, DocumentSystemOutput> filter = getSystemOutputFilter(params); final Predicate<Symbol> docIdFilter = getDocIdFilter(params); final SystemOutputLayout outputLayout = SystemOutputLayout.ParamParser.fromParamVal( params.getString("outputLayout")); final AssessmentSpecFormats.Format annStoreFileFormat = params.getEnum("annStore.fileFormat", AssessmentSpecFormats.Format.class); final ImmutableSet<SystemOutputStore> systemOutputs = loadSystemOutputStores(params, outputLayout); final ImmutableSet<AnnotationStore> annotationStores = loadAnnotationStores(params, annStoreFileFormat); importSystemOutputToAnnotationStore(systemOutputs, annotationStores, filter, docIdFilter); } else { usage(); } }
Example #7
Source File: jMutRepair_003_t.java From coming with MIT License | 6 votes |
/** * @return Whether the predicate is true for the node or any of its children. */ static boolean has(Node node, Predicate<Node> pred, Predicate<Node> traverseChildrenPred) { if (pred.apply(node)) { return true; } if (!traverseChildrenPred.apply(node)) { return false; } for (Node c = node.getFirstChild(); c != null; c = c.getNext()) { if (has(c, pred, traverseChildrenPred)) { return true; } } return false; }
Example #8
Source File: ResolvedTypes.java From xtext-extras with Eclipse Public License 2.0 | 6 votes |
@Override public Collection<ILinkingCandidate> getFollowUpErrors() { Collection<?> rawResult = Collections2.filter(basicGetLinkingMap().values(), new Predicate<IApplicableCandidate>() { @Override public boolean apply(/* @Nullable */ IApplicableCandidate input) { if (input == null) throw new IllegalArgumentException(); if (input instanceof FollowUpError) return true; return false; } }); @SuppressWarnings("unchecked") // cast is safe Collection<ILinkingCandidate> result = (Collection<ILinkingCandidate>) rawResult; return result; }
Example #9
Source File: ConsumerServiceImpl.java From rocket-console with Apache License 2.0 | 6 votes |
@Override public List<TopicConsumerInfo> queryConsumeStatsList(final String topic, String groupName) { ConsumeStats consumeStats = null; try { consumeStats = mqAdminExt.examineConsumeStats(groupName); // todo ConsumeStats examineConsumeStats(final String consumerGroup, final String topic) can use } catch (Exception e) { throw propagate(e); } List<MessageQueue> mqList = Lists.newArrayList(Iterables.filter(consumeStats.getOffsetTable().keySet(), new Predicate<MessageQueue>() { @Override public boolean apply(MessageQueue o) { return StringUtils.isBlank(topic) || o.getTopic().equals(topic); } })); Collections.sort(mqList); List<TopicConsumerInfo> topicConsumerInfoList = Lists.newArrayList(); TopicConsumerInfo nowTopicConsumerInfo = null; for (MessageQueue mq : mqList) { if (nowTopicConsumerInfo == null || (!StringUtils.equals(mq.getTopic(), nowTopicConsumerInfo.getTopic()))) { nowTopicConsumerInfo = new TopicConsumerInfo(mq.getTopic()); topicConsumerInfoList.add(nowTopicConsumerInfo); } nowTopicConsumerInfo.appendQueueStatInfo(QueueStatInfo.fromOffsetTableEntry(mq, consumeStats.getOffsetTable().get(mq))); } return topicConsumerInfoList; }
Example #10
Source File: 1_NodeUtil.java From SimFix with GNU General Public License v2.0 | 6 votes |
/** * Apply the supplied predicate against the potential * all possible result of the expression. */ static boolean valueCheck(Node n, Predicate<Node> p) { switch (n.getType()) { case Token.ASSIGN: case Token.COMMA: return valueCheck(n.getLastChild(), p); case Token.AND: case Token.OR: return valueCheck(n.getFirstChild(), p) && valueCheck(n.getLastChild(), p); case Token.HOOK: return valueCheck(n.getFirstChild().getNext(), p) && valueCheck(n.getLastChild(), p); default: return p.apply(n); } }
Example #11
Source File: RawDatasetRetentionPolicy.java From incubator-gobblin with Apache License 2.0 | 6 votes |
/** * A raw dataset version is qualified to be deleted, iff the corresponding refined paths exist, and the latest * mod time of all files is in the raw dataset is earlier than the latest mod time of all files in the refined paths. */ protected Collection<FileSystemDatasetVersion> listQualifiedRawFileSystemDatasetVersions(Collection<FileSystemDatasetVersion> allVersions) { return Lists.newArrayList(Collections2.filter(allVersions, new Predicate<FileSystemDatasetVersion>() { @Override public boolean apply(FileSystemDatasetVersion version) { Iterable<Path> refinedDatasetPaths = getRefinedDatasetPaths(version); try { Optional<Long> latestRawDatasetModTime = getLatestModTime(version.getPaths()); Optional<Long> latestRefinedDatasetModTime = getLatestModTime(refinedDatasetPaths); return latestRawDatasetModTime.isPresent() && latestRefinedDatasetModTime.isPresent() && latestRawDatasetModTime.get() <= latestRefinedDatasetModTime.get(); } catch (IOException e) { throw new RuntimeException("Failed to get modification time", e); } } })); }
Example #12
Source File: Closure_75_NodeUtil_s.java From coming with MIT License | 6 votes |
/** * Apply the supplied predicate against the potential * all possible result of the expression. */ static boolean valueCheck(Node n, Predicate<Node> p) { switch (n.getType()) { case Token.ASSIGN: case Token.COMMA: return valueCheck(n.getLastChild(), p); case Token.AND: case Token.OR: return valueCheck(n.getFirstChild(), p) && valueCheck(n.getLastChild(), p); case Token.HOOK: return valueCheck(n.getFirstChild().getNext(), p) && valueCheck(n.getLastChild(), p); default: return p.apply(n); } }
Example #13
Source File: Closure_86_NodeUtil_s.java From coming with MIT License | 6 votes |
/** * @return The number of times the the predicate is true for the node * or any of its children. */ static int getCount( Node n, Predicate<Node> pred, Predicate<Node> traverseChildrenPred) { int total = 0; if (pred.apply(n)) { total++; } if (traverseChildrenPred.apply(n)) { for (Node c = n.getFirstChild(); c != null; c = c.getNext()) { total += getCount(c, pred, traverseChildrenPred); } } return total; }
Example #14
Source File: ValueChangeConfig.java From arcusplatform with Apache License 2.0 | 6 votes |
@Override public Condition generate(Map<String, Object> values) { Preconditions.checkState(attribute != null, "must specify an attribute name"); String attributeName; Object oldValue = null; Object newValue = null; Predicate<Model> query = Predicates.alwaysTrue(); attributeName = FunctionFactory.toString(this.attribute.toTemplate(), values); if(this.oldValue != null) { oldValue = this.oldValue.toTemplate().apply(values); } if(this.newValue != null) { newValue = this.newValue.toTemplate().apply(values); } if(this.query != null) { query = FunctionFactory.toModelPredicate(this.query.toTemplate(), values); } return new ValueChangeTrigger(attributeName, oldValue, newValue, query); }
Example #15
Source File: ConvertJavaCode.java From xtext-xtend with Eclipse Public License 2.0 | 6 votes |
private boolean validateResource(Resource resource) { if (resource.getErrors().size() == 0) { List<Issue> issues = Lists.newArrayList(filter(((XtextResource) resource).getResourceServiceProvider() .getResourceValidator().validate(resource, CheckMode.ALL, CancelIndicator.NullImpl), new Predicate<Issue>() { @Override public boolean apply(Issue issue) { String code = issue.getCode(); return issue.getSeverity() == Severity.ERROR && !(IssueCodes.DUPLICATE_TYPE.equals(code) || org.eclipse.xtend.core.validation.IssueCodes.XBASE_LIB_NOT_ON_CLASSPATH .equals(code)); } })); return issues.size() == 0; } return false; }
Example #16
Source File: Closure_60_NodeUtil_t.java From coming with MIT License | 6 votes |
/** * Apply the supplied predicate against the potential * all possible result of the expression. */ static boolean valueCheck(Node n, Predicate<Node> p) { switch (n.getType()) { case Token.ASSIGN: case Token.COMMA: return valueCheck(n.getLastChild(), p); case Token.AND: case Token.OR: return valueCheck(n.getFirstChild(), p) && valueCheck(n.getLastChild(), p); case Token.HOOK: return valueCheck(n.getFirstChild().getNext(), p) && valueCheck(n.getLastChild(), p); default: return p.apply(n); } }
Example #17
Source File: FilteredEntryMultimap.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
boolean removeEntriesIf(Predicate<? super Entry<K, Collection<V>>> predicate) { Iterator<Entry<K, Collection<V>>> entryIterator = unfiltered.asMap().entrySet().iterator(); boolean changed = false; while (entryIterator.hasNext()) { Entry<K, Collection<V>> entry = entryIterator.next(); K key = entry.getKey(); Collection<V> collection = filterCollection(entry.getValue(), new ValuePredicate(key)); if (!collection.isEmpty() && predicate.apply(Maps.immutableEntry(key, collection))) { if (collection.size() == entry.getValue().size()) { entryIterator.remove(); } else { collection.clear(); } changed = true; } } return changed; }
Example #18
Source File: ValidationTestHelper.java From xtext-core with Eclipse Public License 2.0 | 6 votes |
protected Iterable<Issue> doMatchIssues(final Resource resource, final EClass objectType, final String code, final int offset, final int length, final Severity severity, final List<Issue> validate, final String... messageParts) { return Iterables.filter(validate, new Predicate<Issue>() { @Override public boolean apply(Issue input) { if (Strings.equal(input.getCode(), code) && input.getSeverity()==severity) { if ((offset < 0 || offset == input.getOffset()) && (length < 0 || length == input.getLength())) { EObject object = resource.getResourceSet().getEObject(input.getUriToProblem(), true); if (objectType.isInstance(object)) { for (String messagePart : messageParts) { if(!isValidationMessagePartMatches(input.getMessage(), messagePart)){ return false; } } return true; } } } return false; } }); }
Example #19
Source File: TileEntityElevator.java From enderutilities with GNU Lesser General Public License v3.0 | 6 votes |
public static Predicate<TileEntity> isMatchingElevator(final EnumDyeColor color) { return new Predicate<TileEntity> () { @Override public boolean apply(TileEntity te) { if ((te instanceof TileEntityElevator) == false) { return false; } IBlockState state = te.getWorld().getBlockState(te.getPos()); return state.getBlock() instanceof BlockElevator && state.getValue(BlockElevator.COLOR) == color; } }; }
Example #20
Source File: EntityAINearestAttackableTargetFiltered.java From Wizardry with GNU Lesser General Public License v3.0 | 5 votes |
/** * Returns whether the EntityAIBase should begin execution. */ @SuppressWarnings("unchecked") public boolean shouldExecute() { if (this.targetChance > 0 && this.taskOwner.getRNG().nextInt(this.targetChance) != 0) { return false; } else if (this.targetClass != EntityPlayer.class && this.targetClass != EntityPlayerMP.class) { List<T> list = this.taskOwner.world.getEntitiesWithinAABB(this.targetClass, this.getTargetableArea(this.getTargetDistance()), this.targetEntitySelector); if (list.isEmpty()) { return false; } else { list.sort(this.sorter); this.targetEntity = list.get(0); return true; } } else { this.targetEntity = (T) this.taskOwner.world.getNearestAttackablePlayer(this.taskOwner.posX, this.taskOwner.posY + (double) this.taskOwner.getEyeHeight(), this.taskOwner.posZ, this.getTargetDistance(), this.getTargetDistance(), new Function<EntityPlayer, Double>() { @Nullable public Double apply(@Nullable EntityPlayer p_apply_1_) { ItemStack itemstack = p_apply_1_.getItemStackFromSlot(EntityEquipmentSlot.HEAD); if (itemstack.getItem() == Items.SKULL) { int i = itemstack.getItemDamage(); boolean flag = EntityAINearestAttackableTargetFiltered.this.taskOwner instanceof EntitySkeleton && i == 0; boolean flag1 = EntityAINearestAttackableTargetFiltered.this.taskOwner instanceof EntityZombie && i == 2; boolean flag2 = EntityAINearestAttackableTargetFiltered.this.taskOwner instanceof EntityCreeper && i == 4; if (flag || flag1 || flag2) { return Double.valueOf(0.5D); } } return Double.valueOf(1.0D); } }, (Predicate<EntityPlayer>) this.targetEntitySelector); return this.targetEntity != null; } }
Example #21
Source File: PcapTopologyIntegrationTest.java From metron with Apache License 2.0 | 5 votes |
@Test public void filters_results_by_dst_port_greater_than_value_with_query_filter() throws Exception { PcapOptions.FILTER_IMPL.put(configuration, new QueryPcapFilter.Configurator()); PcapOptions.START_TIME_NS.put(configuration, getTimestamp(0, pcapEntries)); PcapOptions.END_TIME_NS .put(configuration, getTimestamp(pcapEntries.size() - 1, pcapEntries) + 1); PcapOptions.FIELDS.put(configuration, "ip_dst_port > 55790"); PcapJob<String> job = new PcapJob<>(); Statusable<Path> results = job.submit(PcapFinalizerStrategies.CLI, configuration); assertEquals(Statusable.JobType.MAP_REDUCE, results.getJobType()); waitForJob(results); assertEquals(JobStatus.State.SUCCEEDED, results.getStatus().getState()); Pageable<Path> resultPages = results.get(); Iterable<byte[]> bytes = Iterables.transform(resultPages, path -> { try { return HDFSUtils.readBytes(path); } catch (IOException e) { throw new IllegalStateException(e); } }); assertInOrder(bytes); assertEquals(Iterables.size(filterPcaps(pcapEntries, new Predicate<JSONObject>() { @Override public boolean apply(@Nullable JSONObject input) { Object prt = input.get(Constants.Fields.DST_PORT.getName()); return prt != null && (Long) prt > 55790; } }, withHeaders) ), resultPages.getSize() ); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PcapMerger.merge(baos, HDFSUtils.readBytes(resultPages.getPage(0))); assertTrue(baos.toByteArray().length > 0); }
Example #22
Source File: OverloadsFolder.java From sql-layer with GNU Affero General Public License v3.0 | 5 votes |
public InputSetFlags toInputSetFlags(Predicate<? super T> predicate) { boolean[] finites = new boolean[finiteArityList.size()]; for (int i = 0; i < finites.length; ++i) { finites[i] = predicate.apply(finiteArityList.get(i)); } boolean infinite = predicate.apply(infiniteArityElement); return new InputSetFlags(finites, infinite); }
Example #23
Source File: FormMappingConstraint.java From bonita-studio with GNU General Public License v2.0 | 5 votes |
private Predicate<FormMapping> withType(final FormMappingType type) { return new Predicate<FormMapping>() { @Override public boolean apply(final FormMapping input) { return input.getType() == type; } }; }
Example #24
Source File: GuavaFunctionalExamplesUnitTest.java From tutorials with MIT License | 5 votes |
@Test public final void givenEvenNumbers_whenCheckingIfAllSatisfyTheEvenPredicate_thenYes() { final List<Integer> evenNumbers = Lists.newArrayList(2, 6, 8, 10, 34, 90); final Predicate<Integer> acceptEvenNumber = new Predicate<Integer>() { @Override public final boolean apply(final Integer number) { return (number % 2) == 0; } }; assertTrue(Iterables.all(evenNumbers, acceptEvenNumber)); }
Example #25
Source File: Maps.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
FilteredKeyMap( Map<K, V> unfiltered, Predicate<? super K> keyPredicate, Predicate<? super Entry<K, V>> entryPredicate) { super(unfiltered, entryPredicate); this.keyPredicate = keyPredicate; }
Example #26
Source File: ScopeVisitor.java From pushfish-android with BSD 2-Clause "Simplified" License | 5 votes |
private void addCreator(String path, ClosureExpression creator) { final ImmutableMap<String, String> referenceAliasesMap = ImmutableMap.copyOf(referenceAliases); ReferenceExtractor extractor = new ReferenceExtractor(sourceUnit, referenceAliasesMap); Iterators.removeIf(creator.getVariableScope().getReferencedLocalVariablesIterator(), new Predicate<Variable>() { public boolean apply(Variable variable) { return referenceAliasesMap.keySet().contains(variable.getName()); } }); creator.getCode().visit(extractor); statementGenerator.addCreator(path, creator, extractor.getReferencedPaths()); }
Example #27
Source File: XtextLinkingService.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
private EPackage findPackageInScope(EObject context, QualifiedName packageNsURI) { IScope scopedPackages = scopeProvider.getScope(context.eResource(), XtextPackage.Literals.ABSTRACT_METAMODEL_DECLARATION__EPACKAGE, new Predicate<IEObjectDescription>() { @Override public boolean apply(IEObjectDescription input) { return isNsUriIndexEntry(input); } }); IEObjectDescription description = scopedPackages.getSingleElement(packageNsURI); if (description != null) { return getResolvedEPackage(description, context); } return null; }
Example #28
Source File: ExpressionBuilder.java From arcusplatform with Apache License 2.0 | 5 votes |
@Override protected Predicate<Model> doBuild() { switch(operator) { case IS: return Predicates.isA(namespace); case HAS: return Predicates.hasA(namespace); default: throw new IllegalArgumentException("Unrecognized operator " + operator); } }
Example #29
Source File: TypeToken.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
@Override public Set<Class<? super T>> rawTypes() { // Java has no way to express ? super T when we parameterize TypeToken vs. Class. @SuppressWarnings({"unchecked", "rawtypes"}) ImmutableList<Class<? super T>> collectedTypes = (ImmutableList) TypeCollector.FOR_RAW_TYPE.collectTypes(getRawTypes()); return FluentIterable.from(collectedTypes).filter(new Predicate<Class<?>>() { @Override public boolean apply(Class<?> type) { return type.isInterface(); } }).toSet(); }
Example #30
Source File: EObjectDescriptionLookUp.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
@Override public Iterable<IEObjectDescription> getExportedObjectsByType(final EClass type) { if (allDescriptions.isEmpty()) return Collections.emptyList(); return Iterables.filter(allDescriptions, new Predicate<IEObjectDescription>() { @Override public boolean apply(IEObjectDescription input) { return EcoreUtil2.isAssignableFrom(type, input.getEClass()); } }); }