List of usage examples for com.google.common.base Predicates and
public static <T> Predicate<T> and(Predicate<? super T> first, Predicate<? super T> second)
From source file:org.richfaces.resource.plugin.ProcessMojo.java
private Predicate<Resource> createResourcesFilter() { Predicate<CharSequence> qualifierPredicate = MorePredicates.compose(includedFiles, excludedFiles, REGEX_CONTAINS_BUILDER_FUNCTION); Predicate<Resource> qualifierResourcePredicate = Predicates.compose(qualifierPredicate, RESOURCE_QUALIFIER_FUNCTION); Predicate<CharSequence> contentTypePredicate = MorePredicates.compose(includedContentTypes, excludedContentTypes, REGEX_CONTAINS_BUILDER_FUNCTION); Predicate<Resource> contentTypeResourcePredicate = Predicates.compose(contentTypePredicate, CONTENT_TYPE_FUNCTION);/*www . j ava 2 s . c om*/ return Predicates.and(qualifierResourcePredicate, contentTypeResourcePredicate); }
From source file:forge.quest.BoosterUtils.java
/** * Create the list of card names at random from the given pool. * * @param source/* w ww.ja va2 s . com*/ * an Iterable<CardPrinted> * @param filter * Predicate<CardPrinted> * @param cntNeeded * an int * @param allowedColors * a List<Predicate<CardRules>> * @param allowDuplicates * If true, multiple copies of the same card will be allowed to be generated. * @return a list of card names */ private static List<PaperCard> generateCards(final Iterable<PaperCard> source, final Predicate<PaperCard> filter, final int cntNeeded, final List<Predicate<CardRules>> allowedColors, final boolean allowDuplicates) { //If color is null, use colorOrder progression to grab cards final List<PaperCard> result = new ArrayList<>(); final int size = allowedColors == null ? 0 : allowedColors.size(); if (allowedColors != null) { Collections.shuffle(allowedColors); } int cntMade = 0, iAttempt = 0; //This will prevent endless loop @ wh int allowedMisses = (size + 4) * cntNeeded; int nullMisses = 0; while (cntMade < cntNeeded && allowedMisses > 0) { PaperCard card = null; if (size > 0) { final Predicate<CardRules> color2 = allowedColors.get(iAttempt % size); int colorMisses = 0; //Try a few times to get a card using the available filter. This is important for sets with only a small //handful of multi-colored cards. do { if (color2 != null) { Predicate<PaperCard> color2c = Predicates.compose(color2, PaperCard.FN_GET_RULES); card = Aggregates.random(Iterables.filter(source, Predicates.and(filter, color2c))); } } while (card == null && colorMisses++ < 10); } if (card == null) { //We can't decide on a color. We're going to try very hard to pick a color within the current filters. if (nullMisses++ < 10) { iAttempt++; continue; } nullMisses = 0; //Still no luck. We're going to skip generating this card. This will very, very rarely result in fewer //cards than expected; however, it will keep unselected colors out of the pool. } if ((card != null) && (allowDuplicates || !result.contains(card))) { result.add(card); cntMade++; } else { allowedMisses--; } iAttempt++; } return result; }
From source file:org.opencms.xml.containerpage.CmsFormatterConfiguration.java
/** * Selects the best matching schema formatter for the provided type and width from this configuration.<p> * * @param containerTypes the container types (comma separated) * @param containerWidth the container width * * @return the matching formatter, or <code>null</code> if none was found *///from w w w. j a va 2 s . c o m public I_CmsFormatterBean getDefaultSchemaFormatter(final String containerTypes, final int containerWidth) { Optional<I_CmsFormatterBean> result = Iterables.tryFind(m_allFormatters, Predicates .and(new IsSchemaFormatter(), new MatchesTypeOrWidth(containerTypes, containerWidth, false))); return result.orNull(); }
From source file:clocker.mesos.entity.MesosClusterImpl.java
/** * De-register our {@link MesosLocation} and its children. *//*from ww w. j av a2 s . com*/ @Override public void stop() { disconnectSensors(); sensors().set(SERVICE_UP, Boolean.FALSE); deleteLocation(); Duration timeout = config().get(SHUTDOWN_TIMEOUT); // Find all applications and stop, blocking for up to five minutes until ended try { Iterable<Entity> entities = Iterables.filter(getManagementContext().getEntityManager().getEntities(), Predicates.and(MesosUtils.sameCluster(this), Predicates.not(EntityPredicates.applicationIdEqualTo(getApplicationId())))); Set<Application> applications = ImmutableSet .copyOf(Iterables.transform(entities, new Function<Entity, Application>() { @Override public Application apply(Entity input) { return input.getApplication(); } })); LOG.debug("Stopping applications: {}", Iterables.toString(applications)); Entities.invokeEffectorList(this, applications, Startable.STOP).get(timeout); } catch (Exception e) { LOG.warn("Error stopping applications", e); } // Stop all framework tasks in parallel try { Group frameworks = sensors().get(MESOS_FRAMEWORKS); LOG.debug("Stopping framework tasks in: {}", Iterables.toString(frameworks.getMembers())); Entities.invokeEffectorList(this, frameworks.getMembers(), Startable.STOP).get(timeout); } catch (Exception e) { LOG.warn("Error stopping frameworks", e); } // Stop anything else left over // TODO Stop slave entities try { super.stop(); } catch (Exception e) { LOG.warn("Error stopping children", e); } }
From source file:org.opencms.xml.containerpage.CmsFormatterConfiguration.java
/** * Gets the detail formatter to use for the given type and container width.<p> * * @param types the container types (comma separated) * @param containerWidth the container width * * @return the detail formatter to use/*from w w w . j a va 2 s.c om*/ */ public I_CmsFormatterBean getDetailFormatter(String types, int containerWidth) { // detail formatters must still match the type or width Predicate<I_CmsFormatterBean> checkValidDetailFormatter = Predicates .and(new MatchesTypeOrWidth(types, containerWidth, true), new IsDetail()); Optional<I_CmsFormatterBean> result = Iterables.tryFind(m_allFormatters, checkValidDetailFormatter); return result.orNull(); }
From source file:org.opensaml.xmlsec.impl.BasicSignatureSigningParametersResolver.java
/** * Get the effective list of signature algorithm URIs to consider, including application of * whitelist/blacklist policy.//from ww w .j a v a 2 s .com * * @param criteria the input criteria being evaluated * @param whitelistBlacklistPredicate the whitelist/blacklist predicate to use * @return the list of effective algorithm URIs */ @Nonnull protected List<String> getEffectiveSignatureAlgorithms(@Nonnull final CriteriaSet criteria, @Nonnull final Predicate<String> whitelistBlacklistPredicate) { ArrayList<String> accumulator = new ArrayList<>(); for (SignatureSigningConfiguration config : criteria.get(SignatureSigningConfigurationCriterion.class) .getConfigurations()) { accumulator.addAll(Collections2.filter(config.getSignatureAlgorithms(), Predicates.and(getAlgorithmRuntimeSupportedPredicate(), whitelistBlacklistPredicate))); } return accumulator; }
From source file:com.tasktop.c2c.server.internal.cloud.terremark.VCloudExpressCloudServiceBean.java
@Override public Node retrieveNodeByName(final String nodeName) { return perform(new ComputeServiceOperation<Node>() { @Override/*www .ja v a2 s. c om*/ protected Node perform(ComputeService computeService) { Predicate<ComputeMetadata> andPred = Predicates.and(NODE_PREDICATE, new NamePredicate(Pattern.compile(Pattern.quote(nodeName)))); Set<? extends NodeMetadata> nodes = computeService.listNodesDetailsMatching(andPred); if (nodes.isEmpty()) { return null; } if (nodes.size() > 1) { throw new IllegalStateException("Multiple nodes with name: " + nodeName); } NodeMetadata nodeMetadata = computeService.getNodeMetadata(nodes.iterator().next().getId()); Node result = createNode(nodeMetadata); debug("retriveNodeByName result [%s]", result); return result; } }); }
From source file:org.trancecode.xproc.step.Step.java
public Iterable<Port> getInputPorts(final boolean includeParameterPorts) { if (includeParameterPorts) { return Iterables.filter(ports.values(), PortPredicates.isInputPort()); } else {//w w w.j a va2 s . co m return Iterables.filter(ports.values(), Predicates.and(PortPredicates.isInputPort(), Predicates.not(PortPredicates.isParameterPort()))); } }
From source file:org.eclipse.emf.compare.rcp.ui.internal.structuremergeviewer.groups.impl.ThreeWayComparisonGroupProvider.java
/** * {@inheritDoc}/*from w w w . j a v a2 s . c om*/ * * @see org.eclipse.emf.compare.rcp.ui.internal.structuremergeviewer.groups.impl.AbstractBuildingDifferenceGroupProvider#buildGroups(org.eclipse.emf.compare.Comparison) */ @Override protected Collection<? extends IDifferenceGroup> buildGroups(Comparison comparison2) { Adapter adapter = EcoreUtil.getAdapter(getComparison().eAdapters(), SideLabelProvider.class); final String leftLabel, rightLabel; if (adapter instanceof SideLabelProvider) { SideLabelProvider labelProvider = (SideLabelProvider) adapter; leftLabel = labelProvider.getLeftLabel(); rightLabel = labelProvider.getRightLabel(); } else { leftLabel = EMFCompareRCPUIMessages.getString("ThreeWayComparisonGroupProvider.left.label"); //$NON-NLS-1$ rightLabel = EMFCompareRCPUIMessages.getString("ThreeWayComparisonGroupProvider.right.label"); //$NON-NLS-1$ } final BasicDifferenceGroupImpl conflicts = new ConflictsGroupImpl(getComparison(), hasConflict(ConflictKind.REAL, ConflictKind.PSEUDO), EMFCompareRCPUIMessages.getString("ThreeWayComparisonGroupProvider.conflicts.label"), //$NON-NLS-1$ getCrossReferenceAdapter()); conflicts.buildSubTree(); final BasicDifferenceGroupImpl leftSide = new BasicDifferenceGroupImpl(getComparison(), Predicates.and(fromSide(DifferenceSource.LEFT), Predicates.not(hasConflict(ConflictKind.REAL, ConflictKind.PSEUDO))), leftLabel, getCrossReferenceAdapter()); leftSide.buildSubTree(); final BasicDifferenceGroupImpl rightSide = new BasicDifferenceGroupImpl(getComparison(), Predicates.and(fromSide(DifferenceSource.RIGHT), Predicates.not(hasConflict(ConflictKind.REAL, ConflictKind.PSEUDO))), rightLabel, getCrossReferenceAdapter()); rightSide.buildSubTree(); return ImmutableList.of(conflicts, leftSide, rightSide); }
From source file:edu.byu.nlp.data.app.AnnotationStream2Annotators.java
private static Dataset readData(String jsonStream) throws IOException { // these parameters are not important since we will ignore the data itself and concentrate only on annotations // in this script int featureCountCutoff = -1; int topNFeaturesPerDocument = -1; Integer featureNormalizer = null; Function<String, String> docTransform = null; Function<String, String> tokenTransform = null; // data reader pipeline per dataset // build a dataset, doing all the tokenizing, stopword removal, and feature normalization String folder = Paths.directory(jsonStream); String file = Paths.baseName(jsonStream); Dataset data = new JSONDocumentDatasetBuilder(folder, file, docTransform, DocPipes.opennlpSentenceSplitter(), DocPipes.McCallumAndNigamTokenizer(), tokenTransform, FeatureSelectorFactories.conjoin(new CountCutoffFeatureSelectorFactory<String>(featureCountCutoff), (topNFeaturesPerDocument < 0) ? null : new TopNPerDocumentFeatureSelectorFactory(topNFeaturesPerDocument)), featureNormalizer).dataset(); // Postprocessing: remove all documents with duplicate sources or empty features data = Datasets.filteredDataset(data, Predicates.and(Datasets.filterDuplicateSources(), Datasets.filterNonEmpty())); logger.info("Number of labeled instances = " + data.getInfo().getNumDocumentsWithObservedLabels()); logger.info("Number of unlabeled instances = " + data.getInfo().getNumDocumentsWithoutObservedLabels()); logger.info("Number of tokens = " + data.getInfo().getNumTokens()); logger.info("Number of features = " + data.getInfo().getNumFeatures()); logger.info("Number of classes = " + data.getInfo().getNumClasses()); logger.info(/*from w w w .j av a 2 s .c o m*/ "Average Document Size = " + (data.getInfo().getNumTokens() / data.getInfo().getNumDocuments())); return data; }