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.urswolfer.intellij.plugin.gerrit.ui.diff.CommentsDiffTool.java

private void handleComments(final DiffPanelImpl diffPanel, final String filePathString) {
    final FilePath filePath = new FilePathImpl(new File(filePathString), false);
    final String relativeFilePath = PathUtils
            .ensureSlashSeparators(getRelativeOrAbsolutePath(project, filePath.getPath()));

    addCommentAction(diffPanel, relativeFilePath, changeInfo);

    gerritUtil.getChangeDetails(changeInfo._number, project, new Consumer<ChangeInfo>() {
        @Override// w w  w  .  j a v a2  s  . com
        public void consume(ChangeInfo changeDetails) {
            gerritUtil.getComments(changeDetails.id, selectedRevisionId, project, true, true,
                    new Consumer<Map<String, List<CommentInfo>>>() {
                        @Override
                        public void consume(Map<String, List<CommentInfo>> comments) {
                            List<CommentInfo> fileComments = comments.get(relativeFilePath);
                            if (fileComments != null) {
                                addCommentsGutter(diffPanel.getEditor2(), relativeFilePath, selectedRevisionId,
                                        Iterables.filter(fileComments, REVISION_COMMENT));
                                if (!baseRevision.isPresent()) {
                                    addCommentsGutter(diffPanel.getEditor1(), relativeFilePath,
                                            selectedRevisionId,
                                            Iterables.filter(fileComments, Predicates.not(REVISION_COMMENT)));
                                }
                            }
                        }
                    });

            if (baseRevision.isPresent()) {
                gerritUtil.getComments(changeDetails.id, baseRevision.get().getFirst(), project, true, true,
                        new Consumer<Map<String, List<CommentInfo>>>() {
                            @Override
                            public void consume(Map<String, List<CommentInfo>> comments) {
                                List<CommentInfo> fileComments = comments.get(relativeFilePath);
                                if (fileComments != null) {
                                    Collections.sort(fileComments, COMMENT_ORDERING);
                                    addCommentsGutter(diffPanel.getEditor1(), relativeFilePath,
                                            baseRevision.get().getFirst(),
                                            Iterables.filter(fileComments, REVISION_COMMENT));
                                }
                            }
                        });
            }

            gerritUtil.setReviewed(changeDetails.id, selectedRevisionId, relativeFilePath, project);
        }
    });
}

From source file:org.mayocat.context.RequestContextInitializer.java

public void requestInitialized(ServletRequestEvent servletRequestEvent) {
    if (isStaticPath(this.getRequestURI(servletRequestEvent))) {
        return;// w  w  w  .  j  av  a2s . c om
    }

    DefaultWebRequestBuilder requestBuilder = new DefaultWebRequestBuilder();

    // 1. Tenant

    String host = getHost(servletRequestEvent);
    String path = getPath(servletRequestEvent);

    Tenant tenant = this.tenantResolver.get().resolve(host, path);
    DefaultWebContext context = new DefaultWebContext(tenant, null);

    // Set the context in the context already, even if we haven't figured out if there is a valid user yet.
    // The context tenant is actually needed to find out the context user and to initialize tenant configurations
    ((ThreadLocalWebContext) this.context).setContext(context);

    if (tenant != null) {
        requestBuilder.tenantRequest(true);
        if (path.indexOf("/tenant/" + tenant.getSlug()) == 0) {
            path = StringUtils.substringAfter(path, "/tenant/" + tenant.getSlug());
            requestBuilder.tenantPrefix("/tenant/" + tenant.getSlug());
        }
    } else {
        requestBuilder.tenantRequest(false);
    }

    requestBuilder.apiRequest(path.indexOf("/api/") == 0);

    // 2. Configurations

    Map<Class, Serializable> configurations = configurationService.getSettings();
    context.setSettings(configurations);

    // 3. User

    Optional<User> user = Optional.absent();
    for (String headerName : Lists.newArrayList("Authorization", "Cookie")) {
        final String headerValue = Strings.nullToEmpty(this.getHeaderValue(servletRequestEvent, headerName));
        for (Authenticator authenticator : this.authenticators.values()) {
            if (authenticator.respondTo(headerName, headerValue)) {
                user = authenticator.verify(headerValue, tenant);
            }
        }
    }

    context.setUser(user.orNull());

    if (tenant != null) {
        // 4. ThemeDefinition
        context.setTheme(themeManager.getTheme());
    }
    // 5. Locale
    LocalesSettings localesSettings = configurationService.getSettings(GeneralSettings.class).getLocales();
    boolean localeSet = false;
    List<Locale> alternativeLocales = FluentIterable.from(localesSettings.getOtherLocales().getValue())
            .filter(Predicates.notNull()).toList();

    String canonicalPath = path;
    if (!alternativeLocales.isEmpty()) {
        for (Locale locale : alternativeLocales) {
            List<String> fragments = ImmutableList.copyOf(
                    Collections2.filter(Arrays.asList(path.split("/")), Predicates.not(IS_NULL_OR_BLANK)));
            if (fragments.size() > 0 && fragments.get(0).equals(locale.toLanguageTag())) {
                context.setLocale(locale);
                context.setAlternativeLocale(true);
                canonicalPath = StringUtils.substringAfter(canonicalPath, "/" + locale);
                localeSet = true;
                break;
            }
        }
    }
    if (!localeSet) {
        context.setLocale(localesSettings.getMainLocale().getValue());
        context.setAlternativeLocale(false);
    }

    if (context.isAlternativeLocale()) {
        path = StringUtils.substringAfter(path, context.getLocale().toLanguageTag());
    }

    // 6. Request
    Optional<Breakpoint> breakpoint = this.breakpointDetector.getBreakpoint(getUserAgent(servletRequestEvent));

    requestBuilder.baseURI(getBaseURI(servletRequestEvent)).canonicalPath(canonicalPath).path(path)
            .breakpoint(breakpoint);

    requestBuilder.secure(isSecure(servletRequestEvent));

    context.setRequest(requestBuilder.build());
}

From source file:org.jclouds.glesys.compute.functions.ServerDetailsToNodeMetadata.java

@Override
public NodeMetadata apply(ServerDetails from) {
    NodeMetadataBuilder builder = new NodeMetadataBuilder();
    builder.ids(from.getId() + "");
    builder.name(from.getHostname());/*from  w w w .  j ava 2  s  . co m*/
    builder.hostname(from.getHostname());
    Location location = FluentIterable.from(locations.get()).firstMatch(idEquals(from.getDatacenter()))
            .orNull();
    checkState(location != null, "no location matched ServerDetails %s", from);
    builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getHostname()));

    // TODO: get glesys to stop stripping out equals and commas!
    if (!isNullOrEmpty(from.getDescription()) && from.getDescription().matches("^[0-9A-Fa-f]+$")) {
        String decoded = new String(base16().lowerCase().decode(from.getDescription()), UTF_8);
        addMetadataAndParseTagsFromCommaDelimitedValue(builder,
                Splitter.on('\n').withKeyValueSeparator("=").split(decoded));
    }

    builder.imageId(from.getTemplateName() + "");
    builder.operatingSystem(parseOperatingSystem(from));
    builder.hardware(new HardwareBuilder().ids(from.getId() + "").ram(from.getMemorySizeMB())
            .processors(ImmutableList.of(new Processor(from.getCpuCores(), 1.0)))
            .volumes(ImmutableList.<Volume>of(new VolumeImpl((float) from.getDiskSizeGB(), true, true)))
            .hypervisor(from.getPlatform()).build());
    builder.status(serverStateToNodeStatus.get(from.getState()));
    Iterable<String> addresses = Iterables
            .filter(Iterables.transform(from.getIps(), new Function<Ip, String>() {

                @Override
                public String apply(Ip arg0) {
                    return Strings.emptyToNull(arg0.getIp());
                }

            }), Predicates.notNull());
    builder.publicAddresses(Iterables.filter(addresses, Predicates.not(IsPrivateIPAddress.INSTANCE)));
    builder.privateAddresses(Iterables.filter(addresses, IsPrivateIPAddress.INSTANCE));
    return builder.build();
}

From source file:org.apache.cassandra.tools.StandaloneScrubber.java

private static void checkManifest(AbstractCompactionStrategy strategy, ColumnFamilyStore cfs,
        Collection<SSTableReader> sstables) {
    WrappingCompactionStrategy wrappingStrategy = (WrappingCompactionStrategy) strategy;
    int maxSizeInMB = (int) ((cfs.getCompactionStrategy().getMaxSSTableBytes()) / (1024L * 1024L));
    if (wrappingStrategy.getWrappedStrategies().size() == 2
            && wrappingStrategy.getWrappedStrategies().get(0) instanceof LeveledCompactionStrategy) {
        System.out.println("Checking leveled manifest");
        Predicate<SSTableReader> repairedPredicate = new Predicate<SSTableReader>() {
            @Override//  w w  w  .j a va  2s  . com
            public boolean apply(SSTableReader sstable) {
                return sstable.isRepaired();
            }
        };

        List<SSTableReader> repaired = Lists.newArrayList(Iterables.filter(sstables, repairedPredicate));
        List<SSTableReader> unRepaired = Lists
                .newArrayList(Iterables.filter(sstables, Predicates.not(repairedPredicate)));

        LeveledManifest repairedManifest = LeveledManifest.create(cfs, maxSizeInMB, repaired);
        for (int i = 1; i < repairedManifest.getLevelCount(); i++) {
            repairedManifest.repairOverlappingSSTables(i);
        }
        LeveledManifest unRepairedManifest = LeveledManifest.create(cfs, maxSizeInMB, unRepaired);
        for (int i = 1; i < unRepairedManifest.getLevelCount(); i++) {
            unRepairedManifest.repairOverlappingSSTables(i);
        }
    }
}

From source file:org.apache.brooklyn.util.exceptions.Exceptions.java

/** returns the first exception in the call chain which is not of common uninteresting types
 * (ie excluding ExecutionException and PropagatedRuntimeExceptions); 
 * or the original throwable if all are uninteresting 
 *///from  w w w .  j a va 2  s  .  co m
public static Throwable getFirstInteresting(Throwable throwable) {
    return Iterables.tryFind(getCausalChain(throwable), Predicates.not(IS_THROWABLE_BORING)).or(throwable);
}

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

public static CardCollection getNotType(Iterable<Card> cardList, String cardType) {
    return CardLists.filter(cardList, Predicates.not(CardPredicates.isType(cardType)));
}

From source file:com.khs.sherpa.servlet.request.DefaultSherpaRequest.java

@SuppressWarnings("unchecked")
protected Object proccess() throws SherpaRuntimeException {
    if (!isRestful()) {
        requestProcessor = new DefaultRequestProcessor();
    } else {// w  w  w .  j  av  a2s.  com
        requestProcessor = new RestfulRequestProcessor(applicationContext);
    }

    String endpoint = requestProcessor.getEndpoint(request);
    String action = requestProcessor.getAction(request);
    String httpMethod = request.getMethod();

    if (StringUtils.isEmpty(endpoint)) {
        if (action.equals(Constants.AUTHENTICATE_ACTION)) {
            return this.processAuthenication();
        } else if (action.equals(Constants.VALID)) {
            return this.processValid();
        }
    }

    Object target = null;
    Set<Method> methods = null;

    try {
        String userid = request.getHeader("userid");
        if (userid == null) {
            userid = request.getParameter("userid");
        }
        String token = request.getHeader("token");
        if (token == null) {
            token = request.getParameter("token");
        }

        this.hasPermission(applicationContext.getType(endpoint), userid, token);

        target = applicationContext.getManagedBean(endpoint);

        if (ApplicationContextAware.class.isAssignableFrom(target.getClass())) {
            ((ApplicationContextAware) target).setApplicationContext(applicationContext);
        }

        methods = Reflections.getAllMethods(applicationContext.getType(endpoint),
                Predicates.and(Predicates.not(SherpaPredicates.withAssignableFrom(Object.class)),
                        ReflectionUtils.withModifier(Modifier.PUBLIC),
                        Predicates.not(ReflectionUtils.withModifier(Modifier.ABSTRACT)),
                        Predicates.not(SherpaPredicates.withGeneric()),
                        Predicates.and(SherpaPredicates.withAssignableFrom(
                                Enhancer.isEnhanced(target.getClass()) ? target.getClass().getSuperclass()
                                        : target.getClass())),
                        Predicates.or(ReflectionUtils.withName(action),
                                Predicates.and(ReflectionUtils.withAnnotation(Action.class),
                                        SherpaPredicates.withActionAnnotationValueEqualTo(action)))));

        if (methods.size() == 0) {
            throw new SherpaActionNotFoundException(action);
        }

    } catch (NoSuchManagedBeanExcpetion e) {
        throw new SherpaRuntimeException(e);
    }

    return this.processEndpoint(target, methods.toArray(new Method[] {}), httpMethod);
}

From source file:com.twitter.common.application.modules.LocalServiceRegistry.java

/**
 * Launches the local services if not already launched, otherwise this is a no-op.
 *///from  w  w  w .  j a  v a2s. co  m
void ensureLaunched() {
    if (primarySocket == null) {
        ImmutableList.Builder<LocalService> builder = ImmutableList.builder();

        for (ServiceRunner runner : runnerProvider.get()) {
            try {
                LocalService service = runner.launch();
                builder.add(service);
                shutdownRegistry.addAction(service.shutdownCommand);
            } catch (LaunchException e) {
                throw new IllegalStateException("Failed to launch " + runner, e);
            }
        }

        List<LocalService> localServices = builder.build();
        Iterable<LocalService> primaries = Iterables.filter(localServices, IS_PRIMARY);
        switch (Iterables.size(primaries)) {
        case 0:
            primarySocket = Optional.absent();
            break;

        case 1:
            primarySocket = Optional.of(SERVICE_TO_SOCKET.apply(Iterables.getOnlyElement(primaries)));
            break;

        default:
            throw new IllegalArgumentException("More than one primary local service: " + primaries);
        }

        Iterable<LocalService> auxSinglyNamed = Iterables.concat(FluentIterable.from(localServices)
                .filter(Predicates.not(IS_PRIMARY)).transform(AUX_NAME_BREAKOUT));

        Map<String, LocalService> byName;
        try {
            byName = Maps.uniqueIndex(auxSinglyNamed, GET_NAME);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Auxiliary services with identical names.", e);
        }

        auxiliarySockets = ImmutableMap.copyOf(Maps.transformValues(byName, SERVICE_TO_SOCKET));
    }
}

From source file:org.immutables.check.ObjectChecker.java

public void satisfies(Predicate<? super T> predicate) {
    if (negate) {
        predicate = Predicates.not(predicate);
    }/*from  www .  ja va2  s .  c om*/
    verifyUsingMatcher(predicate.apply(actualValue), Is.is(true));
}

From source file:com.google.devtools.build.android.dexer.DexFileSplitter.java

@VisibleForTesting
static void splitIntoShards(Options options) throws IOException {
    checkArgument(!options.minimalMainDex || options.mainDexListFile != null,
            "--minimal-main-dex not allowed without --main-dex-list");

    if (!Files.exists(options.outputDirectory)) {
        Files.createDirectories(options.outputDirectory);
    }/*w  w  w  .  j a v a2  s. c  o m*/

    ImmutableSet<String> classesInMainDex = options.mainDexListFile != null
            ? ImmutableSet.copyOf(Files.readAllLines(options.mainDexListFile, UTF_8))
            : null;
    try (Closer closer = Closer.create();
            DexFileSplitter out = new DexFileSplitter(options.outputDirectory, options.maxNumberOfIdxPerDex)) {
        // 1. Scan inputs in order and keep first occurrence of each class, keeping all zips open.
        // We don't process anything yet so we can shard in sorted order, which is what dx would do
        // if presented with a single jar containing all the given inputs.
        // TODO(kmb): Abandon alphabetic sorting to process each input fully before moving on (still
        // requires scanning inputs twice for main dex list).
        LinkedHashMap<String, ZipFile> deduped = new LinkedHashMap<>();
        for (Path inputArchive : options.inputArchives) {
            ZipFile zip = closer.register(new ZipFile(inputArchive.toFile()));
            zip.stream().filter(ZipEntryPredicates.suffixes(".dex", ".class"))
                    .forEach(e -> deduped.putIfAbsent(e.getName(), zip));
        }
        ImmutableList<Map.Entry<String, ZipFile>> files = deduped.entrySet().stream()
                .sorted(Comparator.comparing(e -> e.getKey(), ZipEntryComparator::compareClassNames))
                .collect(ImmutableList.toImmutableList());

        // 2. Process each class in desired order, rolling from shard to shard as needed.
        if (classesInMainDex == null || classesInMainDex.isEmpty()) {
            out.processDexFiles(files, Predicates.alwaysTrue());
        } else {
            // To honor --main_dex_list make two passes:
            // 1. process only the classes listed in the given file
            // 2. process the remaining files
            Predicate<String> mainDexFilter = ZipEntryPredicates.classFileNameFilter(classesInMainDex);
            out.processDexFiles(files, mainDexFilter);
            // Fail if main_dex_list is too big, following dx's example
            checkState(out.shardsWritten() == 0,
                    "Too many classes listed in main dex list file " + "%s, main dex capacity exceeded",
                    options.mainDexListFile);
            if (options.minimalMainDex) {
                out.nextShard(); // Start new .dex file if requested
            }
            out.processDexFiles(files, Predicates.not(mainDexFilter));
        }
    }
}