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

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

Introduction

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

Prototype

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

Source Link

Document

Returns a predicate that always evaluates to true .

Usage

From source file:de.metas.ui.web.material.cockpit.filters.ProductFilterUtil.java

public static Predicate<I_M_Product> toPredicate(@NonNull final List<DocumentFilter> filters) {
    if (filters.isEmpty()) {
        return Predicates.alwaysTrue();
    }//from   w w  w .  j  a  v  a 2s  .  com

    final ProductFilterVO productFilterVO = extractProductFilterVO(filters);
    return product -> doesProductMatchFilter(product, productFilterVO);
}

From source file:org.geogit.storage.RevSHA1Tree.java

/**
 * Returns an iterator over this tree children
 * //from ww w. j  av  a  2s . c o  m
 * @see org.geogit.api.RevTree#iterator(com.google.common.base.Predicate)
 */
@SuppressWarnings("unchecked")
@Override
public Iterator<Ref> iterator(Predicate<Ref> filter) {
    Preconditions.checkState(isNormalized(),
            "iterator() should only be called on a normalized tree to account for element deletions");
    if (filter == null) {
        filter = Predicates.alwaysTrue();
    }

    if (myEntries.isEmpty() && mySubTrees.isEmpty()) {
        return Collections.EMPTY_SET.iterator();
    }
    if (!mySubTrees.isEmpty()) {
        Iterator<Ref>[] iterators = new Iterator[mySubTrees.size()];
        int i = 0;
        for (Ref subtreeRef : mySubTrees.values()) {
            iterators[i] = new LazySubtreeIterator(this.db, subtreeRef.getObjectId(), this.depth + 1, filter);
            i++;
        }
        return Iterators.concat(iterators);
    }

    // we have only content entries, return them in our internal order
    Map<ObjectId, Ref> sorted = new TreeMap<ObjectId, Ref>();
    for (Ref ref : myEntries.values()) {
        if (filter.apply(ref)) {
            sorted.put(ObjectId.forString(ref.getName()), ref);
        }
    }
    return sorted.values().iterator();
}

From source file:org.sosy_lab.cpachecker.cpa.arg.ARGStatistics.java

private void exportARG(final ARGState rootState, final Predicate<Pair<ARGState, ARGState>> isTargetPathEdge) {
    SetMultimap<ARGState, ARGState> relevantSuccessorRelation = ARGUtils.projectARG(rootState,
            ARGUtils.CHILDREN_OF_STATE, ARGUtils.RELEVANT_STATE);
    Function<ARGState, Collection<ARGState>> relevantSuccessorFunction = Functions
            .forMap(relevantSuccessorRelation.asMap(), ImmutableSet.<ARGState>of());

    if (argFile != null) {
        try (Writer w = Files.openOutputFile(argFile)) {
            ARGToDotWriter.write(w, rootState, ARGUtils.CHILDREN_OF_STATE, Predicates.alwaysTrue(),
                    isTargetPathEdge);//from  w  ww. jav  a  2  s.  c  om
        } catch (IOException e) {
            cpa.getLogger().logUserException(Level.WARNING, e, "Could not write ARG to file");
        }
    }

    if (simplifiedArgFile != null) {
        try (Writer w = Files.openOutputFile(simplifiedArgFile)) {
            ARGToDotWriter.write(w, rootState, relevantSuccessorFunction, Predicates.alwaysTrue(),
                    Predicates.alwaysFalse());
        } catch (IOException e) {
            cpa.getLogger().logUserException(Level.WARNING, e, "Could not write ARG to file");
        }
    }

    assert (refinementGraphUnderlyingWriter == null) == (refinementGraphWriter == null);
    if (refinementGraphUnderlyingWriter != null) {
        try (Writer w = refinementGraphUnderlyingWriter) { // for auto-closing
            refinementGraphWriter.writeSubgraph(rootState, relevantSuccessorFunction, Predicates.alwaysTrue(),
                    Predicates.alwaysFalse());
            refinementGraphWriter.finish();

        } catch (IOException e) {
            cpa.getLogger().logUserException(Level.WARNING, e, "Could not write refinement graph to file");
        }
    }
}

From source file:org.sosy_lab.cpachecker.core.algorithm.pdr.transition.BackwardTransition.java

public FluentIterable<Block> getBlocksTo(Iterable<CFANode> pSuccessorLocations)
        throws CPAException, InterruptedException {
    return getBlocksTo(pSuccessorLocations, Predicates.alwaysTrue());
}

From source file:com.google.dart.engine.utilities.general.MemoryUtilities.java

/**
 * Return an object representing the approximate size in bytes of the object graph containing the
 * given object and all objects reachable from it. The actual size of an individual object depends
 * on the implementation of the virtual machine running on the current platform and cannot be
 * computed accurately. However, the value returned is close enough to allow the sizes of two
 * different object structures to be compared with a reasonable degree of confidence.
 * <p>//  w  ww . j a  v a 2 s. co  m
 * Note that this method cannot be used to find the size of primitive values. Primitive values
 * will be automatically boxed and this method will return the size of the boxed primitive, not
 * the size of the primitive itself.
 * 
 * @param object the object at the root of the graph whose size is to be returned
 * @return the approximate size of the object graph containing the given object
 */
public static MemoryUsage measureMemoryUsage(Object object) {
    return measureMemoryUsage(object, Predicates.alwaysTrue());
}

From source file:org.obm.push.mail.imap.LinagoraMailboxService.java

@Override
public Optional<MailboxFolder> getFolder(UserDataRequest udr, MailboxPath path) throws MailException {
    try {//from   w ww  . j av a 2s . c  o  m
        ListResult listFolders = imapClientProvider.getImapClient(udr).listAll(NO_REFERENCE_NAME,
                path.getPath());

        return Iterables.tryFind(mailboxFolders(listFolders), Predicates.alwaysTrue());
    } catch (OpushLocatorException | IMAPException e) {
        throw new MailException(e);
    } catch (ImapTimeoutException e) {
        throw new TimeoutException(e);
    }
}

From source file:org.geogig.osm.cli.commands.OSMHistoryImport.java

private Predicate<Changeset> parseFilter(Envelope env) {
    if (env == null) {
        return Predicates.alwaysTrue();
    }/*from   w  w w . ja  v  a  2 s  . c om*/
    BBoxFiler filter = new BBoxFiler(env);
    return filter;
}

From source file:org.apache.brooklyn.rest.resources.EntityConfigResource.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override/*from www  .ja v a2  s .c o  m*/
public void set(String application, String entityToken, String configName, Boolean recurse, Object newValue) {
    final Entity entity = brooklyn().getEntity(application, entityToken);
    if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.MODIFY_ENTITY, entity)) {
        throw WebResourceUtils.unauthorized("User '%s' is not authorized to modify entity '%s'",
                Entitlements.getEntitlementContext().user(), entity);
    }

    ConfigKey ck = findConfig(entity, configName);
    LOG.debug("REST setting config " + configName + " on " + entity + " to " + newValue);
    ((EntityInternal) entity).config().set(ck, TypeCoercions.coerce(newValue, ck.getTypeToken()));
    if (Boolean.TRUE.equals(recurse)) {
        for (Entity e2 : Entities.descendants(entity, Predicates.alwaysTrue(), false)) {
            ((EntityInternal) e2).config().set(ck, newValue);
        }
    }
}

From source file:org.sonatype.nexus.timeline.feeds.sources.AbstractFeedSource.java

/**
 * Creates predicates out of the map keys and values. It consider entry key for key, and value as "allowed value".
 * Hence, for values, one might use comma separated values. It uses {@link AnyOfFilter} to implement predicate for
 * each map entry. Values are turned into sets in method {@link #valueSet(String)}.
 * <p/>// w ww .ja  v a  2  s  .co  m
 * Example HTTP request with query parameters {@code ?foo=1&bar=a,b,c} will be turned into predicates like
 * (pseudo code):
 * <pre>
 *   and(
 *     value of "foo" member of {1}, // this basically means "foo=1"
 *     value of "bar" member of {a,b,c}, // this basically means "bar" value is in set of {a,b,c}
 *   );
 * </pre>
 *
 * @see {@link AnyOfFilter}
 * @see {@link #valueSet(String)}
 */
protected Predicate<Entry> filters(final Map<String, String> params) {
    if (params.isEmpty()) {
        return Predicates.alwaysTrue();
    }
    final List<Predicate<Entry>> filters = Lists.newArrayList();
    for (Map.Entry<String, String> param : params.entrySet()) {
        // TODO: maybe all with "_" as prefix? But then how to filter for type and subType?
        if (param.getKey().equals("_dc")) {
            continue;
        }
        final AnyOfFilter filter = new AnyOfFilter(param.getKey(), valueSet(param.getValue()));
        filters.add(filter);
    }
    return Predicates.and(filters);
}

From source file:org.janusgraph.graphdb.log.StandardTransactionLogProcessor.java

private void fixSecondaryFailure(final StandardTransactionId txId, final TxEntry entry) {
    logRecoveryMsg("Attempting to repair partially failed transaction [%s]", txId);
    if (entry.entry == null) {
        logRecoveryMsg("Trying to repair expired or unpersisted transaction [%s] (Ignore in startup)", txId);
        return;/*from w  w w.jav  a  2s.c  o m*/
    }

    boolean userLogFailure = true;
    boolean secIndexFailure = true;
    final Predicate<String> isFailedIndex;
    final TransactionLogHeader.Entry commitEntry = entry.entry;
    final TransactionLogHeader.SecondaryFailures secFail = entry.failures;
    if (secFail != null) {
        userLogFailure = secFail.userLogFailure;
        secIndexFailure = !secFail.failedIndexes.isEmpty();
        isFailedIndex = new Predicate<String>() {
            @Override
            public boolean apply(@Nullable String s) {
                return secFail.failedIndexes.contains(s);
            }
        };
    } else {
        isFailedIndex = Predicates.alwaysTrue();
    }

    // I) Restore external indexes
    if (secIndexFailure) {
        //1) Collect all elements (vertices and relations) and the indexes for which they need to be restored
        final SetMultimap<String, IndexRestore> indexRestores = HashMultimap.create();
        BackendOperation.execute(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                StandardJanusGraphTx tx = (StandardJanusGraphTx) graph.newTransaction();
                try {
                    for (TransactionLogHeader.Modification modification : commitEntry
                            .getContentAsModifications(serializer)) {
                        InternalRelation rel = ModificationDeserializer.parseRelation(modification, tx);
                        //Collect affected vertex indexes
                        for (MixedIndexType index : getMixedIndexes(rel.getType())) {
                            if (index.getElement() == ElementCategory.VERTEX
                                    && isFailedIndex.apply(index.getBackingIndexName())) {
                                assert rel.isProperty();
                                indexRestores.put(index.getBackingIndexName(), new IndexRestore(
                                        rel.getVertex(0).longId(), ElementCategory.VERTEX, getIndexId(index)));
                            }
                        }
                        //See if relation itself is affected
                        for (RelationType relType : rel.getPropertyKeysDirect()) {
                            for (MixedIndexType index : getMixedIndexes(relType)) {
                                if (index.getElement().isInstance(rel)
                                        && isFailedIndex.apply(index.getBackingIndexName())) {
                                    assert rel.id() instanceof RelationIdentifier;
                                    indexRestores.put(index.getBackingIndexName(), new IndexRestore(rel.id(),
                                            ElementCategory.getByClazz(rel.getClass()), getIndexId(index)));
                                }
                            }
                        }
                    }
                } finally {
                    if (tx.isOpen())
                        tx.rollback();
                }
                return true;
            }
        }, readTime);

        //2) Restore elements per backing index
        for (final String indexName : indexRestores.keySet()) {
            final StandardJanusGraphTx tx = (StandardJanusGraphTx) graph.newTransaction();
            try {
                BackendTransaction btx = tx.getTxHandle();
                final IndexTransaction indexTx = btx.getIndexTransaction(indexName);
                BackendOperation.execute(new Callable<Boolean>() {
                    @Override
                    public Boolean call() throws Exception {
                        Map<String, Map<String, List<IndexEntry>>> restoredDocs = Maps.newHashMap();
                        for (IndexRestore restore : indexRestores.get(indexName)) {
                            JanusGraphSchemaVertex indexV = (JanusGraphSchemaVertex) tx
                                    .getVertex(restore.indexId);
                            MixedIndexType index = (MixedIndexType) indexV.asIndexType();
                            JanusGraphElement element = restore.retrieve(tx);
                            if (element != null) {
                                graph.getIndexSerializer().reindexElement(element, index, restoredDocs);
                            } else { //Element is deleted
                                graph.getIndexSerializer().removeElement(restore.elementId, index,
                                        restoredDocs);
                            }
                        }
                        indexTx.restore(restoredDocs);
                        indexTx.commit();
                        return true;
                    }

                    @Override
                    public String toString() {
                        return "IndexMutation";
                    }
                }, persistenceTime);

            } finally {
                if (tx.isOpen())
                    tx.rollback();
            }
        }

    }

    // II) Restore log messages
    final String logTxIdentifier = (String) commitEntry.getMetadata().get(LogTxMeta.LOG_ID);
    if (userLogFailure && logTxIdentifier != null) {
        TransactionLogHeader txHeader = new TransactionLogHeader(txCounter.incrementAndGet(), times.getTime(),
                times);
        final StaticBuffer userLogContent = txHeader.serializeUserLog(serializer, commitEntry, txId);
        BackendOperation.execute(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                final Log userLog = graph.getBackend().getUserLog(logTxIdentifier);
                Future<Message> env = userLog.add(userLogContent);
                if (env.isDone()) {
                    env.get();
                }
                return true;
            }
        }, persistenceTime);
    }

}