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.apache.brooklyn.entity.nosql.etcd.EtcdClusterImpl.java

protected void onServerPoolMemberChanged(Entity member) {
    synchronized (memberMutex) {
        log.debug("For {}, considering membership of {} which is in locations {}",
                new Object[] { this, member, member.getLocations() });

        Map<Entity, String> nodes = sensors().get(ETCD_CLUSTER_NODES);
        if (belongsInServerPool(member)) {
            if (nodes == null) {
                nodes = Maps.newLinkedHashMap();
            }/*  w  w w. j a  v  a2 s.  c o  m*/
            String name = Preconditions.checkNotNull(getNodeName(member));

            // Wait until node has been installed
            DynamicTasks
                    .queueIfPossible(
                            DependentConfiguration.attributeWhenReady(member, EtcdNode.ETCD_NODE_INSTALLED))
                    .orSubmitAndBlock(this).andWaitForSuccess();

            // Check for first node in the cluster.
            Duration timeout = config().get(BrooklynConfigKeys.START_TIMEOUT);
            Entity firstNode = sensors().get(DynamicCluster.FIRST);
            if (member.equals(firstNode)) {
                nodes.put(member, name);
                recalculateClusterAddresses(nodes);
                log.info("Adding first node {}: {}; {} to cluster", new Object[] { this, member, name });
                ((EntityInternal) member).sensors().set(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE);
            } else {
                int retry = 3; // TODO use a configurable Repeater instead?
                while (retry-- > 0 && member.sensors().get(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER) == null
                        && !nodes.containsKey(member)) {
                    Optional<Entity> anyNodeInCluster = Iterables.tryFind(nodes.keySet(),
                            Predicates.and(Predicates.instanceOf(EtcdNode.class), EntityPredicates
                                    .attributeEqualTo(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE)));
                    if (anyNodeInCluster.isPresent()) {
                        DynamicTasks.queueIfPossible(DependentConfiguration.builder()
                                .attributeWhenReady(anyNodeInCluster.get(), Startable.SERVICE_UP)
                                .timeout(timeout).build()).orSubmitAndBlock(this).andWaitForSuccess();
                        Entities.invokeEffectorWithArgs(this, anyNodeInCluster.get(),
                                EtcdNode.JOIN_ETCD_CLUSTER, name, getNodeAddress(member))
                                .blockUntilEnded(timeout);
                        nodes.put(member, name);
                        recalculateClusterAddresses(nodes);
                        log.info("Adding node {}: {}; {} to cluster", new Object[] { this, member, name });
                        ((EntityInternal) member).sensors().set(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER,
                                Boolean.TRUE);
                    } else {
                        log.info("Waiting for first node in cluster {}", this);
                        Time.sleep(Duration.seconds(15));
                    }
                }
            }
        } else {
            if (nodes != null && nodes.containsKey(member)) {
                Optional<Entity> anyNodeInCluster = Iterables.tryFind(nodes.keySet(),
                        Predicates.and(
                                Predicates.instanceOf(EtcdNode.class), EntityPredicates
                                        .attributeEqualTo(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.TRUE),
                                Predicates.not(Predicates.equalTo(member))));
                if (anyNodeInCluster.isPresent()) {
                    Entities.invokeEffectorWithArgs(this, anyNodeInCluster.get(), EtcdNode.LEAVE_ETCD_CLUSTER,
                            getNodeName(member)).blockUntilEnded();
                }
                nodes.remove(member);
                recalculateClusterAddresses(nodes);
                log.info("Removing node {}: {}; {} from cluster",
                        new Object[] { this, member, getNodeName(member) });
                ((EntityInternal) member).sensors().set(EtcdNode.ETCD_NODE_HAS_JOINED_CLUSTER, Boolean.FALSE);
            }
        }

        ServiceNotUpLogic.updateNotUpIndicatorRequiringNonEmptyMap(this, ETCD_CLUSTER_NODES);
        log.debug("Done {} checkEntity {}", this, member);
    }
}

From source file:cn.howardliu.gear.spring.boot.autoconfigure.SwaggerAutoConfiguration.java

@Bean
@ConditionalOnMissingBean//www.  jav a  2  s  .  com
@ConditionalOnBean(UiConfiguration.class)
@ConditionalOnProperty(name = "swagger.enabled", matchIfMissing = true)
public List<Docket> createRestApi(SwaggerProperties swaggerProperties) {
    ConfigurableBeanFactory configurableBeanFactory = (ConfigurableBeanFactory) beanFactory;
    List<Docket> docketList = new LinkedList<>();

    // 
    if (swaggerProperties.getDocket().size() == 0) {
        ApiInfo apiInfo = new ApiInfoBuilder().title(swaggerProperties.getTitle())
                .description(swaggerProperties.getDescription()).version(swaggerProperties.getVersion())
                .license(swaggerProperties.getLicense()).licenseUrl(swaggerProperties.getLicenseUrl())
                .contact(new Contact(swaggerProperties.getContact().getName(),
                        swaggerProperties.getContact().getUrl(), swaggerProperties.getContact().getEmail()))
                .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl()).build();

        // base-path?
        // ?path?/**
        if (swaggerProperties.getBasePath().isEmpty()) {
            swaggerProperties.getBasePath().add("/**");
        }
        List<Predicate<String>> basePath = new ArrayList<>();
        for (String path : swaggerProperties.getBasePath()) {
            basePath.add(PathSelectors.ant(path));
        }

        // exclude-path?
        List<Predicate<String>> excludePath = new ArrayList<>();
        for (String path : swaggerProperties.getExcludePath()) {
            excludePath.add(PathSelectors.ant(path));
        }

        Docket docketForBuilder = new Docket(DocumentationType.SWAGGER_2).host(swaggerProperties.getHost())
                .apiInfo(apiInfo).securityContexts(Collections.singletonList(securityContext()))
                .globalOperationParameters(buildGlobalOperationParametersFromSwaggerProperties(
                        swaggerProperties.getGlobalOperationParameters()));

        if ("BasicAuth".equalsIgnoreCase(swaggerProperties.getAuthorization().getType())) {
            docketForBuilder.securitySchemes(Collections.singletonList(basicAuth()));
        } else if (!"None".equalsIgnoreCase(swaggerProperties.getAuthorization().getType())) {
            docketForBuilder.securitySchemes(Collections.singletonList(apiKey()));
        }

        // ??
        if (!swaggerProperties.getApplyDefaultResponseMessages()) {
            buildGlobalResponseMessage(swaggerProperties, docketForBuilder);
        }

        Docket docket = docketForBuilder.select()
                .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
                .paths(Predicates.and(Predicates.not(Predicates.or(excludePath)), Predicates.or(basePath)))
                .build();

        /* ignoredParameterTypes **/
        Class<?>[] array = new Class[swaggerProperties.getIgnoredParameterTypes().size()];
        Class<?>[] ignoredParameterTypes = swaggerProperties.getIgnoredParameterTypes().toArray(array);
        docket.ignoredParameterTypes(ignoredParameterTypes);

        configurableBeanFactory.registerSingleton("defaultDocket", docket);
        docketList.add(docket);
        return docketList;
    }

    // 
    for (String groupName : swaggerProperties.getDocket().keySet()) {
        SwaggerProperties.DocketInfo docketInfo = swaggerProperties.getDocket().get(groupName);

        ApiInfo apiInfo = new ApiInfoBuilder()
                .title(docketInfo.getTitle().isEmpty() ? swaggerProperties.getTitle() : docketInfo.getTitle())
                .description(docketInfo.getDescription().isEmpty() ? swaggerProperties.getDescription()
                        : docketInfo.getDescription())
                .version(docketInfo.getVersion().isEmpty() ? swaggerProperties.getVersion()
                        : docketInfo.getVersion())
                .license(docketInfo.getLicense().isEmpty() ? swaggerProperties.getLicense()
                        : docketInfo.getLicense())
                .licenseUrl(docketInfo.getLicenseUrl().isEmpty() ? swaggerProperties.getLicenseUrl()
                        : docketInfo.getLicenseUrl())
                .contact(new Contact(
                        docketInfo.getContact().getName().isEmpty() ? swaggerProperties.getContact().getName()
                                : docketInfo.getContact().getName(),
                        docketInfo.getContact().getUrl().isEmpty() ? swaggerProperties.getContact().getUrl()
                                : docketInfo.getContact().getUrl(),
                        docketInfo.getContact().getEmail().isEmpty() ? swaggerProperties.getContact().getEmail()
                                : docketInfo.getContact().getEmail()))
                .termsOfServiceUrl(
                        docketInfo.getTermsOfServiceUrl().isEmpty() ? swaggerProperties.getTermsOfServiceUrl()
                                : docketInfo.getTermsOfServiceUrl())
                .build();

        // base-path?
        // ?path?/**
        if (docketInfo.getBasePath().isEmpty()) {
            docketInfo.getBasePath().add("/**");
        }
        List<Predicate<String>> basePath = new ArrayList();
        for (String path : docketInfo.getBasePath()) {
            basePath.add(PathSelectors.ant(path));
        }

        // exclude-path?
        List<Predicate<String>> excludePath = new ArrayList();
        for (String path : docketInfo.getExcludePath()) {
            excludePath.add(PathSelectors.ant(path));
        }

        Docket docketForBuilder = new Docket(DocumentationType.SWAGGER_2).host(swaggerProperties.getHost())
                .apiInfo(apiInfo).securityContexts(Collections.singletonList(securityContext()))
                .globalOperationParameters(
                        assemblyGlobalOperationParameters(swaggerProperties.getGlobalOperationParameters(),
                                docketInfo.getGlobalOperationParameters()));

        if ("BasicAuth".equalsIgnoreCase(swaggerProperties.getAuthorization().getType())) {
            docketForBuilder.securitySchemes(Collections.singletonList(basicAuth()));
        } else if (!"None".equalsIgnoreCase(swaggerProperties.getAuthorization().getType())) {
            docketForBuilder.securitySchemes(Collections.singletonList(apiKey()));
        }

        // ??
        if (!swaggerProperties.getApplyDefaultResponseMessages()) {
            buildGlobalResponseMessage(swaggerProperties, docketForBuilder);
        }

        Docket docket = docketForBuilder.groupName(groupName).select()
                .apis(RequestHandlerSelectors.basePackage(docketInfo.getBasePackage()))
                .paths(Predicates.and(Predicates.not(Predicates.or(excludePath)), Predicates.or(basePath)))
                .build();

        /* ignoredParameterTypes **/
        Class<?>[] array = new Class[docketInfo.getIgnoredParameterTypes().size()];
        Class<?>[] ignoredParameterTypes = docketInfo.getIgnoredParameterTypes().toArray(array);
        docket.ignoredParameterTypes(ignoredParameterTypes);

        configurableBeanFactory.registerSingleton(groupName, docket);
        docketList.add(docket);
    }
    return docketList;
}

From source file:org.apache.isis.core.unittestsupport.bidir.BidirectionalRelationshipContractTestAbstract.java

private static Predicate<Method> withConcreteMethodNamed(final String getMethod) {
    return Predicates.and(ReflectionUtils.withName(getMethod), new Predicate<Method>() {
        public boolean apply(Method m) {
            return !m.isSynthetic() && !Modifier.isAbstract(m.getModifiers());
        }/*from w w  w.  j  a  v a  2 s  . c  o  m*/
    });
}

From source file:com.ardorcraft.control.WalkControl.java

public void setupMouseTriggers(final LogicalLayer layer, final boolean dragOnly) {
    final WalkControl control = this;
    // Mouse look
    final Predicate<TwoInputStates> someMouseDown = Predicates.or(TriggerConditions.leftButtonDown(),
            Predicates.or(TriggerConditions.rightButtonDown(), TriggerConditions.middleButtonDown()));
    final Predicate<TwoInputStates> dragged = Predicates.and(TriggerConditions.mouseMoved(), someMouseDown);
    final TriggerAction dragAction = new TriggerAction() {

        // Test boolean to allow us to ignore first mouse event. First event
        // can wildly vary based on platform.
        private boolean firstPing = true;

        @Override/*from w  w  w  . ja v a2 s  .  com*/
        public void perform(final Canvas source, final TwoInputStates inputStates, final double tpf) {
            final MouseState mouse = inputStates.getCurrent().getMouseState();
            if (mouse.getDx() != 0 || mouse.getDy() != 0) {
                if (!firstPing) {
                    control.rotate(-mouse.getDx(), -mouse.getDy());
                } else {
                    firstPing = false;
                }
            }
        }
    };

    _mouseTrigger = new InputTrigger(dragOnly ? dragged : TriggerConditions.mouseMoved(), dragAction);
    layer.registerTrigger(_mouseTrigger);
}

From source file:com.datastax.driver.core.utils.SocketChannelMonitor.java

/**
 * @param channelFilter {@link Predicate} to use to determine whether or not a socket shall be considered.
 * @return Channels matching the given {@link Predicate}.
 *//*w  w w. ja va  2s.  c  o m*/
public Iterable<SocketChannel> matchingChannels(final Predicate<SocketChannel> channelFilter) {
    return Iterables.filter(Lists.newArrayList(channels), Predicates.and(Predicates.notNull(), channelFilter));
}

From source file:forge.card.BoosterGenerator.java

@SuppressWarnings("unchecked")
public static PrintSheet makeSheet(String sheetKey, Iterable<PaperCard> src) {

    PrintSheet ps = new PrintSheet(sheetKey);
    String[] sKey = TextUtil.splitWithParenthesis(sheetKey, ' ', 2);
    Predicate<PaperCard> setPred = (Predicate<PaperCard>) (sKey.length > 1
            ? IPaperCard.Predicates.printedInSets(sKey[1].split(" "))
            : Predicates.alwaysTrue());/* w  ww. j  av  a 2 s.co m*/

    List<String> operators = new LinkedList<>(Arrays.asList(TextUtil.splitWithParenthesis(sKey[0], ':')));
    Predicate<PaperCard> extraPred = buildExtraPredicate(operators);

    // source replacement operators - if one is applied setPredicate will be ignored
    Iterator<String> itMod = operators.iterator();
    while (itMod.hasNext()) {

        String mainCode = itMod.next();

        if (mainCode.regionMatches(true, 0, "fromSheet", 0, 9)) { // custom print sheet

            String sheetName = StringUtils.strip(mainCode.substring(9), "()\" ");
            src = StaticData.instance().getPrintSheets().get(sheetName).toFlatList();
            setPred = Predicates.alwaysTrue();

        } else if (mainCode.startsWith("promo")) { // get exactly the named cards, that's a tiny inlined print sheet

            String list = StringUtils.strip(mainCode.substring(5), "() ");
            String[] cardNames = TextUtil.splitWithParenthesis(list, ',', '"', '"');
            List<PaperCard> srcList = new ArrayList<>();

            for (String cardName : cardNames) {
                srcList.add(StaticData.instance().getCommonCards().getCard(cardName));
            }

            src = srcList;
            setPred = Predicates.alwaysTrue();

        } else {
            continue;
        }

        itMod.remove();

    }

    // only special operators should remain by now - the ones that could not be turned into one predicate
    String mainCode = operators.isEmpty() ? null : operators.get(0).trim();

    if (null == mainCode || mainCode.equalsIgnoreCase(BoosterSlots.ANY)) { // no restriction on rarity

        Predicate<PaperCard> predicate = Predicates.and(setPred, extraPred);
        ps.addAll(Iterables.filter(src, predicate));

    } else if (mainCode.equalsIgnoreCase(BoosterSlots.UNCOMMON_RARE)) { // for sets like ARN, where U1 cards are considered rare and U3 are uncommon

        Predicate<PaperCard> predicateRares = Predicates.and(setPred, IPaperCard.Predicates.Presets.IS_RARE,
                extraPred);
        ps.addAll(Iterables.filter(src, predicateRares));

        Predicate<PaperCard> predicateUncommon = Predicates.and(setPred,
                IPaperCard.Predicates.Presets.IS_UNCOMMON, extraPred);
        ps.addAll(Iterables.filter(src, predicateUncommon), 3);

    } else if (mainCode.equalsIgnoreCase(BoosterSlots.RARE_MYTHIC)) {
        // Typical ratio of rares to mythics is 53:15, changing to 35:10 in smaller sets.
        // To achieve the desired 1:8 are all mythics are added once, and all rares added twice per print sheet.

        Predicate<PaperCard> predicateMythic = Predicates.and(setPred,
                IPaperCard.Predicates.Presets.IS_MYTHIC_RARE, extraPred);
        ps.addAll(Iterables.filter(src, predicateMythic));

        Predicate<PaperCard> predicateRare = Predicates.and(setPred, IPaperCard.Predicates.Presets.IS_RARE,
                extraPred);
        ps.addAll(Iterables.filter(src, predicateRare), 2);

    } else {
        throw new IllegalArgumentException("Booster generator: operator could not be parsed - " + mainCode);
    }

    return ps;

}

From source file:club.zhcs.swagger.SwaggerAutoConfiguration.java

@Bean
@ConditionalOnMissingBean/*from  w ww . j a v a 2  s .com*/
@ConditionalOnBean(UiConfiguration.class)
@ConditionalOnProperty(name = "swagger.enabled", matchIfMissing = true)
public List<Docket> createRestApi(SwaggerConfigurationProerties SwaggerConfigurationProerties) {
    ConfigurableBeanFactory configurableBeanFactory = (ConfigurableBeanFactory) beanFactory;
    List<Docket> docketList = Lists.newArrayList();

    // 
    if (SwaggerConfigurationProerties.getDocket().size() == 0) {
        ApiInfo apiInfo = new ApiInfoBuilder().title(SwaggerConfigurationProerties.getTitle())
                .description(SwaggerConfigurationProerties.getDescription())
                .version(SwaggerConfigurationProerties.getVersion())
                .license(SwaggerConfigurationProerties.getLicense())
                .licenseUrl(SwaggerConfigurationProerties.getLicenseUrl())
                .contact(new Contact(SwaggerConfigurationProerties.getContact().getName(),
                        SwaggerConfigurationProerties.getContact().getUrl(),
                        SwaggerConfigurationProerties.getContact().getEmail()))
                .termsOfServiceUrl(SwaggerConfigurationProerties.getTermsOfServiceUrl()).build();

        // base-path?
        // ?path?/**
        if (SwaggerConfigurationProerties.getBasePath().isEmpty()) {
            SwaggerConfigurationProerties.getBasePath().add("/**");
        }
        List<Predicate<String>> basePath = new ArrayList();
        for (String path : SwaggerConfigurationProerties.getBasePath()) {
            basePath.add(PathSelectors.ant(path));
        }

        // exclude-path?
        List<Predicate<String>> excludePath = Lists.newArrayList();
        for (String path : SwaggerConfigurationProerties.getExcludePath()) {
            excludePath.add(PathSelectors.ant(path));
        }

        Docket docketForBuilder = new Docket(DocumentationType.SWAGGER_2)
                .host(SwaggerConfigurationProerties.getHost()).apiInfo(apiInfo)
                .securitySchemes(Collections.singletonList(apiKey()))
                .securityContexts(Collections.singletonList(securityContext()))
                .globalOperationParameters(buildGlobalOperationParametersFromSwaggerConfigurationProerties(
                        SwaggerConfigurationProerties.getGlobalOperationParameters()));

        // ??
        if (!SwaggerConfigurationProerties.getApplyDefaultResponseMessages()) {
            buildGlobalResponseMessage(SwaggerConfigurationProerties, docketForBuilder);
        }

        Docket docket = docketForBuilder.select()
                .apis(RequestHandlerSelectors.basePackage(SwaggerConfigurationProerties.getBasePackage()))
                .paths(Predicates.and(Predicates.not(Predicates.or(excludePath)), Predicates.or(basePath)))
                .build();

        /* ignoredParameterTypes **/
        Class<?>[] array = new Class[SwaggerConfigurationProerties.getIgnoredParameterTypes().size()];
        Class<?>[] ignoredParameterTypes = SwaggerConfigurationProerties.getIgnoredParameterTypes()
                .toArray(array);
        docket.ignoredParameterTypes(ignoredParameterTypes);

        configurableBeanFactory.registerSingleton("defaultDocket", docket);
        docketList.add(docket);
        return docketList;
    }

    // 
    for (String groupName : SwaggerConfigurationProerties.getDocket().keySet()) {
        SwaggerConfigurationProerties.DocketInfo docketInfo = SwaggerConfigurationProerties.getDocket()
                .get(groupName);

        ApiInfo apiInfo = new ApiInfoBuilder()
                .title(docketInfo.getTitle().isEmpty() ? SwaggerConfigurationProerties.getTitle()
                        : docketInfo.getTitle())
                .description(
                        docketInfo.getDescription().isEmpty() ? SwaggerConfigurationProerties.getDescription()
                                : docketInfo.getDescription())
                .version(docketInfo.getVersion().isEmpty() ? SwaggerConfigurationProerties.getVersion()
                        : docketInfo.getVersion())
                .license(docketInfo.getLicense().isEmpty() ? SwaggerConfigurationProerties.getLicense()
                        : docketInfo.getLicense())
                .licenseUrl(docketInfo.getLicenseUrl().isEmpty() ? SwaggerConfigurationProerties.getLicenseUrl()
                        : docketInfo.getLicenseUrl())
                .contact(new Contact(
                        docketInfo.getContact().getName().isEmpty()
                                ? SwaggerConfigurationProerties.getContact().getName()
                                : docketInfo.getContact().getName(),
                        docketInfo.getContact().getUrl().isEmpty()
                                ? SwaggerConfigurationProerties.getContact().getUrl()
                                : docketInfo.getContact().getUrl(),
                        docketInfo.getContact().getEmail().isEmpty()
                                ? SwaggerConfigurationProerties.getContact().getEmail()
                                : docketInfo.getContact().getEmail()))
                .termsOfServiceUrl(docketInfo.getTermsOfServiceUrl().isEmpty()
                        ? SwaggerConfigurationProerties.getTermsOfServiceUrl()
                        : docketInfo.getTermsOfServiceUrl())
                .build();

        // base-path?
        // ?path?/**
        if (docketInfo.getBasePath().isEmpty()) {
            docketInfo.getBasePath().add("/**");
        }
        List<Predicate<String>> basePath = new ArrayList();
        for (String path : docketInfo.getBasePath()) {
            basePath.add(PathSelectors.ant(path));
        }

        // exclude-path?
        List<Predicate<String>> excludePath = new ArrayList();
        for (String path : docketInfo.getExcludePath()) {
            excludePath.add(PathSelectors.ant(path));
        }

        Docket docketForBuilder = new Docket(DocumentationType.SWAGGER_2)
                .host(SwaggerConfigurationProerties.getHost()).apiInfo(apiInfo)
                .securitySchemes(Collections.singletonList(apiKey()))
                .securityContexts(Collections.singletonList(securityContext()))
                .globalOperationParameters(assemblyGlobalOperationParameters(
                        SwaggerConfigurationProerties.getGlobalOperationParameters(),
                        docketInfo.getGlobalOperationParameters()));

        // ??
        if (!SwaggerConfigurationProerties.getApplyDefaultResponseMessages()) {
            buildGlobalResponseMessage(SwaggerConfigurationProerties, docketForBuilder);
        }

        Docket docket = docketForBuilder.groupName(groupName).select()
                .apis(RequestHandlerSelectors.basePackage(docketInfo.getBasePackage()))
                .paths(Predicates.and(Predicates.not(Predicates.or(excludePath)), Predicates.or(basePath)))
                .build();

        /* ignoredParameterTypes **/
        Class<?>[] array = new Class[docketInfo.getIgnoredParameterTypes().size()];
        Class<?>[] ignoredParameterTypes = docketInfo.getIgnoredParameterTypes().toArray(array);
        docket.ignoredParameterTypes(ignoredParameterTypes);

        configurableBeanFactory.registerSingleton(groupName, docket);
        docketList.add(docket);
    }
    return docketList;
}

From source file:eu.lp0.cursus.scoring.scores.impl.GenericRaceLapsData.java

protected Iterable<Pilot> extractRaceLaps(Race race, Predicate<Pilot> filter) {
    // If they aren't marked as attending the race as a pilot, they don't get scored
    Predicate<Pilot> attending = Predicates.in(filteredPilots(race));
    if (filter != null) {
        filter = Predicates.and(attending, filter);
    } else {/*from w  w w. jav a2 s . com*/
        filter = attending;
    }

    // Convert a list of race events into a list of valid pilot laps
    return Iterables.filter(Iterables.transform(Iterables.unmodifiableIterable(race.getTallies()),
            new Function<RaceTally, Pilot>() {
                boolean scoring = scoreBeforeStart;

                @Override
                public Pilot apply(@Nonnull RaceTally tally) {
                    switch (tally.getType()) {
                    case START:
                        scoring = true;
                        break;

                    case LAP:
                        if (scoring) {
                            return tally.getPilot();
                        }
                        break;

                    case INVALID_LAP:
                        break;

                    case FINISH:
                        scoring = scoreAfterFinish;
                        break;
                    }

                    return null;
                }

            }), filter);
}

From source file:com.ardor3d.example.app.RotatingCubeGame.java

private void registerInputTriggers() {
    logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.W), new TriggerAction() {
        public void perform(final Canvas source, final InputState inputState, final double tpf) {
            moveForward(source, tpf);/*from   w w  w. ja  v a 2  s  . c o  m*/
        }
    }));
    logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.S), new TriggerAction() {
        public void perform(final Canvas source, final InputState inputState, final double tpf) {
            moveBack(source, tpf);
        }
    }));
    logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.A), new TriggerAction() {
        public void perform(final Canvas source, final InputState inputState, final double tpf) {
            turnLeft(source, tpf);
        }
    }));
    logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.D), new TriggerAction() {
        public void perform(final Canvas source, final InputState inputState, final double tpf) {
            turnRight(source, tpf);
        }
    }));
    logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.Q), new TriggerAction() {
        public void perform(final Canvas source, final InputState inputState, final double tpf) {
            moveLeft(source, tpf);
        }
    }));
    logicalLayer.registerTrigger(new InputTrigger(new KeyHeldCondition(Key.E), new TriggerAction() {
        public void perform(final Canvas source, final InputState inputState, final double tpf) {
            moveRight(source, tpf);
        }
    }));

    logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.ESCAPE), new TriggerAction() {
        public void perform(final Canvas source, final InputState inputState, final double tpf) {
            exit.exit();
        }
    }));

    logicalLayer
            .registerTrigger(new InputTrigger(new KeyPressedCondition(toggleRotationKey), new TriggerAction() {
                public void perform(final Canvas source, final InputState inputState, final double tpf) {
                    toggleRotation();
                }
            }));
    logicalLayer.registerTrigger(new InputTrigger(new KeyReleasedCondition(Key.U), new TriggerAction() {
        public void perform(final Canvas source, final InputState inputState, final double tpf) {
            toggleRotation();
        }
    }));

    logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.ZERO), new TriggerAction() {
        public void perform(final Canvas source, final InputState inputState, final double tpf) {
            resetCamera(source);
        }
    }));
    logicalLayer.registerTrigger(new InputTrigger(new KeyPressedCondition(Key.NINE), new TriggerAction() {
        public void perform(final Canvas source, final InputState inputState, final double tpf) {
            lookAtZero(source);
        }
    }));

    final Predicate<TwoInputStates> mouseMovedAndOneButtonPressed = Predicates.and(
            TriggerConditions.mouseMoved(),
            Predicates.or(TriggerConditions.leftButtonDown(), TriggerConditions.rightButtonDown()));

    logicalLayer.registerTrigger(new InputTrigger(mouseMovedAndOneButtonPressed, new TriggerAction() {
        public void perform(final Canvas source, final InputState inputState, final double tpf) {
            final MouseState mouseState = inputState.getMouseState();

            turn(source, mouseState.getDx() * tpf * -MOUSE_TURN_SPEED);
            rotateUpDown(source, mouseState.getDy() * tpf * -MOUSE_TURN_SPEED);
        }
    }));
    logicalLayer.registerTrigger(new InputTrigger(
            new MouseButtonCondition(ButtonState.DOWN, ButtonState.DOWN, ButtonState.UNDEFINED),
            new TriggerAction() {
                public void perform(final Canvas source, final InputState inputState, final double tpf) {
                    moveForward(source, tpf);
                }
            }));

}

From source file:org.apache.aurora.scheduler.sla.MetricCalculator.java

@Timed("sla_stats_computation")
@Override/*ww  w. ja  v  a 2  s .c  o  m*/
public void run() {
    FluentIterable<IScheduledTask> tasks = FluentIterable
            .from(Storage.Util.fetchTasks(storage, Query.unscoped()));

    List<IScheduledTask> prodTasks = tasks
            .filter(Predicates.compose(Predicates.and(ITaskConfig::isProduction, IS_SERVICE), Tasks::getConfig))
            .toList();

    List<IScheduledTask> nonProdTasks = tasks.filter(Predicates
            .compose(Predicates.and(Predicates.not(ITaskConfig::isProduction), IS_SERVICE), Tasks::getConfig))
            .toList();

    long nowMs = clock.nowMillis();
    Range<Long> timeRange = Range.closedOpen(nowMs - settings.refreshRateMs, nowMs);

    runAlgorithms(prodTasks, settings.prodMetrics, timeRange, NAME_QUALIFIER_PROD);
    runAlgorithms(nonProdTasks, settings.nonProdMetrics, timeRange, NAME_QUALIFIER_NON_PROD);
}