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

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

Introduction

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

Prototype

@GwtCompatible(serializable = true)
public static <T> Predicate<T> notNull() 

Source Link

Document

Returns a predicate that evaluates to true if the object reference being tested is not null.

Usage

From source file:com.analog.lyric.dimple.model.core.EdgeStateList.java

/**
 * Returns collection of non-null entries.
 * @since 0.08
 */
Collection<EdgeState> allEdgeState() {
    return new EdgeStateCollection(_nEdges, Predicates.notNull());
}

From source file:org.apache.isis.viewer.wicket.ui.components.widgets.linkandlabel.ActionLinkFactoryAbstract.java

protected ActionLink newLink(final String linkId, final ObjectAction action,
        final ToggledMementosProvider toggledMementosProviderIfAny) {

    final ActionModel actionModel = ActionModel.create(this.targetEntityModel, action);

    final ActionLink link = new ActionLink(linkId, actionModel, action) {
        private static final long serialVersionUID = 1L;

        protected void doOnClick(final AjaxRequestTarget target) {

            if (toggledMementosProviderIfAny != null) {

                final PersistenceSession persistenceSession = getIsisSessionFactory().getCurrentSession()
                        .getPersistenceSession();
                final SpecificationLoader specificationLoader = getIsisSessionFactory()
                        .getSpecificationLoader();

                final List<ObjectAdapterMemento> selectedMementos = toggledMementosProviderIfAny.getToggles();

                final ImmutableList<Object> selectedPojos = FluentIterable.from(selectedMementos)
                        .transform(new Function<ObjectAdapterMemento, Object>() {
                            @Nullable/*from ww w .j  a va 2  s  .c  om*/
                            @Override
                            public Object apply(@Nullable final ObjectAdapterMemento input) {
                                if (input == null) {
                                    return null;
                                }
                                final ObjectAdapter objectAdapter = input.getObjectAdapter(
                                        AdapterManager.ConcurrencyChecking.NO_CHECK, persistenceSession,
                                        specificationLoader);
                                return objectAdapter != null ? objectAdapter.getObject() : null;
                            }
                        }).filter(Predicates.notNull()).toList();

                final ActionPrompt actionPrompt = ActionParameterDefaultsFacetFromAssociatedCollection
                        .withSelected(selectedPojos,
                                new ActionParameterDefaultsFacetFromAssociatedCollection.SerializableRunnable<ActionPrompt>() {
                                    public ActionPrompt call() {
                                        return performOnClick(target);
                                    }
                                });
                if (actionPrompt != null) {
                    actionPrompt.setOnClose(new ActionPrompt.CloseHandler() {
                        @Override
                        public void close(final AjaxRequestTarget target) {
                            toggledMementosProviderIfAny.clearToggles(target);
                        }
                    });
                }

            } else {
                performOnClick(target);
            }
        }

        private ActionPrompt performOnClick(final AjaxRequestTarget target) {
            return ActionLinkFactoryAbstract.this.onClick(this, target);
        }

    };

    link.add(new CssClassAppender("noVeil"));
    return link;
}

From source file:com.ignorelist.kassandra.steam.scraper.Configuration.java

public static Configuration fromProperties(Properties properties) {
    Configuration configuration = new Configuration();
    String sharedConfigPaths = properties.getProperty(CONFIG_SHARED_CONFIG_PATHS);
    if (null != sharedConfigPaths) {
        Set<Path> paths = Sets.newHashSet(
                Iterables.filter(Iterables.transform(Splitter.on(':').split(sharedConfigPaths), STRING_TO_PATH),
                        Predicates.notNull()));
        configuration.setSharedConfigPaths(paths);
    }// w  w  w. j a v a2 s.co m
    String tagTypes = properties.getProperty(CONFIG_TAG_TYPES);
    if (null != tagTypes) {
        Set<TagType> tags = Sets.newHashSet(
                Iterables.filter(Iterables.transform(Splitter.on(PROPERTIES_VALUE_SEPERATOR).split(tagTypes),
                        STRING_TO_TAG_TYPE), Predicates.notNull()));
        configuration.setTagTypes(tags);
    }
    configuration.setWhiteList(STRING_TO_PATH.apply(properties.getProperty(CONFIG_WHITE_LIST)));
    String removeNotWhiteListed = properties.getProperty(CONFIG_REMOVE_NOT_WHITE_LISTED);
    if (null != removeNotWhiteListed) {
        configuration.setRemoveNotWhiteListed(Boolean.valueOf(removeNotWhiteListed));
    }
    configuration.setReplacements(STRING_TO_PATH.apply(properties.getProperty(CONFIG_REPLACEMENTS)));
    String downloadThreads = properties.getProperty(CONFIG_DOWNLOAD_THREADS);
    if (null != downloadThreads) {
        try {
            configuration.setDownloadThreads(Integer.valueOf(downloadThreads));
        } catch (NumberFormatException nfe) {
            LOG.log(Level.WARNING, "failed to parse downloadThreads: {0}", downloadThreads);
        }
    }
    String cacheExpiryDays = properties.getProperty(CONFIG_CACHE_EXPIRY_DAYS);
    if (null != cacheExpiryDays) {
        try {
            final Integer d = Integer.valueOf(cacheExpiryDays);
            if (d >= 1) {
                configuration.setCacheExpiryDays(d);
            } else {
                LOG.log(Level.WARNING, "cacheExpiryDays must be >= 1");
            }
        } catch (NumberFormatException nfe) {
            LOG.log(Level.WARNING, "failed to parse cacheExpiryDays: {0}", downloadThreads);
        }
    }
    return configuration;
}

From source file:org.locationtech.geogig.geotools.plumbing.ExportOp.java

/**
 * Executes the export operation using the parameters that have been specified.
 * /*from  www.  j  a  v  a  2  s  .  c  om*/
 * @return a FeatureCollection with the specified features
 */
@Override
protected SimpleFeatureStore _call() {
    final ObjectDatabase database = objectDatabase();
    if (filterFeatureTypeId != null) {
        RevObject filterType = database.getIfPresent(filterFeatureTypeId);
        checkArgument(filterType instanceof RevFeatureType, "Provided filter feature type is does not exist");
    }

    final SimpleFeatureStore targetStore = getTargetStore();

    final String refspec = resolveRefSpec();
    final String treePath = refspec.substring(refspec.indexOf(':') + 1);
    final RevTree rootTree = resolveRootTree(refspec);
    final NodeRef typeTreeRef = resolTypeTreeRef(refspec, treePath, rootTree);

    final ObjectId defaultMetadataId = typeTreeRef.getMetadataId();

    final RevTree typeTree = database.getTree(typeTreeRef.objectId());

    final ProgressListener progressListener = getProgressListener();

    progressListener.started();
    progressListener
            .setDescription("Exporting from " + path + " to " + targetStore.getName().getLocalPart() + "... ");

    final Iterator<SimpleFeature> filtered;
    {
        final Iterator<SimpleFeature> plainFeatures = getFeatures(typeTree, database,

                defaultMetadataId, progressListener);

        Iterator<SimpleFeature> adaptedFeatures = adaptToArguments(plainFeatures, defaultMetadataId);

        Iterator<Optional<Feature>> transformed = Iterators.transform(adaptedFeatures, ExportOp.this.function);

        Iterator<SimpleFeature> result = Iterators
                .filter(Iterators.transform(transformed, new Function<Optional<Feature>, SimpleFeature>() {
                    @Override
                    public SimpleFeature apply(Optional<Feature> input) {
                        return (SimpleFeature) input.orNull();
                    }
                }), Predicates.notNull());

        // check the resulting schema has something to contribute
        PeekingIterator<SimpleFeature> peekingIt = Iterators.peekingIterator(result);
        if (peekingIt.hasNext()) {
            Function<AttributeDescriptor, String> toString = new Function<AttributeDescriptor, String>() {
                @Override
                public String apply(AttributeDescriptor input) {
                    return input.getLocalName();
                }
            };
            SimpleFeature peek = peekingIt.peek();
            Set<String> sourceAtts = new HashSet<String>(
                    Lists.transform(peek.getFeatureType().getAttributeDescriptors(), toString));
            Set<String> targetAtts = new HashSet<String>(
                    Lists.transform(targetStore.getSchema().getAttributeDescriptors(), toString));
            if (Sets.intersection(sourceAtts, targetAtts).isEmpty()) {
                throw new GeoToolsOpException(StatusCode.UNABLE_TO_ADD,
                        "No common attributes between source and target feature types");
            }
        }

        filtered = peekingIt;
    }
    FeatureCollection<SimpleFeatureType, SimpleFeature> asFeatureCollection = new BaseFeatureCollection<SimpleFeatureType, SimpleFeature>() {

        @Override
        public FeatureIterator<SimpleFeature> features() {

            return new DelegateFeatureIterator<SimpleFeature>(filtered);
        }
    };

    // add the feature collection to the feature store
    final Transaction transaction;
    if (transactional) {
        transaction = new DefaultTransaction("create");
    } else {
        transaction = Transaction.AUTO_COMMIT;
    }
    try {
        targetStore.setTransaction(transaction);
        try {
            targetStore.addFeatures(asFeatureCollection);
            transaction.commit();
        } catch (final Exception e) {
            if (transactional) {
                transaction.rollback();
            }
            Throwables.propagateIfInstanceOf(e, GeoToolsOpException.class);
            throw new GeoToolsOpException(e, StatusCode.UNABLE_TO_ADD);
        } finally {
            transaction.close();
        }
    } catch (IOException e) {
        throw new GeoToolsOpException(e, StatusCode.UNABLE_TO_ADD);
    }

    progressListener.complete();

    return targetStore;

}

From source file:com.analog.lyric.dimple.model.core.EdgeStateList.java

Collection<Edge> allEdges() {
    return new EdgeCollection(_nEdges, Predicates.notNull());
}

From source file:org.apache.beam.runners.spark.metrics.WithMetricsSupport.java

private Function<Map.Entry<String, Metric>, Map<String, Gauge>> beamMetricToGauges() {
    return new Function<Map.Entry<String, Metric>, Map<String, Gauge>>() {
        @Override/* www. jav a 2 s  .  c  o m*/
        public Map<String, Gauge> apply(final Map.Entry<String, Metric> entry) {
            final Map<String, ?> metrics = ((SparkBeamMetric) entry.getValue()).renderAll();
            final String parentName = entry.getKey();
            final Map<String, Gauge> gaugeMap = Maps.transformEntries(metrics, toGauge());
            final Map<String, Gauge> fullNameGaugeMap = Maps.newLinkedHashMap();
            for (Map.Entry<String, Gauge> gaugeEntry : gaugeMap.entrySet()) {
                fullNameGaugeMap.put(parentName + "." + gaugeEntry.getKey(), gaugeEntry.getValue());
            }
            return Maps.filterValues(fullNameGaugeMap, Predicates.notNull());
        }
    };
}

From source file:org.eclipse.viatra.integration.gmf.GMFModelConnector.java

@Override
protected Collection<EObject> getSelectedEObjects(ISelection selection) {
    if (selection instanceof IStructuredSelection) {
        Iterator<IGraphicalEditPart> selectionIterator = Iterators
                .filter((((IStructuredSelection) selection).iterator()), IGraphicalEditPart.class);
        return Lists.newArrayList(Iterators
                .filter(Iterators.transform(selectionIterator, new Function<IGraphicalEditPart, EObject>() {

                    @Override/*from w  w  w .  j  av  a2  s.  com*/
                    public EObject apply(IGraphicalEditPart input) {
                        return input.resolveSemanticElement();
                    }
                }), Predicates.notNull()));
    } else {
        return super.getSelectedEObjects();
    }
}

From source file:com.facebook.buck.android.PreDexMerge.java

private void addStepsForSplitDex(ImmutableList.Builder<Step> steps, BuildContext context,
        BuildableContext buildableContext) {

    // Collect all of the DexWithClasses objects to use for merging.
    ImmutableList<DexWithClasses> dexFilesToMerge = FluentIterable.from(preDexDeps)
            .transform(DexWithClasses.TO_DEX_WITH_CLASSES).filter(Predicates.notNull()).toList();

    final SplitDexPaths paths = new SplitDexPaths();

    final ImmutableSet<Path> secondaryDexDirectories = ImmutableSet.of(paths.metadataDir, paths.jarfilesDir);

    // Do not clear existing directory which might contain secondary dex files that are not
    // re-merged (since their contents did not change).
    steps.add(new MkdirStep(paths.jarfilesSubdir));
    steps.add(new MkdirStep(paths.successDir));

    steps.add(new MakeCleanDirectoryStep(paths.metadataSubdir));
    steps.add(new MakeCleanDirectoryStep(paths.scratchDir));

    buildableContext.addMetadata(SECONDARY_DEX_DIRECTORIES_KEY,
            Iterables.transform(secondaryDexDirectories, Functions.toStringFunction()));

    buildableContext.recordArtifact(primaryDexPath);
    buildableContext.recordArtifactsInDirectory(paths.jarfilesSubdir);
    buildableContext.recordArtifactsInDirectory(paths.metadataSubdir);
    buildableContext.recordArtifactsInDirectory(paths.successDir);

    PreDexedFilesSorter preDexedFilesSorter = new PreDexedFilesSorter(uberRDotJava.getRDotJavaDexWithClasses(),
            dexFilesToMerge, dexSplitMode.getPrimaryDexPatterns(), paths.scratchDir,
            dexSplitMode.getLinearAllocHardLimit(), dexSplitMode.getDexStore(), paths.jarfilesSubdir);
    final PreDexedFilesSorter.Result sortResult = preDexedFilesSorter.sortIntoPrimaryAndSecondaryDexes(context,
            steps);/*from   w w w  .jav a  2 s  . c  o m*/

    steps.add(new SmartDexingStep(primaryDexPath, Suppliers.ofInstance(sortResult.primaryDexInputs),
            Optional.of(paths.jarfilesSubdir),
            Optional.of(Suppliers.ofInstance(sortResult.secondaryOutputToInputs)),
            sortResult.dexInputHashesProvider, paths.successDir, /* numThreads */ Optional.<Integer>absent(),
            AndroidBinary.DX_MERGE_OPTIONS));

    // Record the primary dex SHA1 so exopackage apks can use it to compute their ABI keys.
    // Single dex apks cannot be exopackages, so they will never need ABI keys.
    steps.add(new RecordFileSha1Step(primaryDexPath, PRIMARY_DEX_HASH_KEY, buildableContext));

    steps.add(new AbstractExecutionStep("write_metadata_txt") {
        @Override
        public int execute(ExecutionContext executionContext) {
            ProjectFilesystem filesystem = executionContext.getProjectFilesystem();
            Map<Path, DexWithClasses> metadataTxtEntries = sortResult.metadataTxtDexEntries;
            List<String> lines = Lists.newArrayListWithCapacity(metadataTxtEntries.size());
            try {
                for (Map.Entry<Path, DexWithClasses> entry : metadataTxtEntries.entrySet()) {
                    Path pathToSecondaryDex = entry.getKey();
                    String containedClass = Iterables.get(entry.getValue().getClassNames(), 0);
                    containedClass = containedClass.replace('/', '.');
                    String hash = filesystem.computeSha1(pathToSecondaryDex);
                    lines.add(
                            String.format("%s %s %s", pathToSecondaryDex.getFileName(), hash, containedClass));
                }
                filesystem.writeLinesToPath(lines, paths.metadataFile);
            } catch (IOException e) {
                executionContext.logError(e, "Failed when writing metadata.txt multi-dex.");
                return 1;
            }
            return 0;
        }
    });
}

From source file:org.mitre.oauth2.service.impl.DefaultSystemScopeService.java

@Override
public Set<String> toStrings(Set<SystemScope> scope) {
    if (scope == null) {
        return null;
    } else {/*from w w  w  . j a  va  2s .  com*/
        return new LinkedHashSet<String>(
                Collections2.filter(Collections2.transform(scope, systemScopeToString), Predicates.notNull()));
    }
}

From source file:org.robotframework.ide.eclipse.main.plugin.tableeditor.source.SuiteSourceQuickAssistProcessor.java

private List<ICompletionProposal> computeRobotProblemsAssistants(
        final IQuickAssistInvocationContext invocationContext, final IMarker marker,
        final IProblemCause cause) {

    final List<? extends IMarkerResolution> fixers = cause.createFixers(marker);
    final Iterable<RedSuiteMarkerResolution> suiteFixers = filter(fixers, RedSuiteMarkerResolution.class);
    final Iterable<RedXmlConfigMarkerResolution> redXmlFixers = filter(fixers,
            RedXmlConfigMarkerResolution.class);

    final Iterable<ICompletionProposal> suiteRepairProposals = filter(
            transform(suiteFixers, new Function<RedSuiteMarkerResolution, ICompletionProposal>() {

                @Override// w w w  .j  a  va  2s .  c om
                public ICompletionProposal apply(final RedSuiteMarkerResolution resolution) {
                    return resolution.asContentProposal(marker,
                            invocationContext.getSourceViewer().getDocument(), suiteModel).orElse(null);
                }
            }), Predicates.notNull());
    final Iterable<ICompletionProposal> redXmlRepairProposals = filter(
            transform(redXmlFixers, new Function<RedXmlConfigMarkerResolution, ICompletionProposal>() {

                @Override
                public ICompletionProposal apply(final RedXmlConfigMarkerResolution resolution) {
                    return resolution.asContentProposal(marker);
                }
            }), Predicates.notNull());

    final List<ICompletionProposal> proposals = newArrayList(redXmlRepairProposals);
    proposals.addAll(newArrayList(suiteRepairProposals));
    return proposals;
}