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

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

Introduction

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

Prototype

public static <T> Predicate<T> not(Predicate<T> predicate) 

Source Link

Document

Returns a predicate that evaluates to true if the given predicate evaluates to false .

Usage

From source file:org.simmetrics.example.StringMetricBuilderExample.java

/**
 * Tokens can be filtered to avoid comparing strings on common but otherwise
 * low information words. Tokens can be filtered after any tokenization step
 * and can be applied repeatedly./*w  ww  .ja  v a 2  s.  co  m*/
 * 
 * A filter can be implemented by implementing a the {@link Predicate}
 * interface. By chaining predicates more complicated filters can be build.
 * */
public static float example05() {
    Set<String> commonWords = Sets.newHashSet("it", "is");
    Set<String> otherCommonWords = Sets.newHashSet("a");

    String a = "A quirky thing it is. This is a sentence.";
    String b = "This sentence is similar; a quirky thing it is.";

    StringMetric metric = with(new CosineSimilarity<String>()).simplify(Simplifiers.toLowerCase())
            .simplify(Simplifiers.removeNonWord()).tokenize(Tokenizers.whitespace())
            .filter(Predicates.not(in(commonWords))).filter(Predicates.not(in(otherCommonWords)))
            .tokenize(Tokenizers.qGram(3)).build();

    return metric.compare(a, b); // 0.68061393
}

From source file:com.twitter.aurora.GuiceUtils.java

/**
 * Binds an exception trap on all interface methods of all classes bound against an interface.
 * Individual methods may opt out of trapping by annotating with {@link AllowUnchecked}.
 * Only void methods are allowed, any non-void interface methods must explicitly opt out.
 *
 * @param binder The binder to register an interceptor with.
 * @param wrapInterface Interface whose methods should be wrapped.
 * @throws IllegalArgumentException If any of the non-whitelisted interface methods are non-void.
 *//*  w w  w. j av  a 2s  . c om*/
public static void bindExceptionTrap(Binder binder, Class<?> wrapInterface) throws IllegalArgumentException {

    Set<Method> disallowed = ImmutableSet
            .copyOf(Iterables.filter(ImmutableList.copyOf(wrapInterface.getMethods()),
                    Predicates.and(Predicates.not(IS_WHITELISTED), Predicates.not(VOID_METHOD))));
    Preconditions.checkArgument(disallowed.isEmpty(),
            "Non-void methods must be explicitly whitelisted with @AllowUnchecked: " + disallowed);

    Matcher<Method> matcher = Matchers.<Method>not(WHITELIST_MATCHER)
            .and(interfaceMatcher(wrapInterface, false));
    binder.bindInterceptor(Matchers.subclassesOf(wrapInterface), matcher, new MethodInterceptor() {
        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            try {
                return invocation.proceed();
            } catch (RuntimeException e) {
                LOG.log(Level.WARNING, "Trapped uncaught exception: " + e, e);
                return null;
            }
        }
    });
}

From source file:com.google.api.tools.framework.tools.SwaggerToolDriverBase.java

private void printDiagnostics(List<Diag> list) {
    Predicate<Diag> error = new Predicate<Diag>() {
        @Override//from  w w  w .j  av a  2  s  .  c o m
        public boolean apply(Diag input) {
            return input.getKind() == Kind.ERROR;
        }
    };

    String errors = Joiner.on("\n  ").join(Iterables.filter(list, error));
    String warnings = Joiner.on("\n  ").join(Iterables.filter(list, Predicates.not(error)));

    if (!errors.isEmpty()) {
        System.out.printf("\nSwagger/service config conversion encountered ERRORS:\n  %s\n", errors);
    }
    if (!warnings.isEmpty()) {
        System.out.printf("\nSwagger/service config conversion encountered warnings:\n  %s\n", warnings);
    }
}

From source file:org.apache.james.rrt.lib.MappingsImpl.java

@Override
public Mappings exclude(Type type) {
    Preconditions.checkNotNull(type);
    return fromMappings(FluentIterable.from(mappings).filter(Predicates.not(hasType(type))));
}

From source file:info.becauseqa.WebServiceApplication.java

/****************************************************************************************************************/
@Bean//ww  w  . ja v  a2s  .co m
public Docket customerDocket() {
    //add the authorization header
    /*  Parameter authorizationParameter = new ParameterBuilder().jobName("Authorization").APIInfo_description("Put your credential as username:pasword base64")
            
        .modelRef(new ModelRef("Basic ***")).parameterType("header")
        .required(true).build();
      List<Parameter> aParameters = new ArrayList<Parameter>();
      aParameters.add(authorizationParameter);*/
    return new Docket(DocumentationType.SWAGGER_2)
            //                .jobGroupName(APIInfo_ROOTPATH + APIInfo_VERSION)
            .select().apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot"))) //exclude the basic-error-resources,from spring boot
            .paths(PathSelectors.any()).build().apiInfo(apiInfo())
            .directModelSubstitute(LocalDateTime.class, String.class).useDefaultResponseMessages(false)
            .enableUrlTemplating(true);
    //                .globalOperationParameters(aParameters);
}

From source file:com.facebook.buck.js.ReactNativeDeps.java

@Override
public ImmutableList<Step> getBuildSteps(BuildContext context, final BuildableContext buildableContext) {
    ImmutableList.Builder<Step> steps = ImmutableList.builder();

    final Path output = BuildTargets.getScratchPath(getBuildTarget(), "__%s/deps.txt");
    steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), output.getParent()));

    steps.add(new ShellStep(getProjectFilesystem().getRootPath()) {
        @Override/*from  w  w  w  .j ava2 s  .c  o m*/
        protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) {
            ImmutableList.Builder<String> builder = ImmutableList.builder();

            builder.add(getResolver().getAbsolutePath(jsPackager).toString(), "list-dependencies",
                    platform.toString(),
                    getProjectFilesystem().resolve(getResolver().getAbsolutePath(entryPath)).toString(),
                    "--output", getProjectFilesystem().resolve(output).toString());

            if (packagerFlags.isPresent()) {
                builder.addAll(Arrays.asList(packagerFlags.get().split(" ")));
            }

            return builder.build();
        }

        @Override
        public String getShortName() {
            return "react-native-deps";
        }
    });

    steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), outputDir));

    steps.add(new AbstractExecutionStep("hash_js_inputs") {
        @Override
        public int execute(ExecutionContext context) throws IOException {
            ImmutableList<Path> paths;
            try {
                paths = FluentIterable.from(getProjectFilesystem().readLines(output))
                        .transform(MorePaths.TO_PATH).transform(getProjectFilesystem().getRelativizer())
                        .toSortedList(Ordering.natural());
            } catch (IOException e) {
                context.logError(e, "Error reading output of the 'react-native-deps' step.");
                return 1;
            }

            FluentIterable<SourcePath> unlistedSrcs = FluentIterable.from(paths)
                    .transform(SourcePaths.toSourcePath(getProjectFilesystem()))
                    .filter(Predicates.not(Predicates.in(srcs)));
            if (!unlistedSrcs.isEmpty()) {
                context.logError(new RuntimeException(),
                        "Entry path '%s' transitively uses the following source files which were not "
                                + "included in 'srcs':\n%s",
                        entryPath, Joiner.on('\n').join(unlistedSrcs));
                return 1;
            }

            Hasher hasher = Hashing.sha1().newHasher();
            for (Path path : paths) {
                try {
                    hasher.putUnencodedChars(getProjectFilesystem().computeSha1(path));
                } catch (IOException e) {
                    context.logError(e, "Error hashing input file: %s", path);
                    return 1;
                }
            }

            String inputsHash = hasher.hash().toString();
            buildableContext.addMetadata(METADATA_KEY_FOR_INPUTS_HASH, inputsHash);
            getProjectFilesystem().writeContentsToPath(inputsHash, inputsHashFile);
            return 0;
        }
    });

    return steps.build();
}

From source file:com.google.devtools.build.lib.query2.DepsUnboundedVisitor.java

private void checkIfMissingTargets(Iterable<SkyKey> keys, Map<SkyKey, Iterable<SkyKey>> depMap) {
    if (depMap.size() != Iterables.size(keys)) {
        Iterable<Label> missingTargets = Iterables.transform(
                Iterables.filter(keys, Predicates.not(Predicates.in(depMap.keySet()))), SKYKEY_TO_LABEL);
        env.getEventHandler().handle(Event.warn("Targets were missing from graph: " + missingTargets));
    }//from  www. jav  a2  s . c om
}

From source file:com.facebook.buck.cxx.CxxLinkableEnhancer.java

/**
 * Construct a {@link CxxLink} rule that builds a native linkable from top-level input objects
 * and a dependency tree of {@link NativeLinkable} dependencies.
 *
 * @param params base params used to build the rule.  Target and deps will be overridden.
 * @param nativeLinkableDeps library dependencies that the linkable links in
 * @param immediateLinkableInput framework and libraries of the linkable itself
 *///from  w w w .  j av a  2 s  . c  om
public static CxxLink createCxxLinkableBuildRule(CxxBuckConfig cxxBuckConfig, CxxPlatform cxxPlatform,
        BuildRuleParams params, BuildRuleResolver ruleResolver, final SourcePathResolver resolver,
        SourcePathRuleFinder ruleFinder, BuildTarget target, Linker.LinkType linkType, Optional<String> soname,
        Path output, Linker.LinkableDepType depType, Iterable<? extends NativeLinkable> nativeLinkableDeps,
        Optional<Linker.CxxRuntimeType> cxxRuntimeType, Optional<SourcePath> bundleLoader,
        ImmutableSet<BuildTarget> blacklist, NativeLinkableInput immediateLinkableInput)
        throws NoSuchBuildTargetException {

    // Soname should only ever be set when linking a "shared" library.
    Preconditions.checkState(!soname.isPresent() || SONAME_REQUIRED_LINK_TYPES.contains(linkType));

    // Bundle loaders are only supported for Mach-O bundle libraries
    Preconditions.checkState(!bundleLoader.isPresent() || linkType == Linker.LinkType.MACH_O_BUNDLE);

    // Collect and topologically sort our deps that contribute to the link.
    ImmutableList.Builder<NativeLinkableInput> nativeLinkableInputs = ImmutableList.builder();
    nativeLinkableInputs.add(immediateLinkableInput);
    for (NativeLinkable nativeLinkable : Maps
            .filterKeys(NativeLinkables.getNativeLinkables(cxxPlatform, nativeLinkableDeps, depType),
                    Predicates.not(blacklist::contains))
            .values()) {
        NativeLinkableInput input = NativeLinkables.getNativeLinkableInput(cxxPlatform, depType,
                nativeLinkable);
        LOG.verbose("Native linkable %s returned input %s", nativeLinkable, input);
        nativeLinkableInputs.add(input);
    }
    NativeLinkableInput linkableInput = NativeLinkableInput.concat(nativeLinkableInputs.build());

    // Build up the arguments to pass to the linker.
    ImmutableList.Builder<Arg> argsBuilder = ImmutableList.builder();

    // If we're doing a shared build, pass the necessary flags to the linker, including setting
    // the soname.
    if (linkType == Linker.LinkType.SHARED) {
        argsBuilder.addAll(cxxPlatform.getLd().resolve(ruleResolver).getSharedLibFlag());
    } else if (linkType == Linker.LinkType.MACH_O_BUNDLE) {
        argsBuilder.add(new StringArg("-bundle"));
        // It's possible to build a Mach-O bundle without a bundle loader (logic tests, for example).
        if (bundleLoader.isPresent()) {
            argsBuilder.add(new StringArg("-bundle_loader"), new SourcePathArg(resolver, bundleLoader.get()));
        }
    }
    if (soname.isPresent()) {
        argsBuilder.addAll(StringArg.from(cxxPlatform.getLd().resolve(ruleResolver).soname(soname.get())));
    }

    // Add all arguments from our dependencies.
    argsBuilder.addAll(linkableInput.getArgs());

    // Add all shared libraries
    addSharedLibrariesLinkerArgs(cxxPlatform, resolver, ImmutableSortedSet.copyOf(linkableInput.getLibraries()),
            argsBuilder);

    // Add framework args
    addFrameworkLinkerArgs(cxxPlatform, resolver, ImmutableSortedSet.copyOf(linkableInput.getFrameworks()),
            argsBuilder);

    final ImmutableList<Arg> allArgs = argsBuilder.build();

    return createCxxLinkableBuildRule(cxxBuckConfig, cxxPlatform, params, ruleResolver, resolver, ruleFinder,
            target, output, allArgs, depType, cxxRuntimeType);
}

From source file:forge.game.card.CardLists.java

public static CardCollection getNotKeyword(Iterable<Card> cardList, String keyword) {
    return CardLists.filter(cardList, Predicates.not(CardPredicates.hasKeyword(keyword)));
}

From source file:de.flapdoodle.guava.Transformations.java

public static <T> Partition<T> partition(Collection<T> collection, Predicate<? super T> filter) {
    return new Partition<T>(Collections2.filter(collection, filter),
            Collections2.filter(collection, Predicates.not(filter)));
}