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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
Source File: TestAttributeExpressions.java From arcusplatform with Apache License 2.0 | 5 votes |
@Test public void testIsSupported() { Predicate<Model> predicate = ExpressionCompiler.compile("test:attr is supported"); assertTrue(predicate.apply(new SimpleModel(ImmutableMap.<String, Object>of("test:attr", true)))); assertTrue(predicate.apply(new SimpleModel(ImmutableMap.<String, Object>of("test:attr", -0.9)))); assertTrue(predicate.apply(new SimpleModel(ImmutableMap.<String, Object>of("test:attr", "a string")))); assertFalse(predicate.apply(new SimpleModel(ImmutableMap.<String, Object>of()))); }
Example #21
Source File: ForEachModelAction.java From arcusplatform with Apache License 2.0 | 5 votes |
/** * This will execute {@code delegate} for each matching device model. The * {@code targetVariable} indicates the variable that should be populated * with the selected address. * @param delegate * @param selector * @param targetAttribute */ public ForEachModelAction(Action delegate, Predicate<Model> selector, String targetVariable) { Preconditions.checkNotNull(delegate, "must have a delegate action"); Preconditions.checkNotNull(selector, "must specify a selector"); Preconditions.checkArgument(!StringUtils.isEmpty(targetVariable), "must specify a variable for the address"); this.delegate = delegate; this.selector = selector; this.targetVariable = targetVariable; }
Example #22
Source File: JdtBasedSimpleTypeScopeTest.java From xtext-eclipse with Eclipse Public License 2.0 | 5 votes |
@Test public void testGetContents_01() { Iterable<IEObjectDescription> contents = typeScope.getAllElements(); assertTrue(Iterables.any(contents, new Predicate<IEObjectDescription>() { @Override public boolean apply(IEObjectDescription input) { return List.class.getName().equals(input.getName().toString()); } })); }
Example #23
Source File: UndirectedMultiNodeConnections.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
@Override public Set<E> edgesConnecting(final Object node) { return Collections.unmodifiableSet( Maps.filterEntries(incidentEdgeMap, new Predicate<Entry<E, N>>() { @Override public boolean apply(Entry<E, N> entry) { return entry.getValue().equals(node); } }).keySet()); }
Example #24
Source File: AnswerKey.java From tac-kbp-eal with MIT License | 5 votes |
public AnswerKey copyMerging(AnswerKey toMerge) { // (1) determine which responses are newly assessed final Set<Response> alreadyAssessedInBaseline = FluentIterable.from(annotatedResponses()) .transform(AssessedResponseFunctions.response()).toSet(); final Predicate<AssessedResponse> ResponseNotAssessedInBaseline = compose( not(in(alreadyAssessedInBaseline)), AssessedResponseFunctions.response()); final Set<AssessedResponse> newAssessedResponses = FluentIterable.from(toMerge.annotatedResponses()) .filter(ResponseNotAssessedInBaseline) .toSet(); // add newly assessed responses together with baseline assessed responses to new // result, fixing the coreference indices of new assessments if needed final ImmutableSet.Builder<AssessedResponse> resultAssessed = ImmutableSet.builder(); resultAssessed.addAll(annotatedResponses()); resultAssessed.addAll(newAssessedResponses); final ImmutableSet<Response> responsesAssessedInAdditional = FluentIterable.from(toMerge.annotatedResponses()) .transform(AssessedResponseFunctions.response()) .toSet(); final Set<Response> stillUnannotated = Sets.union( // things unassessed in baseline which were still not // assessed in additional Sets.difference(unannotatedResponses(), responsesAssessedInAdditional), Sets.difference(toMerge.unannotatedResponses(), alreadyAssessedInBaseline)); log.info("\t{} additional assessments found; {} remain unassessed", newAssessedResponses.size(), stillUnannotated.size()); return AnswerKey.from(docId(), resultAssessed.build(), stillUnannotated, corefAnnotation().copyMerging(toMerge.corefAnnotation())); }
Example #25
Source File: AssetService.java From bonita-ui-designer with GNU General Public License v2.0 | 5 votes |
/** * Upload a local asset */ public Asset upload(MultipartFile file, T component, String type) { AssetType assetType = AssetType.getAsset(type); checkArgument(file != null && !file.isEmpty(), "Part named [file] is needed to successfully import a component"); checkArgument(assetType != null, ASSET_TYPE_IS_REQUIRED); try { if (AssetType.JSON.getPrefix().equals(type)) { checkWellFormedJson(file.getBytes()); } final Asset asset = new Asset() .setName(getOriginalFilename(file.getOriginalFilename())) .setType(assetType) .setOrder(getNextOrder(component)); Optional<Asset> existingAsset = Iterables.<Asset>tryFind(component.getAssets(), new Predicate<Asset>() { @Override public boolean apply(Asset element) { return asset.equalsWithoutComponentId(element); } }); if (existingAsset.isPresent()) { asset.setId(existingAsset.get().getId()); } return save(component, asset, file.getBytes()); } catch (IOException e) { logger.error("Asset creation" + e); throw new ServerImportException( format("Error while uploading asset in %s [%s]", file.getOriginalFilename(), repository.getComponentName()), e); } }
Example #26
Source File: ScanPluginAsGroupSwaggerConfig.java From onetwo with Apache License 2.0 | 5 votes |
protected void registerDocketIfNotExist(String docketBeanName, String groupName, String appName, Collection<Predicate<RequestHandler>> packages) { Docket innerDocket = createDocket(groupName, appName, packages); if (!applicationContext.containsBeanDefinition(docketBeanName)) { SpringUtils.registerAndInitSingleton(applicationContext, docketBeanName, innerDocket); logger.info("docket[{}] registered", docketBeanName); } else { logger.info("docket[{}] ignored", docketBeanName); } }
Example #27
Source File: AbstractScope.java From xtext-core with Eclipse Public License 2.0 | 5 votes |
protected Iterable<IEObjectDescription> getLocalElementsByName(final QualifiedName name) { Iterable<IEObjectDescription> localElements = getAllLocalElements(); Iterable<IEObjectDescription> result = Iterables.filter(localElements, new Predicate<IEObjectDescription>() { @Override public boolean apply(IEObjectDescription input) { if (isIgnoreCase()) { return name.equalsIgnoreCase(input.getName()); } else { return name.equals(input.getName()); } } }); return result; }
Example #28
Source File: GroupsWizardPage.java From bonita-studio with GNU General Public License v2.0 | 5 votes |
private Predicate<Membership> withGroupParentPath(final String path) { return new Predicate<Membership>() { @Override public boolean apply(Membership membership) { String groupParentPath = membership.getGroupParentPath(); if (groupParentPath != null && !groupParentPath.endsWith("/")) { groupParentPath = groupParentPath + "/"; } return groupParentPath != null && groupParentPath.startsWith(path); } }; }
Example #29
Source File: Closure_10_NodeUtil_s.java From coming with MIT License | 5 votes |
/** * A pre-order traversal, calling Visitor.visit for each child matching * the predicate. */ static void visitPreOrder(Node node, Visitor visitor, Predicate<Node> traverseChildrenPred) { visitor.visit(node); if (traverseChildrenPred.apply(node)) { for (Node c = node.getFirstChild(); c != null; c = c.getNext()) { visitPreOrder(c, visitor, traverseChildrenPred); } } }
Example #30
Source File: Word2VecCN.java From word2vec with Apache License 2.0 | 5 votes |
public Word2VecCNBuilder addAllFiles(@NonNull String root, @NonNull Predicate<File> predicate) { File dir = new File(root); if (dir.exists() && dir.isDirectory() && dir.canRead()) { Files.fileTreeTraverser() .breadthFirstTraversal(dir) .filter(predicate) .forEach(this::addFile); } throw new IllegalArgumentException(root + " is not a valid directory!"); }