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

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

Introduction

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

Prototype

public static <T> Predicate<T> or(Predicate<? super T> first, Predicate<? super T> second) 

Source Link

Document

Returns a predicate that evaluates to true if either of its components evaluates to true .

Usage

From source file:org.eclipse.sirius.diagram.ui.tools.internal.dialogs.DiagramElementsSelectionDialog.java

/**
 * Init the content provider./*ww  w  .ja v a  2  s.c  o  m*/
 * 
 * @param includeLabel
 *            include label (containers, lists, edges and nodes if there are
 *            on border for nodes) in the tree content
 */
protected void initContentProvider(boolean includeLabel) {
    AdapterFactory adapterFactory = getAdapterFactory(includeLabel);
    Predicate<Object> predicate = Predicates.instanceOf(DDiagramElement.class);
    if (includeLabel) {
        predicate = Predicates.or(predicate,
                Predicates.instanceOf(AbstractDDiagramElementLabelItemProvider.class));
    }
    contentProvider = new FilteredTreeContentProvider(adapterFactory, predicate);
}

From source file:org.apache.impala.analysis.StmtRewriter.java

/**
 * Checks if an expr containing a correlated subquery is eligible for rewrite by
 * tranforming into a join. 'correlatedPredicates' contains the correlated
 * predicates identified in the subquery. Throws an AnalysisException if 'expr'
 * is not eligible for rewrite./*from ww  w  . ja  v a 2 s .c om*/
 * TODO: Merge all the rewrite eligibility tests into a single function.
 */
private static void canRewriteCorrelatedSubquery(Expr expr, List<Expr> correlatedPredicates)
        throws AnalysisException {
    Preconditions.checkNotNull(expr);
    Preconditions.checkNotNull(correlatedPredicates);
    Preconditions.checkState(expr.contains(Subquery.class));
    SelectStmt stmt = (SelectStmt) expr.getSubquery().getStatement();
    Preconditions.checkNotNull(stmt);
    // Grouping and/or aggregation is not allowed on correlated scalar and IN subqueries
    if ((expr instanceof BinaryPredicate && (stmt.hasGroupByClause() || stmt.hasAnalyticInfo()))
            || (expr instanceof InPredicate && (stmt.hasAggInfo() || stmt.hasAnalyticInfo()))) {
        throw new AnalysisException(
                "Unsupported correlated subquery with grouping " + "and/or aggregation: " + stmt.toSql());
    }

    final com.google.common.base.Predicate<Expr> isSingleSlotRef = new com.google.common.base.Predicate<Expr>() {
        @Override
        public boolean apply(Expr arg) {
            return arg.unwrapSlotRef(false) != null;
        }
    };

    // A HAVING clause is only allowed on correlated EXISTS subqueries with
    // correlated binary predicates of the form Slot = Slot (see IMPALA-2734)
    // TODO Handle binary predicates with IS NOT DISTINCT op
    if (expr instanceof ExistsPredicate && stmt.hasHavingClause() && !correlatedPredicates.isEmpty()
            && (!stmt.hasAggInfo() || !Iterables.all(correlatedPredicates,
                    Predicates.or(Expr.IS_EQ_BINARY_PREDICATE, isSingleSlotRef)))) {
        throw new AnalysisException(
                "Unsupported correlated EXISTS subquery with a " + "HAVING clause: " + stmt.toSql());
    }

    // The following correlated subqueries with a limit clause are supported:
    // 1. EXISTS subqueries
    // 2. Scalar subqueries with aggregation
    if (stmt.hasLimit()
            && (!(expr instanceof BinaryPredicate) || !stmt.hasAggInfo() || stmt.selectList_.isDistinct())
            && !(expr instanceof ExistsPredicate)) {
        throw new AnalysisException(
                "Unsupported correlated subquery with a " + "LIMIT clause: " + stmt.toSql());
    }
}

From source file:com.google.javascript.jscomp.PeepholeRemoveDeadCode.java

/**
 *
 *///w  w w.ja  va  2 s  . c  om
static boolean hasBreakOrContinue(Node n) {
    // TODO(johnlenz): This is overkill as named breaks may refer to outer
    // loops or labels, and any break my refer to an inner loop.
    // More generally, this check may be more expensive than we like.
    return NodeUtil.has(n,
            Predicates.or(new NodeUtil.MatchNodeType(Token.BREAK), new NodeUtil.MatchNodeType(Token.CONTINUE)),
            NodeUtil.MATCH_NOT_FUNCTION);
}

From source file:io.usethesource.criterion.CalculateFootprintsHeterogeneous.java

private static String measureAndReport(final Object objectToMeasure, final String className, DataType dataType,
        Archetype archetype, boolean supportsStagedMutability, int size, int run,
        MemoryFootprintPreset preset) {/*from   ww  w  . j  a  va2  s. c o  m*/
    final Predicate<Object> predicate;

    switch (preset) {
    case DATA_STRUCTURE_OVERHEAD:
        // TODO: create JmhLeaf
        // predicate = Predicates
        // .not(Predicates.or(Predicates.instanceOf(Integer.class),
        // Predicates.instanceOf(BigInteger.class),
        // Predicates.instanceOf(JmhValue.class), Predicates.instanceOf(PureInteger.class)));
        predicate = Predicates.not(Predicates.or(Predicates.instanceOf(PureInteger.class),
                Predicates.instanceOf(PureIntegerWithCustomHashCode.class)));
        break;
    case RETAINED_SIZE:
        predicate = Predicates.alwaysTrue();
        break;
    case RETAINED_SIZE_WITH_BOXED_INTEGER_FILTER:
        predicate = Predicates.not(Predicates.instanceOf(Integer.class));
        break;
    default:
        throw new IllegalStateException();
    }

    return measureAndReport(objectToMeasure, className, dataType, archetype, supportsStagedMutability, size,
            run, predicate);
}

From source file:brooklyn.entity.basic.AbstractSoftwareProcessSshDriver.java

/**
 * Sets up a {@link ScriptHelper} to generate a script that controls the given phase
 * (<em>check-running</em>, <em>launching</em> etc.) including default header and
 * footer commands./*  w  ww.ja va2 s.c  o m*/
 * <p>
 * Supported flags:
 * <ul>
 * <li><strong>usePidFile</strong> - <em>true</em> or <em>filename</em> to save and retrieve the PID
 * <li><strong>processOwner</strong> - <em>username</em> that owns the running process
 * <li><strong>nonStandardLayout</strong> - <em>true</em> to omit all default commands
 * <li><strong>installIncomplete</strong> - <em>true</em> to prevent marking complete
 * <li><strong>debug</strong> - <em>true</em> to enable shell debug output
 * </li>
 *
 * @param flags a {@link Map} of flags to control script generation
 * @param phase the phase to create the ScriptHelper for
 *
 * @see #newScript(String)
 * @see #USE_PID_FILE
 * @see #PROCESS_OWNER
 * @see #NON_STANDARD_LAYOUT
 * @see #INSTALL_INCOMPLETE
 * @see #DEBUG
 */
protected ScriptHelper newScript(Map<String, ?> flags, String phase) {
    if (!Entities.isManaged(getEntity()))
        throw new IllegalStateException(
                getEntity() + " is no longer managed; cannot create script to run here (" + phase + ")");

    if (!Iterables.all(flags.keySet(), StringPredicates.equalToAny(VALID_FLAGS))) {
        throw new IllegalArgumentException("Invalid flags passed: " + flags);
    }

    ScriptHelper s = new ScriptHelper(this, phase + " " + elvis(entity, this));
    if (!groovyTruth(flags.get(NON_STANDARD_LAYOUT))) {
        if (groovyTruth(flags.get(DEBUG))) {
            s.header.prepend("set -x");
        }
        if (INSTALLING.equals(phase)) {
            // mutexId should be global because otherwise package managers will contend with each other 
            s.useMutex(getLocation(), "installation lock at host", "installing " + elvis(entity, this));
            s.header.append("export INSTALL_DIR=\"" + getInstallDir() + "\"", "mkdir -p $INSTALL_DIR",
                    "cd $INSTALL_DIR", "test -f BROOKLYN && exit 0");

            if (!groovyTruth(flags.get(INSTALL_INCOMPLETE))) {
                s.footer.append("date > $INSTALL_DIR/BROOKLYN");
            }
            // don't set vars during install phase, prevent dependency resolution
            s.environmentVariablesReset();
        }
        if (ImmutableSet.of(CUSTOMIZING, LAUNCHING, CHECK_RUNNING, STOPPING, KILLING, RESTARTING)
                .contains(phase)) {
            s.header.append("export RUN_DIR=\"" + getRunDir() + "\"", "mkdir -p $RUN_DIR", "cd $RUN_DIR");
        }
    }

    if (ImmutableSet.of(LAUNCHING, RESTARTING).contains(phase)) {
        s.failIfBodyEmpty();
    }
    if (ImmutableSet.of(STOPPING, KILLING).contains(phase)) {
        // stopping and killing allowed to have empty body if pid file set
        if (!groovyTruth(flags.get(USE_PID_FILE)))
            s.failIfBodyEmpty();
    }
    if (ImmutableSet.of(INSTALLING, LAUNCHING).contains(phase)) {
        s.updateTaskAndFailOnNonZeroResultCode();
    }
    if (phase.equalsIgnoreCase(CHECK_RUNNING)) {
        s.setInessential();
        s.setTransient();
        s.setFlag(SshTool.PROP_CONNECT_TIMEOUT, Duration.TEN_SECONDS.toMilliseconds());
        s.setFlag(SshTool.PROP_SESSION_TIMEOUT, Duration.THIRTY_SECONDS.toMilliseconds());
        s.setFlag(SshTool.PROP_SSH_TRIES, 1);
    }

    if (groovyTruth(flags.get(USE_PID_FILE))) {
        Object usePidFile = flags.get(USE_PID_FILE);
        String pidFile = (usePidFile instanceof CharSequence ? usePidFile
                : Os.mergePathsUnix(getRunDir(), PID_FILENAME)).toString();
        String processOwner = (String) flags.get(PROCESS_OWNER);
        if (LAUNCHING.equals(phase)) {
            entity.setAttribute(SoftwareProcess.PID_FILE, pidFile);
            s.footer.prepend("echo $! > " + pidFile);
        } else if (CHECK_RUNNING.equals(phase)) {
            // old method, for supplied service, or entity.id
            // "ps aux | grep ${service} | grep \$(cat ${pidFile}) > /dev/null"
            // new way, preferred?
            if (processOwner != null) {
                s.body.append(BashCommands.sudoAsUser(processOwner, "test -f " + pidFile) + " || exit 1",
                        "ps -p $(" + BashCommands.sudoAsUser(processOwner, "cat " + pidFile) + ")");
            } else {
                s.body.append("test -f " + pidFile + " || exit 1", "ps -p `cat " + pidFile + "`");
            }
            // no pid, not running; 1 is not running
            s.requireResultCode(Predicates.or(Predicates.equalTo(0), Predicates.equalTo(1)));
        } else if (STOPPING.equals(phase)) {
            if (processOwner != null) {
                s.body.append("export PID=$(" + BashCommands.sudoAsUser(processOwner, "cat " + pidFile) + ")",
                        "test -n \"$PID\" || exit 0", BashCommands.sudoAsUser(processOwner, "kill $PID"),
                        BashCommands.sudoAsUser(processOwner, "kill -9 $PID"),
                        BashCommands.sudoAsUser(processOwner, "rm -f " + pidFile));
            } else {
                s.body.append("export PID=$(cat " + pidFile + ")", "test -n \"$PID\" || exit 0", "kill $PID",
                        "kill -9 $PID", "rm -f " + pidFile);
            }
        } else if (KILLING.equals(phase)) {
            if (processOwner != null) {
                s.body.append("export PID=$(" + BashCommands.sudoAsUser(processOwner, "cat " + pidFile) + ")",
                        "test -n \"$PID\" || exit 0", BashCommands.sudoAsUser(processOwner, "kill -9 $PID"),
                        BashCommands.sudoAsUser(processOwner, "rm -f " + pidFile));
            } else {
                s.body.append("export PID=$(cat " + pidFile + ")", "test -n \"$PID\" || exit 0", "kill -9 $PID",
                        "rm -f " + pidFile);
            }
        } else if (RESTARTING.equals(phase)) {
            if (processOwner != null) {
                s.footer.prepend(BashCommands.sudoAsUser(processOwner, "test -f " + pidFile) + " || exit 1",
                        "ps -p $(" + BashCommands.sudoAsUser(processOwner, "cat " + pidFile) + ") || exit 1");
            } else {
                s.footer.prepend("test -f " + pidFile + " || exit 1", "ps -p $(cat " + pidFile + ") || exit 1");
            }
            // no pid, not running; no process; can't restart, 1 is not running
        } else {
            log.warn(USE_PID_FILE + ": script option not valid for " + s.summary);
        }
    }

    return s;
}

From source file:org.eclipse.sirius.business.internal.session.danalysis.DAnalysisSessionImpl.java

/**
 * This method allows adding {@code ModelChangeTrigger} to the current
 * session {@link SessionEventBroker}. This method is called during the
 * opening of the Session, before setting the open attribute to true and
 * before launching the SessionListener.OPENED notifications.
 *//*from   w w  w . java 2 s  .c o  m*/
protected void initLocalTriggers() {
    Predicate<Notification> danglingRemovalPredicate = Predicates.or(DanglingRefRemovalTrigger.IS_DETACHMENT,
            DanglingRefRemovalTrigger.IS_ATTACHMENT);
    DanglingRefRemovalTrigger danglingRemovalTrigger = new DanglingRefRemovalTrigger(this);
    getEventBroker().addLocalTrigger(SessionEventBrokerImpl.asFilter(danglingRemovalPredicate),
            danglingRemovalTrigger);

    addRefreshEditorsListener();
    /*
     * Make sure these adapters are added after the rest, and in particular
     * after the semantic cross-referencer, so that they can rely on an
     * up-to-date cross-referencer when invoked.
     */
    for (DAnalysis analysis : allAnalyses()) {
        addAdaptersOnAnalysis(analysis);
    }
}

From source file:com.eucalyptus.bootstrap.Databases.java

/**
 * List all known databases.//ww  w  . j  a  v  a 2s. com
 */
static Set<String> listDatabases() {
    final Set<String> dbNames = Sets.newHashSet();
    final Predicate<String> dbNamePredicate = Predicates.or(Strings.startsWith("eucalyptus_"),
            Predicates.equalTo("database_events"));

    for (final Host h : Hosts.listActiveDatabases()) {
        Iterables.addAll(dbNames, Iterables
                .filter(Databases.getBootstrapper().listDatabases(h.getBindAddress()), dbNamePredicate));
    }

    return dbNames;
}

From source file:org.apache.flex.compiler.internal.legacy.ASDefinitionFilter.java

/**
 * Generate a predicate based on the AccessValue of the ASDefinitionFilter.
 * This predicate will do the right thing for private, protected, internal,
 * or public access values./*from  www. j a  v  a  2  s  . c  om*/
 */
public Predicate<IDefinition> computeAccessValuePredicate(ICompilerProject project, ASScope scope) {
    Predicate<IDefinition> pred = null;
    if (fAccessRule == AccessValue.ALL) {
        pred = null;
    } else if (fAccessRule == AccessValue.PRIVATE) {
        pred = new PrivateAccessValuePredicate(project, fContext.getNamespaceSet(project));
    } else {
        if (fAccessRule == AccessValue.PUBLIC) {
            pred = new PublicAccessValuePredicate();
        } else if (fAccessRule == AccessValue.INTERNAL) {
            pred = new InternalAccessValuePredicate();
        } else if (fAccessRule == AccessValue.PROTECTED) {
            pred = new ProtectedAccessValuePredicate();
        }
        // CM expects these rules to match the public/internal/protected namespaces,
        // but to also match stuff in the open namespaces wherever the lookup was occurring
        if (pred != null)
            pred = Predicates.or(pred, new NamespaceSetPredicate(project, fContext.getNamespaceSet(project)));
    }
    return pred;
}