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

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:org.eclipse.acceleo.engine.internal.environment.AcceleoEvaluationEnvironment.java

/**
 * Filters non-applicable templates out of the candidates list.
 * //  ww w .  j  ava 2 s. c om
 * @param candidates
 *            List of templates that needs to be filtered out.
 * @param argumentTypes
 *            Types of the arguments for the call.
 * @return The set of applicable templates.
 */
private Set<Template> applicableTemplates(Set<Template> candidates, final List<Object> argumentTypes) {
    Predicate<Template> argumentSizeMatch = new Predicate<Template>() {
        public boolean apply(Template input) {
            final List<Variable> parameters = input.getParameter();
            return parameters.size() == argumentTypes.size()
                    || parameters.isEmpty() && argumentTypes.size() == 1;
        }
    };
    Predicate<Template> argumentsMatch = new Predicate<Template>() {
        public boolean apply(Template input) {
            final List<Variable> parameters = input.getParameter();
            if (parameters.isEmpty() && argumentTypes.size() == 1) {
                return true;
            }
            boolean argumentMatch = true;
            for (int i = 0; i < argumentTypes.size() && argumentMatch; i++) {
                final Variable param = parameters.get(i);
                final Object parameterType = param.getType();
                argumentMatch = isApplicableArgument(parameterType, argumentTypes.get(i));
            }
            return argumentMatch;
        }
    };

    return Sets.filter(candidates, Predicates.and(argumentSizeMatch, argumentsMatch));
}

From source file:org.eclipse.viatra.query.patternlanguage.emf.ui.contentassist.EMFPatternLanguageProposalProvider.java

/**
 * @since 2.0/*w ww  .  j  a  v a  2s.  c  o m*/
 */
@Override
public void completePatternCall_PatternRef(EObject model, Assignment assignment, ContentAssistContext context,
        ICompletionProposalAcceptor acceptor) {
    /*
     * filter not local, private patterns (private patterns in other resources) this information stored in the
     * userdata of the EObjectDescription EObjectDescription only created for not local eObjects, so check for
     * resource equality is unnecessary.
     */
    lookupCrossReference(((CrossReference) assignment.getTerminal()), context, acceptor, Predicates
            .and(featureDescriptionPredicate, input -> !("true".equals(input.getUserData("private")))));
}

From source file:com.eucalyptus.cluster.ClusterEndpoint.java

public DescribeRegionsResponseType DescribeRegions(final DescribeRegionsType request)
        throws EucalyptusCloudException {//TODO:GRZE:URGENT fix the behaviour here.
    final DescribeRegionsResponseType reply = (DescribeRegionsResponseType) request.getReply();
    for (final Class<? extends ComponentId> componentIdClass : ImmutableList.of(Eucalyptus.class)) {
        try {/*from ww w.j  a  va2s  .com*/
            final Component component = Components.lookup(componentIdClass);
            final String region = component.getComponentId().name();
            final List<Region> regions = Lists.newArrayList();
            final NavigableSet<ServiceConfiguration> configs = component.services();
            if (!configs.isEmpty() && Component.State.ENABLED.equals(configs.first().lookupState())) {
                regions.add(new Region(region, ServiceUris.remotePublicify(configs.first()).toASCIIString()));
            }

            final Filter filter = Filters.generate(request.getFilterSet(), Region.class);
            final Predicate<Object> requested = Predicates.and(filterByName(request.getRegions()),
                    filter.asPredicate());
            for (final Region item : Iterables.filter(regions, requested)) {
                reply.getRegionInfo().add(new RegionInfoType(item.getDisplayName(), item.getEndpointUrl()));
            }
        } catch (NoSuchElementException ex) {
            LOG.error(ex, ex);
        }
    }
    return reply;
}

From source file:com.eucalyptus.autoscaling.backend.AutoScalingBackendService.java

public DescribePoliciesResponseType describePolicies(final DescribePoliciesType request)
        throws EucalyptusCloudException {
    final DescribePoliciesResponseType reply = request.getReply();

    //TODO: MaxRecords / NextToken support for DescribePolicies

    final Context ctx = Contexts.lookup();
    final boolean showAll = request.policyNames().remove("verbose");
    final OwnerFullName ownerFullName = ctx.isAdministrator() && showAll ? null
            : ctx.getUserFullName().asAccountFullName();

    try {/*from w w w . j  a v a2  s .c  om*/
        final Predicate<ScalingPolicy> requestedAndAccessible = Predicates.and(
                AutoScalingMetadatas.filterPrivilegesByIdOrArn(ScalingPolicy.class, request.policyNames()),
                AutoScalingResourceName.isResourceName().apply(request.getAutoScalingGroupName())
                        ? AutoScalingMetadatas.filterByProperty(
                                AutoScalingResourceName
                                        .parse(request.getAutoScalingGroupName(), autoScalingGroup).getUuid(),
                                ScalingPolicies.toGroupUuid())
                        : AutoScalingMetadatas.filterByProperty(request.getAutoScalingGroupName(),
                                ScalingPolicies.toGroupName()));

        final List<ScalingPolicyType> results = reply.getDescribePoliciesResult().getScalingPolicies()
                .getMember();
        results.addAll(scalingPolicies.list(ownerFullName, requestedAndAccessible,
                TypeMappers.lookup(ScalingPolicy.class, ScalingPolicyType.class)));

        final List<String> scalingPolicyArns = Lists.transform(results, ScalingPolicyType.policyArn());
        final Map<String, Collection<String>> policyArnToAlarmArns = activityManager
                .getAlarmsForPolicies(ctx.getUserFullName(), scalingPolicyArns);

        for (final ScalingPolicyType scalingPolicyType : results) {
            final Collection<String> alarmArns = policyArnToAlarmArns.get(scalingPolicyType.getPolicyARN());
            if (alarmArns != null && !alarmArns.isEmpty()) {
                scalingPolicyType.setAlarms(new Alarms(alarmArns));
            }
        }
    } catch (Exception e) {
        handleException(e);
    }

    return reply;
}

From source file:forge.game.GameActionUtil.java

private static boolean hasUrzaLands(final Player p) {
    final CardCollectionView landsControlled = p.getCardsIn(ZoneType.Battlefield);
    return Iterables.any(landsControlled,
            Predicates.and(CardPredicates.isType("Urza's"), CardPredicates.isType("Mine")))
            && Iterables.any(landsControlled,
                    Predicates.and(CardPredicates.isType("Urza's"), CardPredicates.isType("Power-Plant")))
            && Iterables.any(landsControlled,
                    Predicates.and(CardPredicates.isType("Urza's"), CardPredicates.isType("Tower")));
}

From source file:org.spongepowered.common.mixin.core.world.extent.MixinExtentViewTransform.java

@Override
public Collection<Entity> getEntities(Predicate<Entity> filter) {
    // Order matters! Bounds filter before the argument filter so it doesn't see out of bounds entities
    return this.extent.getEntities(Predicates.and(new EntityInBounds(this.blockMin, this.blockMax), filter));
}

From source file:org.apache.brooklyn.entity.group.DynamicClusterImpl.java

@Override
public void restart() {
    String mode = getConfig(RESTART_MODE);
    if (mode == null) {
        throw new UnsupportedOperationException(
                "Restart not supported for this cluster: " + RESTART_MODE.getName() + " is not configured.");
    }/* w w  w.  j  a v a  2s.  c  om*/
    if ("off".equalsIgnoreCase(mode)) {
        throw new UnsupportedOperationException("Restart not supported for this cluster.");
    }

    if ("sequential".equalsIgnoreCase(mode)) {
        ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING);
        DynamicTasks
                .queue(Effectors.invocationSequential(Startable.RESTART, null, Iterables.filter(getChildren(),
                        Predicates.and(Predicates.instanceOf(Startable.class), EntityPredicates.isManaged()))));
    } else if ("parallel".equalsIgnoreCase(mode)) {
        ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING);
        DynamicTasks.queue(Effectors.invocationParallel(Startable.RESTART, null, Iterables.filter(getChildren(),
                Predicates.and(Predicates.instanceOf(Startable.class), EntityPredicates.isManaged()))));
    } else {
        throw new IllegalArgumentException("Unknown " + RESTART_MODE.getName() + " '" + mode + "'");
    }

    DynamicTasks.waitForLast();
    ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING);
}

From source file:nl.mvdr.umvc3replayanalyser.controller.Umvc3ReplayManagerController.java

/** Updates the replay table. */
private void updateReplayTable() {
    log.debug("Updating replay table.");

    // Save the selected replay so we can reselect it later.
    Replay selectedReplay = replayTableView.getSelectionModel().getSelectedItem();

    // Construct the filter predicate
    Predicate<Replay> sideOnePredicate = new MatchReplayPredicate(playerOneTextField.getText(),
            playerOneCharacterOneComboBox.getValue(), Assist.getType(playerOneAssistOneComboBox.getValue()),
            playerOneCharacterTwoComboBox.getValue(), Assist.getType(playerOneAssistTwoComboBox.getValue()),
            playerOneCharacterThreeComboBox.getValue(), Assist.getType(playerOneAssistThreeComboBox.getValue()),
            maintainCharacterOrderCheckBox.isSelected(), Side.PLAYER_ONE);
    Predicate<Replay> sideTwoPredicate = new MatchReplayPredicate(playerTwoTextField.getText(),
            playerTwoCharacterOneComboBox.getValue(), Assist.getType(playerTwoAssistOneComboBox.getValue()),
            playerTwoCharacterTwoComboBox.getValue(), Assist.getType(playerTwoAssistTwoComboBox.getValue()),
            playerTwoCharacterThreeComboBox.getValue(), Assist.getType(playerTwoAssistThreeComboBox.getValue()),
            maintainCharacterOrderCheckBox.isSelected(), Side.PLAYER_TWO);
    Predicate<Replay> predicate = Predicates.and(sideOnePredicate, sideTwoPredicate);

    if (!maintainPlayerOrderCheckBox.isSelected()) {
        sideOnePredicate = new MatchReplayPredicate(playerTwoTextField.getText(),
                playerTwoCharacterOneComboBox.getValue(), Assist.getType(playerTwoAssistOneComboBox.getValue()),
                playerTwoCharacterTwoComboBox.getValue(), Assist.getType(playerTwoAssistTwoComboBox.getValue()),
                playerTwoCharacterThreeComboBox.getValue(),
                Assist.getType(playerTwoAssistThreeComboBox.getValue()),
                maintainCharacterOrderCheckBox.isSelected(), Side.PLAYER_ONE);
        sideTwoPredicate = new MatchReplayPredicate(playerOneTextField.getText(),
                playerOneCharacterOneComboBox.getValue(), Assist.getType(playerOneAssistOneComboBox.getValue()),
                playerOneCharacterTwoComboBox.getValue(), Assist.getType(playerOneAssistTwoComboBox.getValue()),
                playerOneCharacterThreeComboBox.getValue(),
                Assist.getType(playerOneAssistThreeComboBox.getValue()),
                maintainCharacterOrderCheckBox.isSelected(), Side.PLAYER_TWO);
        predicate = Predicates.or(predicate, Predicates.and(sideOnePredicate, sideTwoPredicate));
    }//  w w w  .  j a  v a2s  .co  m

    if (log.isDebugEnabled()) {
        log.debug("Using predicate to filter replays: " + predicate);
    }

    Iterable<Replay> filteredReplays = Iterables.filter(replays, predicate);

    List<Replay> viewReplays = replayTableView.getItems();
    viewReplays.clear();
    for (Replay replay : filteredReplays) {
        viewReplays.add(replay);
    }

    if (log.isDebugEnabled()) {
        log.debug(String.format("Filtered replays. Displaying %s of %s replays.", "" + viewReplays.size(),
                "" + this.replays.size()));
    }

    // Force a re-sort of the table.
    List<TableColumn<Replay, ?>> sortOrder = new ArrayList<>(replayTableView.getSortOrder());
    replayTableView.getSortOrder().setAll(sortOrder);

    // Attempt to reselect the originally selected replay.
    int newIndex = replayTableView.getItems().indexOf(selectedReplay);
    replayTableView.getSelectionModel().select(newIndex);
}

From source file:org.opensaml.xmlsec.impl.BasicEncryptionParametersResolver.java

/**
 * Get the effective list of data encryption algorithm URIs to consider, including application of 
 * whitelist/blacklist policy./*w  w w  .  j  av a 2  s.co  m*/
 * 
 * @param criteria the input criteria being evaluated
 * @param whitelistBlacklistPredicate  the whitelist/blacklist predicate to use
 * 
 * @return the list of effective algorithm URIs
 */
@Nonnull
protected List<String> getEffectiveDataEncryptionAlgorithms(@Nonnull final CriteriaSet criteria,
        @Nonnull final Predicate<String> whitelistBlacklistPredicate) {

    ArrayList<String> accumulator = new ArrayList<>();
    for (EncryptionConfiguration config : criteria.get(EncryptionConfigurationCriterion.class)
            .getConfigurations()) {

        accumulator.addAll(Collections2.filter(config.getDataEncryptionAlgorithms(),
                Predicates.and(getAlgorithmRuntimeSupportedPredicate(), whitelistBlacklistPredicate)));

    }
    return accumulator;
}

From source file:org.elasticsearch.test.InternalTestCluster.java

/**
 * Ensures that at most <code>n</code> are up and running.
 * If less nodes that <code>n</code> are running this method
 * will not start any additional nodes./*from  w ww  .j  a  v a  2s.  c  om*/
 */
public synchronized void ensureAtMostNumDataNodes(int n) throws IOException {
    int size = numDataNodes();
    if (size <= n) {
        return;
    }
    // prevent killing the master if possible and client nodes
    final Iterator<NodeAndClient> values = n == 0 ? nodes.values().iterator()
            : Iterators.filter(nodes.values().iterator(), Predicates.and(new DataNodePredicate(),
                    Predicates.not(new MasterNodePredicate(getMasterName()))));

    final Iterator<NodeAndClient> limit = Iterators.limit(values, size - n);
    logger.info("changing cluster size from {} to {}, {} data nodes", size(), n + numSharedClientNodes, n);
    Set<NodeAndClient> nodesToRemove = new HashSet<>();
    while (limit.hasNext()) {
        NodeAndClient next = limit.next();
        nodesToRemove.add(next);
        removeDisruptionSchemeFromNode(next);
        next.close();
    }
    for (NodeAndClient toRemove : nodesToRemove) {
        nodes.remove(toRemove.name);
    }
    if (!nodesToRemove.isEmpty() && size() > 0) {
        assertNoTimeout(client().admin().cluster().prepareHealth()
                .setWaitForNodes(Integer.toString(nodes.size())).get());
    }
}