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:com.android.tools.idea.npw.importing.ModulesTable.java

private Collection<ModuleImportSettingsPane> updateModuleEditors() {
    isRefreshing = true;/*from  w ww .j av a2 s  . co m*/
    try {
        ModuleToImport primary = myListModel.getPrimary();
        setModuleNameVisibility(primary != null, myListModel.getAllModules().size() > 1);
        if (primary != null) {
            apply(myPrimaryModuleSettings, primary);
        }

        boolean isFirst = true;
        Collection<ModuleImportSettingsPane> editors = Lists.newLinkedList();

        Set<ModuleToImport> allModules = Sets.newTreeSet(new ModuleComparator(myListModel.getCurrentPath()));
        Iterables.addAll(allModules, Iterables.filter(myListModel.getAllModules(),
                Predicates.not(Predicates.equalTo(myListModel.getPrimary()))));

        for (final ModuleToImport module : allModules) {
            final ModuleImportSettingsPane pane = createModuleSetupPanel(module, isFirst);
            if (pane != null) {
                isFirst = false;
                editors.add(pane);
            }
        }
        return editors;
    } finally {
        isRefreshing = false;
    }
}

From source file:org.apache.brooklyn.util.core.osgi.BundleMaker.java

/** creates a ZIP in a temp file from the given classpath folder, 
 * by recursively taking everything in the referenced directories,
 * treating the given folder as the root,
 * respecting the MANIFEST.MF if present (ie putting it first so it is a valid JAR) */
public File createJarFromClasspathDir(String path) {
    File f = Os.newTempFile(path, "zip");
    ZipOutputStream zout = null;/*from   w  w  w.  jav  a2s  .c  om*/
    try {
        if (Urls.getProtocol(path) == null) {
            // default if no URL is classpath
            path = Os.tidyPath(path);
            if (!path.startsWith("/") && optionalDefaultClassForLoading != null) {
                path = "/" + optionalDefaultClassForLoading.getPackage().getName().replace('.', '/') + "/"
                        + path;
            }
            path = "classpath:" + path;
        }

        if (resources.doesUrlExist(Urls.mergePaths(path, MANIFEST_PATH))) {
            InputStream min = resources.getResourceFromUrl(Urls.mergePaths(path, MANIFEST_PATH));
            zout = new JarOutputStream(new FileOutputStream(f), new Manifest(min));
            addUrlItemRecursively(zout, path, path, Predicates.not(Predicates.equalTo(MANIFEST_PATH)));
        } else {
            zout = new JarOutputStream(new FileOutputStream(f));
            addUrlItemRecursively(zout, path, path, Predicates.alwaysTrue());
        }

        return f;

    } catch (Exception e) {
        throw Exceptions.propagateAnnotated("Error creating ZIP from classpath spec " + path, e);

    } finally {
        Streams.closeQuietly(zout);
    }
}

From source file:com.google.devtools.build.lib.generatedprojecttest.util.RuleSetUtils.java

/**
 * Predicate for checking if a rule class is not in excluded.
 *///from   w  ww  .j  a v a 2 s  . c om
public static Predicate<String> notContainsAnyOf(final ImmutableSet<String> excluded) {
    return Predicates.not(Predicates.in(excluded));
}

From source file:gg.uhc.uhc.modules.team.ListTeamsCommand.java

@Override
protected boolean runCommand(CommandSender sender, OptionSet options) {
    int page = pageSpec.value(options);
    boolean emptyOnly = options.has(emptyOnlySpec);
    boolean showAll = options.has(showAllSpec);

    if (showAll && emptyOnly) {
        sender.sendMessage(ChatColor.RED + "You must provide -e OR -a, you cannot supply both");
        return true;
    }//ww  w . jav  a 2  s . com

    Predicate<Team> predicate;
    String type;

    if (emptyOnly) {
        type = "(empty teams)";
        predicate = Predicates.not(FunctionalUtil.TEAMS_WITH_PLAYERS);
    } else if (showAll) {
        type = "(all teams)";
        predicate = Predicates.alwaysTrue();
    } else {
        type = "(with players)";
        predicate = FunctionalUtil.TEAMS_WITH_PLAYERS;
    }

    List<Team> teams = Lists.newArrayList(Iterables.filter(teamModule.getTeams().values(), predicate));

    if (teams.size() == 0) {
        sender.sendMessage(ChatColor.RED + "No results found for query " + type);
        return true;
    }

    List<List<Team>> partitioned = Lists.partition(teams, COUNT_PER_PAGE);

    if (page > partitioned.size()) {
        sender.sendMessage(ChatColor.RED + "Page " + page + " does not exist");
        return true;
    }

    List<Team> pageItems = partitioned.get(page - 1);

    Map<String, Object> context = ImmutableMap.<String, Object>builder().put("page", page)
            .put("pages", partitioned.size()).put("type", type).put("count", pageItems.size())
            .put("teams", teams.size()).put("multiple", partitioned.size() > 1).build();

    sender.sendMessage(messages.evalTemplate("header", context));

    Joiner joiner = Joiner.on(", ");
    for (Team team : pageItems) {
        String memberString;
        Set<OfflinePlayer> members = team.getPlayers();

        if (members.size() == 0) {
            memberString = NO_MEMBERS;
        } else {
            memberString = joiner
                    .join(Iterables.transform(team.getPlayers(), FunctionalUtil.PLAYER_NAME_FETCHER));
        }

        sender.sendMessage(
                String.format(FORMAT, team.getPrefix() + team.getDisplayName(), team.getName(), memberString));
    }

    return true;
}

From source file:org.onehippo.cms7.essentials.dashboard.utils.HippoNodeUtils.java

public static List<String> getProjectNamespaces(final Session session) {
    try {//w w w. j  a  v  a  2  s  .  c om
        final Node rootNode = session.getRootNode();
        final Node namespace = rootNode.getNode("hippo:namespaces");
        final NodeIterator nodes = namespace.getNodes();
        final Collection<String> namespaceNames = new HashSet<>();
        while (nodes.hasNext()) {
            final Node node = nodes.nextNode();
            final String name = node.getName();
            namespaceNames.add(name);
        }
        return ImmutableList.copyOf(Iterables.filter(namespaceNames, Predicates.not(NAMESPACE_PREDICATE)));
    } catch (RepositoryException e) {
        log.error("Error fetching namespaces", e);
    }
    return Collections.emptyList();

}

From source file:com.datastax.driver.core.utils.SocketChannelMonitor.java

/**
 * <p/>//from   www .j a  va2s  . c  o m
 * Report for all sockets matching the given predicate.  The report format reflects the number of open, closed,
 * live and total sockets created.  This is logged at DEBUG if enabled.
 * <p/>
 * <p/>
 * If TRACE is enabled, each individual socket will be logged as well.
 *
 * @param channelFilter used to determine which sockets to report on.
 */
public void report(Predicate<SocketChannel> channelFilter) {
    if (logger.isDebugEnabled()) {
        Iterable<SocketChannel> channels = matchingChannels(channelFilter);
        Iterable<SocketChannel> open = Iterables.filter(channels, openChannels);
        Iterable<SocketChannel> closed = Iterables.filter(channels, Predicates.not(openChannels));

        logger.debug(
                "Channel states: {} open, {} closed, live {}, total sockets created "
                        + "(including those that don't match filter) {}.",
                Iterables.size(open), Iterables.size(closed), Iterables.size(channels), channelsCreated.get());

        if (logger.isTraceEnabled()) {
            logger.trace("Open channels {}.", open);
            logger.trace("Closed channels {}.", closed);
        }
    }
}

From source file:org.jclouds.cloudsigma2.compute.config.CloudSigmaComputeServiceContextModule.java

@Provides
@Singleton/*from w w  w.  j  a va2 s . c  o m*/
protected Predicate<DriveInfo> supplyDriveUnclaimed(DriveClaimed driveClaimed, Timeouts timeouts) {
    return retry(Predicates.not(driveClaimed), timeouts.nodeRunning, 1000, MILLISECONDS);
}

From source file:com.facebook.buck.command.config.AbstractConfigIgnoredByDaemon.java

@Value.Lazy
public ImmutableMap<String, ImmutableMap<String, String>> getRawConfigForParser() {
    ImmutableMap<String, ImmutableSet<String>> ignoredFields = getIgnoreFieldsForDaemonRestart();
    ImmutableMap<String, ImmutableMap<String, String>> rawSections = getDelegate().getConfig()
            .getSectionToEntries();// w w w.  ja  v a 2 s .c  o m

    // If the raw config doesn't have sections which have ignored fields, then just return it as-is.
    ImmutableSet<String> sectionsWithIgnoredFields = ignoredFields.keySet();
    if (Sets.intersection(rawSections.keySet(), sectionsWithIgnoredFields).isEmpty()) {
        return rawSections;
    }

    // Otherwise, iterate through the config to do finer-grain filtering.
    ImmutableMap.Builder<String, ImmutableMap<String, String>> filtered = ImmutableMap.builder();
    for (Map.Entry<String, ImmutableMap<String, String>> sectionEnt : rawSections.entrySet()) {
        String sectionName = sectionEnt.getKey();

        // If this section doesn't have a corresponding ignored section, then just add it as-is.
        if (!sectionsWithIgnoredFields.contains(sectionName)) {
            filtered.put(sectionEnt);
            continue;
        }

        // If none of this section's entries are ignored, then add it as-is.
        ImmutableMap<String, String> fields = sectionEnt.getValue();
        ImmutableSet<String> ignoredFieldNames = ignoredFields.getOrDefault(sectionName, ImmutableSet.of());
        if (Sets.intersection(fields.keySet(), ignoredFieldNames).isEmpty()) {
            filtered.put(sectionEnt);
            continue;
        }

        // Otherwise, filter out the ignored fields.
        ImmutableMap<String, String> remainingKeys = ImmutableMap
                .copyOf(Maps.filterKeys(fields, Predicates.not(ignoredFieldNames::contains)));
        filtered.put(sectionName, remainingKeys);
    }

    return MoreMaps.filterValues(filtered.build(), Predicates.not(Map::isEmpty));
}

From source file:uk.co.unclealex.executable.generator.scan.ExecutableAnnotationInformationFinderImpl.java

/**
 * Find all {@link Executable} annotations in a list of classes.
 * /*  w w w. ja  v  a 2  s .  c  o m*/
 * @param clazz
 *          The class to search.
 * @return A list of all found methods that have an {@link Executable}
 *         annotation.
 * @throws ExecutableScanException
 *           Thrown if there is an error with {@link Executable} annotations
 *           for the given class.
 */
protected List<ExecutableAnnotationInformation> findExecutableAnnotationInformation(Class<?> clazz)
        throws ExecutableScanException {
    Predicate<Method> isAnnotatedPredicate = Predicates.compose(Predicates.not(Predicates.isNull()),
            new ExecutableAnnotationFunction());
    List<Method> annotatedMethods = Lists
            .newArrayList(Iterables.filter(Arrays.asList(clazz.getDeclaredMethods()), isAnnotatedPredicate));
    List<ExecutableAnnotationInformation> executableAnnotationInformations = Lists.newArrayList();
    if (!annotatedMethods.isEmpty()) {
        if (clazz.getEnclosingClass() != null || clazz.isInterface()) {
            throw new NotTopLevelClassExecutableScanException(clazz);
        }
        for (Method annotatedMethod : annotatedMethods) {
            ExecutableAnnotationInformation executableAnnotationInformation = generateExecutableAnnotationInformation(
                    clazz, annotatedMethod);
            executableAnnotationInformations.add(executableAnnotationInformation);
        }
    }
    return executableAnnotationInformations;
}

From source file:io.pengyuc.jackson.versioning.JsonVersioningDeserializer.java

@Override
public Object deserialize(JsonParser jsonParser, DeserializationContext ctx) throws IOException {
    final ObjectNode jsonNode = jsonParser.readValueAsTree();
    Version jsonVersion = modelVersion;/* w  ww .  j a  va  2 s.co m*/
    try {
        if (jsonVersionProperty != null && jsonNode.has(jsonVersionProperty.getName())) {
            jsonVersion = Version.fromString(jsonNode.get(jsonVersionProperty.getName()).asText());
        } else {
            Object jsonVersionObj = ctx.getAttribute(Version.JsonVersionConfigDeserializing);
            if (jsonVersionObj != null) {
                if (jsonVersionObj instanceof Version)
                    jsonVersion = (Version) jsonVersionObj;
                else
                    jsonVersion = Version.fromString(jsonVersionObj.toString());
            }
        }
    } catch (IllegalArgumentException e) {
        throw ctx.mappingException("Failed to parse version string: %s", e.getMessage(), e);
    }

    if (modelVersion.compareTo(jsonVersion) < 0) {
        throw ctx.mappingException("JSON version (%s) is greater than the latest model version (%s)",
                jsonVersion.toString(), modelVersion.toString());
    }

    Optional<BeanPropertyDefinition> propertyNotInVersion = FluentIterable.from(beanDesc.findProperties())
            // Find the properties that should not be in this version of json
            .filter(Predicates.not(JsonVersioningPredicate.forPropertyDefInVersion(jsonVersion)))
            // see if any of those invalid property names is in the json
            .firstMatch(new Predicate<BeanPropertyDefinition>() {
                @Override
                public boolean apply(BeanPropertyDefinition beanPropertyDefinition) {
                    return jsonNode.has(beanPropertyDefinition.getName());
                }
            });

    if (propertyNotInVersion.isPresent()) {
        throw ctx.mappingException("Property \"%s\" is not in version %s", propertyNotInVersion.get().getName(),
                jsonVersion.toString());
    }

    // If there is no json version in the json body, insert the version to the json version property (if exists)
    if (jsonVersionProperty != null
            && Strings.isNullOrEmpty(jsonNode.findPath(jsonVersionProperty.getName()).asText()))
        jsonNode.put(jsonVersionProperty.getName(), jsonVersion.toString());

    JsonParser postInterceptionParser = new TreeTraversingParser(jsonNode, jsonParser.getCodec());
    postInterceptionParser.nextToken();
    return deserializer.deserialize(postInterceptionParser, ctx);

}