Example usage for com.google.common.base Predicates compose

List of usage examples for com.google.common.base Predicates compose

Introduction

In this page you can find the example usage for com.google.common.base Predicates compose.

Prototype

public static <A, B> Predicate<A> compose(Predicate<B> predicate, Function<A, ? extends B> function) 

Source Link

Document

Returns the composition of a function and a predicate.

Usage

From source file:com.android.utils.FileUtils.java

/**
 * Find a file with the specified name in a given directory .
 *///from w  w  w .  ja  v  a 2  s .  co m
public static Optional<File> find(@NonNull File base, @NonNull final String name) {
    checkArgument(base.isDirectory(), "'base' must be a directory.");
    return Files.fileTreeTraverser().preOrderTraversal(base)
            .filter(Predicates.compose(Predicates.equalTo(name), GET_NAME)).last();
}

From source file:com.android.builder.internal.packaging.IncrementalPackager.java

/**
 * Updates native libraries in the archive.
 *
 * @param files the resources to update/*from   w  w w  .  j  av  a  2 s. c o  m*/
 * @throws IOException failed to update the archive
 */
public void updateNativeLibraries(@NonNull ImmutableMap<RelativeFile, FileStatus> files) throws IOException {
    updateFiles(PackagedFileUpdates.fromIncrementalRelativeFileSet(
            Maps.filterKeys(files, Predicates.compose(mAbiPredicate, RelativeFile.EXTRACT_PATH))));
}

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);/*from  w  ww  .  j  a v a 2s  .c o m*/

    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//from w  ww.jav a2  s .  c o m
 *            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.apache.jackrabbit.oak.plugins.memory.ModifiedNodeState.java

@Nonnull
@Override//from  w ww  .  j ava  2  s  .  co  m
public Iterable<? extends ChildNodeEntry> getChildNodeEntries() {
    if (!base.exists()) {
        return emptyList();
    } else if (nodes.isEmpty()) {
        return base.getChildNodeEntries(); // shortcut
    } else {
        Predicate<ChildNodeEntry> predicate = Predicates.compose(not(in(nodes.keySet())),
                ChildNodeEntry.GET_NAME);
        return concat(filter(base.getChildNodeEntries(), predicate),
                iterable(filterValues(nodes, NodeState.EXISTS).entrySet()));
    }
}

From source file:org.sosy_lab.cpachecker.cpa.predicate.PredicateCPARefiner.java

static List<ARGState> transformPath(ARGPath pPath) {
    List<ARGState> result = from(pPath.asStatesList()).skip(1).filter(Predicates
            .compose(PredicateAbstractState.FILTER_ABSTRACTION_STATES, toState(PredicateAbstractState.class)))
            .toList();//from   w  w  w . j a  v  a2  s . c  o  m

    assert from(result).allMatch(new Predicate<ARGState>() {
        @Override
        public boolean apply(ARGState pInput) {
            boolean correct = pInput.getParents().size() <= 1;
            assert correct : "PredicateCPARefiner expects abstraction states to have only one parent, but this state has more:"
                    + pInput;
            return correct;
        }
    });

    assert pPath.getLastState() == result.get(result.size() - 1);
    return result;
}

From source file:edu.buaa.satla.analysis.core.predicate.PredicateForcedCovering.java

/**
 * Return a list with all abstraction states on the path from the ARG root
 * to the given element.//from  ww  w  .j  a v a2  s  . co  m
 */
private ImmutableList<ARGState> getAbstractionPathTo(ARGState argState) {
    ARGPath pathFromRoot = ARGUtils.getOnePathTo(argState);

    return from(pathFromRoot.asStatesList())
            .filter(Predicates.compose(PredicateAbstractState.FILTER_ABSTRACTION_STATES,
                    AbstractStates.toState(PredicateAbstractState.class)))
            .toList();
}

From source file:edu.harvard.med.screensaver.service.libraries.PlateUpdater.java

private void updatePrimaryWellConcentration(Plate plate) {
    Map<String, Object> properties = Maps.newHashMap();
    properties.put("plateNumber", plate.getPlateNumber());
    properties.put("libraryWellType", LibraryWellType.EXPERIMENTAL);
    List<Well> wells = _dao.findEntitiesByProperties(Well.class, properties);
    ConcentrationStatistics concentrationStatistics = plate.getConcentrationStatistics();
    for (Well well : wells) {
        if (well.getMgMlConcentration() != null) {
            if (concentrationStatistics.getMaxMgMlConcentration() == null)
                concentrationStatistics.setMaxMgMlConcentration(well.getMgMlConcentration());
            else if (well.getMgMlConcentration()
                    .compareTo(concentrationStatistics.getMaxMgMlConcentration()) > 0)
                concentrationStatistics.setMaxMgMlConcentration(well.getMgMlConcentration());
            if (concentrationStatistics.getMinMgMlConcentration() == null)
                concentrationStatistics.setMinMgMlConcentration(well.getMgMlConcentration());
            else if (well.getMgMlConcentration()
                    .compareTo(concentrationStatistics.getMinMgMlConcentration()) < 0)
                concentrationStatistics.setMinMgMlConcentration(well.getMgMlConcentration());
        }/* w w  w.j  av a  2 s  .  c  o  m*/
        if (well.getMolarConcentration() != null) {
            if (concentrationStatistics.getMaxMolarConcentration() == null)
                concentrationStatistics.setMaxMolarConcentration(well.getMolarConcentration());
            else if (well.getMolarConcentration()
                    .compareTo(concentrationStatistics.getMaxMolarConcentration()) > 0)
                concentrationStatistics.setMaxMolarConcentration(well.getMolarConcentration());
            if (concentrationStatistics.getMinMolarConcentration() == null)
                concentrationStatistics.setMinMolarConcentration(well.getMolarConcentration());
            else if (well.getMolarConcentration()
                    .compareTo(concentrationStatistics.getMinMolarConcentration()) < 0)
                concentrationStatistics.setMinMolarConcentration(well.getMolarConcentration());
        }
    }

    Map<BigDecimal, Integer> mgMlCounts = Maps.transformValues(Multimaps.index(
            Lists.newArrayList(Iterators.filter(wells.iterator(),
                    Predicates.compose(Predicates.notNull(), Well.ToMgMlConcentration))),
            Well.ToMgMlConcentration).asMap(), CollectionSize);

    if (!mgMlCounts.isEmpty())
        concentrationStatistics.setPrimaryWellMgMlConcentration(findMaxByValueThenKey(mgMlCounts).getKey());

    Map<MolarConcentration, Integer> molarCounts = Maps.transformValues(Multimaps.index(
            Lists.newArrayList(Iterators.filter(wells.iterator(),
                    Predicates.compose(Predicates.notNull(), Well.ToMolarConcentration))),
            Well.ToMolarConcentration).asMap(), CollectionSize);

    if (!molarCounts.isEmpty())
        concentrationStatistics.setPrimaryWellMolarConcentration(findMaxByValueThenKey(molarCounts).getKey());
}

From source file:com.android.build.gradle.tasks.PackageAndroidArtifact.java

/**
 * Packages the application incrementally. In case of instant run packaging, this is not a
 * perfectly incremental task as some files are always rewritten even if no change has
 * occurred./* w ww.  ja va 2  s  .  c o m*/
 *
 * @param changedDex incremental dex packaging data
 * @param changedJavaResources incremental java resources
 * @param changedAssets incremental assets
 * @param changedAndroidResources incremental Android resource
 * @param changedNLibs incremental native libraries changed
 * @throws IOException failed to package the APK
 */
private void doTask(@NonNull ImmutableMap<RelativeFile, FileStatus> changedDex,
        @NonNull ImmutableMap<RelativeFile, FileStatus> changedJavaResources,
        @NonNull ImmutableMap<RelativeFile, FileStatus> changedAssets,
        @NonNull ImmutableMap<RelativeFile, FileStatus> changedAndroidResources,
        @NonNull ImmutableMap<RelativeFile, FileStatus> changedNLibs) throws IOException {

    ImmutableMap.Builder<RelativeFile, FileStatus> javaResourcesForApk = ImmutableMap.builder();
    javaResourcesForApk.putAll(changedJavaResources);

    Collection<File> instantRunDexBaseFiles;
    switch (dexPackagingPolicy) {
    case INSTANT_RUN_SHARDS_IN_SINGLE_APK:
        /*
         * If we're doing instant run, then we don't want to treat all dex archives
         * as dex archives for packaging. We will package some of the dex files as
         * resources.
         *
         * All dex files in directories whose name contains INSTANT_RUN_PACKAGES_PREFIX
         * are kept in the apk as dex files. All other dex files are placed as
         * resources as defined by makeInstantRunResourcesFromDex.
         */
        instantRunDexBaseFiles = getDexFolders().stream()
                .filter(input -> input.getName().contains(INSTANT_RUN_PACKAGES_PREFIX))
                .collect(Collectors.toSet());
        Iterable<File> nonInstantRunDexBaseFiles = getDexFolders().stream()
                .filter(f -> !instantRunDexBaseFiles.contains(f)).collect(Collectors.toSet());

        ImmutableMap<RelativeFile, FileStatus> newInstantRunResources = makeInstantRunResourcesFromDex(
                nonInstantRunDexBaseFiles);

        @SuppressWarnings("unchecked")
        ImmutableMap<RelativeFile, FileStatus> updatedChangedResources = IncrementalRelativeFileSets
                .union(Sets.newHashSet(changedJavaResources, newInstantRunResources));
        changedJavaResources = updatedChangedResources;

        changedDex = ImmutableMap.copyOf(Maps.filterKeys(changedDex,
                Predicates.compose(Predicates.in(instantRunDexBaseFiles), RelativeFile.EXTRACT_BASE)));

        break;
    case INSTANT_RUN_MULTI_APK:
        instantRunDexBaseFiles = getDexFolders().stream()
                .filter(input -> input.getName().contains(InstantRunSlicer.MAIN_SLICE_NAME))
                .collect(Collectors.toSet());
        changedDex = ImmutableMap.copyOf(Maps.filterKeys(changedDex,
                Predicates.compose(Predicates.in(instantRunDexBaseFiles), RelativeFile.EXTRACT_BASE)));

    case STANDARD:
        break;
    default:
        throw new RuntimeException("Unhandled DexPackagingPolicy : " + getDexPackagingPolicy());
    }

    PrivateKey key;
    X509Certificate certificate;
    boolean v1SigningEnabled;
    boolean v2SigningEnabled;

    try {
        if (signingConfig != null && signingConfig.isSigningReady()) {
            CertificateInfo certificateInfo = KeystoreHelper.getCertificateInfo(signingConfig.getStoreType(),
                    checkNotNull(signingConfig.getStoreFile()), checkNotNull(signingConfig.getStorePassword()),
                    checkNotNull(signingConfig.getKeyPassword()), checkNotNull(signingConfig.getKeyAlias()));
            key = certificateInfo.getKey();
            certificate = certificateInfo.getCertificate();
            v1SigningEnabled = signingConfig.isV1SigningEnabled();
            v2SigningEnabled = signingConfig.isV2SigningEnabled();
        } else {
            key = null;
            certificate = null;
            v1SigningEnabled = false;
            v2SigningEnabled = false;
        }

        ApkCreatorFactory.CreationData creationData = new ApkCreatorFactory.CreationData(getOutputFile(), key,
                certificate, v1SigningEnabled, v2SigningEnabled, null, // BuiltBy
                getBuilder().getCreatedBy(), getMinSdkVersion(),
                PackagingUtils.getNativeLibrariesLibrariesPackagingMode(manifest),
                getNoCompressPredicate()::apply);

        try (IncrementalPackager packager = createPackager(creationData)) {
            packager.updateDex(changedDex);
            packager.updateJavaResources(changedJavaResources);
            packager.updateAssets(changedAssets);
            packager.updateAndroidResources(changedAndroidResources);
            packager.updateNativeLibraries(changedNLibs);
        }
    } catch (PackagerException | KeytoolException e) {
        throw new RuntimeException(e);
    }

    /*
     * Save all used zips in the cache.
     */
    Stream.concat(changedDex.keySet().stream(),
            Stream.concat(changedJavaResources.keySet().stream(),
                    Stream.concat(changedAndroidResources.keySet().stream(), changedNLibs.keySet().stream())))
            .map(RelativeFile::getBase).filter(File::isFile).distinct().forEach((File f) -> {
                try {
                    cacheByPath.add(f);
                } catch (IOException e) {
                    throw new IOExceptionWrapper(e);
                }
            });

    // Mark this APK production, this will eventually be saved when instant-run is enabled.
    // this might get overridden if the apk is signed/aligned.
    try {
        instantRunContext.addChangedFile(instantRunFileType, getOutputFile());
    } catch (IOException e) {
        throw new BuildException(e.getMessage(), e);
    }
}

From source file:com.google.gerrit.server.notedb.ChangeBundle.java

private <K, V> Map<K, V> limitToValidPatchSets(Map<K, V> in, Function<K, PatchSet.Id> func) {
    return Maps.filterKeys(in, Predicates.compose(validPatchSetPredicate(), func));
}