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

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

Introduction

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

Prototype

public static <A, B> Predicate<A> compose(Predicate<B> predicate, Function<A, ? extends B> function) 

Source Link

Document

Returns the composition of a function and a predicate.

Usage

From source file:org.apache.aurora.scheduler.thrift.ReadOnlySchedulerImpl.java

private Map<IJobKey, IJobConfiguration> getJobs(Optional<String> ownerRole,
        Multimap<IJobKey, IScheduledTask> tasks) {

    // We need to synthesize the JobConfiguration from the the current tasks because the
    // ImmediateJobManager doesn't store jobs directly and ImmediateJobManager#getJobs always
    // returns an empty Collection.
    Map<IJobKey, IJobConfiguration> jobs = Maps.newHashMap();

    jobs.putAll(Maps.transformEntries(tasks.asMap(), (jobKey, tasks1) -> {

        // Pick the latest transitioned task for each immediate job since the job can be in the
        // middle of an update or some shards have been selectively created.
        TaskConfig mostRecentTaskConfig = Tasks.getLatestActiveTask(tasks1).getAssignedTask().getTask()
                .newBuilder();//from   w w w.j a va 2  s. c o m

        return IJobConfiguration.build(
                new JobConfiguration().setKey(jobKey.newBuilder()).setOwner(mostRecentTaskConfig.getOwner())
                        .setTaskConfig(mostRecentTaskConfig).setInstanceCount(tasks1.size()));
    }));

    // Get cron jobs directly from the manager. Do this after querying the task store so the real
    // template JobConfiguration for a cron job will overwrite the synthesized one that could have
    // been created above.
    Predicate<IJobConfiguration> configFilter = ownerRole.isPresent()
            ? Predicates.compose(Predicates.equalTo(ownerRole.get()), JobKeys::getRole)
            : Predicates.alwaysTrue();
    jobs.putAll(Maps.uniqueIndex(FluentIterable.from(Storage.Util.fetchCronJobs(storage)).filter(configFilter),
            IJobConfiguration::getKey));

    return jobs;
}

From source file:org.sosy_lab.cpachecker.cfa.postprocessing.function.CFunctionPointerResolver.java

private List<CFunctionEntryNode> getFunctionSet(final CFunctionCall call) {
    return from(candidateFunctions).filter(CFunctionEntryNode.class)
            .filter(Predicates.compose(matchingFunctionCall,
                    new Function<CFunctionEntryNode, Pair<CFunctionCall, CFunctionType>>() {
                        @Override
                        public Pair<CFunctionCall, CFunctionType> apply(CFunctionEntryNode f) {
                            return Pair.of(call, f.getFunctionDefinition().getType());
                        }//from  w  w  w  . jav a  2 s  .  co m
                    }))
            .toList();
}

From source file:clocker.mesos.entity.MesosClusterImpl.java

public List<String> scanSlaves(JsonArray slaves) throws UnknownHostException {
    List<String> slaveIds = MutableList.<String>of();
    for (int i = 0; i < slaves.size(); i++) {
        JsonObject slave = slaves.get(i).getAsJsonObject();
        boolean active = slave.get("active").getAsBoolean();
        String id = slave.get("id").getAsString();
        String hostname = slave.get("hostname").getAsString();
        Double registered = slave.get("registered_time").getAsDouble();
        Group group = sensors().get(MESOS_SLAVES);

        Optional<Entity> entity = Iterables.tryFind(group.getMembers(), Predicates
                .compose(Predicates.equalTo(id), EntityFunctions.attribute(MesosSlave.MESOS_SLAVE_ID)));
        if (entity.isPresent()) {
            Entity found = entity.get();
            found.sensors().set(MesosSlave.SLAVE_ACTIVE, active);
            if (!active) {
                Lifecycle state = found.sensors().get(Attributes.SERVICE_STATE_ACTUAL);
                if (Lifecycle.ON_FIRE.equals(state) || Lifecycle.STARTING.equals(state)) {
                    continue;
                } else if (Lifecycle.STOPPING.equals(state) || Lifecycle.STOPPED.equals(state)) {
                    group.removeMember(found);
                    group.removeChild(found);
                    Entities.unmanage(found);
                } else {
                    ServiceStateLogic.setExpectedState(found, Lifecycle.STOPPING);
                }/* w w w  .j  a v  a  2  s. c  o m*/
            }
        } else if (active) {
            LocationSpec<SshMachineLocation> spec = LocationSpec.create(SshMachineLocation.class)
                    .configure(SshMachineLocation.SSH_HOST, hostname)
                    .configure("address", InetAddress.getByName(hostname)).displayName(hostname);
            if (config().get(MESOS_SLAVE_ACCESSIBLE)) {
                spec.configure(CloudLocationConfig.WAIT_FOR_SSHABLE, "true")
                        .configure(SshMachineLocation.DETECT_MACHINE_DETAILS, true)
                        .configure(SshMachineLocation.SSH_PORT, config().get(MesosSlave.SLAVE_SSH_PORT))
                        .configure(LocationConfigKeys.USER, config().get(MesosSlave.SLAVE_SSH_USER))
                        .configure(LocationConfigKeys.PASSWORD, config().get(MesosSlave.SLAVE_SSH_PASSWORD))
                        .configure(SshTool.PROP_PASSWORD, config().get(MesosSlave.SLAVE_SSH_PASSWORD))
                        .configure(SshTool.PROP_PORT, config().get(MesosSlave.SLAVE_SSH_PORT))
                        .configure(LocationConfigKeys.PRIVATE_KEY_DATA,
                                config().get(MesosSlave.SLAVE_SSH_PRIVATE_KEY_DATA))
                        .configure(LocationConfigKeys.PRIVATE_KEY_FILE,
                                config().get(MesosSlave.SLAVE_SSH_PRIVATE_KEY_FILE));
            } else {
                spec.configure(CloudLocationConfig.WAIT_FOR_SSHABLE, "false")
                        .configure(SshMachineLocation.DETECT_MACHINE_DETAILS, false);
            }
            SshMachineLocation machine = getManagementContext().getLocationManager().createLocation(spec);

            // Setup port forwarding
            MarathonPortForwarder portForwarder = new MarathonPortForwarder();
            portForwarder.setManagementContext(getManagementContext());

            EntitySpec<MesosSlave> slaveSpec = EntitySpec.create(MesosSlave.class)
                    .configure(MesosSlave.MESOS_SLAVE_ID, id)
                    .configure(MesosSlave.REGISTERED_AT, registered.longValue())
                    .configure(MesosSlave.MESOS_CLUSTER, this).displayName("Mesos Slave (" + hostname + ")");
            MesosSlave added = sensors().get(MESOS_SLAVES).addMemberChild(slaveSpec);
            added.sensors().set(MesosSlave.SLAVE_ACTIVE, active);
            added.sensors().set(MesosSlave.HOSTNAME, hostname);
            added.sensors().set(MesosSlave.ADDRESS, hostname);

            added.start(ImmutableList.of(machine));
            portForwarder.init(hostname, this);

            // Setup subnet tier
            SubnetTier subnetTier = added.addChild(
                    EntitySpec.create(SubnetTier.class).configure(SubnetTier.PORT_FORWARDER, portForwarder)
                            .configure(SubnetTier.SUBNET_CIDR, Cidr.UNIVERSAL));
            Entities.start(subnetTier, ImmutableList.of(machine));
            added.sensors().set(MesosSlave.SUBNET_TIER, subnetTier);
        }

        if (active)
            slaveIds.add(id);
    }
    return slaveIds;
}

From source file:com.eucalyptus.cloudwatch.backend.CloudWatchBackendService.java

public DescribeAlarmHistoryResponseType describeAlarmHistory(final DescribeAlarmHistoryType request)
        throws CloudWatchException {
    final DescribeAlarmHistoryResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();

    try {/*from w ww .ja  v  a2 s  . co  m*/
        final OwnerFullName ownerFullName = ctx.getUserFullName();
        final String accountId = ownerFullName.getAccountNumber();
        final String alarmName = validateAlarmName(request.getAlarmName(), false);
        final Date endDate = validateEndDate(request.getEndDate(), false);
        final Date startDate = validateStartDate(request.getStartDate(), false);
        validateDateOrder(startDate, endDate, "StartDate", "EndDate", false, false);
        final HistoryItemType historyItemType = validateHistoryItemType(request.getHistoryItemType(), false);
        final Integer maxRecords = validateMaxRecords(request.getMaxRecords());
        final String nextToken = request.getNextToken();
        final List<AlarmHistory> results = AlarmManager.describeAlarmHistory(accountId, alarmName, endDate,
                historyItemType, maxRecords, startDate, nextToken,
                Predicates.compose(RestrictedTypes.<CloudWatchMetadata.AlarmMetadata>filterPrivileged(),
                        TransformationFunctions.AlarmHistoryToAlarmMetadata.INSTANCE));
        if (maxRecords != null && results.size() == maxRecords) {
            reply.getDescribeAlarmHistoryResult().setNextToken(results.get(results.size() - 1).getNaturalId());
        }
        final AlarmHistoryItems alarmHistoryItems = new AlarmHistoryItems();
        alarmHistoryItems
                .setMember(Lists.newArrayList(Collections2.<AlarmHistory, AlarmHistoryItem>transform(results,
                        TransformationFunctions.AlarmHistoryToAlarmHistoryItem.INSTANCE)));
        reply.getDescribeAlarmHistoryResult().setAlarmHistoryItems(alarmHistoryItems);
    } catch (Exception ex) {
        handleException(ex);
    }
    return reply;
}

From source file:org.trancecode.xproc.PipelineParser.java

private static Step addImplicitInputPort(final Step step) {
    if (STEPS_WITH_IMPLICIT_INPUT_PORT.contains(step.getType())) {
        final Iterable<Port> inputPorts = Iterables.filter(step.getInputPorts(false), Predicates.not(
                Predicates.compose(Predicates.equalTo(XProcPorts.XPATH_CONTEXT), PortFunctions.getPortName())));
        if (Iterables.isEmpty(inputPorts)) {
            final Port port = Port.newInputPort(step.getName(), XProcPorts.SOURCE, step.getLocation())
                    .setPrimary(true);// w  w  w . j  av  a2  s .  c  o m
            LOG.trace("  add implicit input port: {}", port);
            return step.declarePort(port);
        }
    }

    return step;
}

From source file:com.qcadoo.view.internal.components.grid.GridComponentPattern.java

public Map<String, GridComponentColumn> getColumns() {
    // FIXME MAKU -> KRNA: I think we should return an unmodifable (immutable) map or (if mutability were intended) pack them
    // into SynchronizedMap.
    return Maps.filterEntries(columns,
            Predicates.compose(COLUMNS_VISIBLE_FOR_TENANT_PREDICATE, VALUE_FROM_MAP_ENTRY_FUNCTION));
}

From source file:brooklyn.entity.container.docker.DockerHostImpl.java

public void scanContainers() {
    // TODO remember that _half started_ containers left behind are not to be re-used
    // TODO add cleanup for these?
    getDynamicLocation().getLock().lock();
    try {//  ww w.j  a  va 2  s  .c om
        String output = runDockerCommand("ps");
        List<String> ps = Splitter.on(CharMatcher.anyOf("\r\n")).omitEmptyStrings().splitToList(output);
        if (ps.size() > 1) {
            for (int i = 1; i < ps.size(); i++) {
                String line = ps.get(i);
                String id = Strings.getFirstWord(line);
                Optional<Entity> container = Iterables.tryFind(getDockerContainerCluster().getMembers(),
                        Predicates.compose(StringPredicates.startsWith(id),
                                EntityFunctions.attribute(DockerContainer.CONTAINER_ID)));
                if (container.isPresent())
                    continue;

                // Build a DockerContainer without a locations, as it may not be SSHable
                String containerId = Strings.getFirstWord(runDockerCommand("inspect --format {{.Id}} " + id));
                String imageId = Strings.getFirstWord(runDockerCommand("inspect --format {{.Image}} " + id));
                String imageName = Strings
                        .getFirstWord(runDockerCommand("inspect --format {{.Config.Image}} " + id));
                EntitySpec<DockerContainer> containerSpec = EntitySpec
                        .create(config().get(DOCKER_CONTAINER_SPEC))
                        .configure(SoftwareProcess.ENTITY_STARTED, Boolean.TRUE)
                        .configure(DockerContainer.DOCKER_HOST, this)
                        .configure(DockerContainer.DOCKER_INFRASTRUCTURE, getInfrastructure())
                        .configure(DockerContainer.DOCKER_IMAGE_ID, imageId)
                        .configure(DockerAttributes.DOCKER_IMAGE_NAME, imageName)
                        .configure(DockerContainer.LOCATION_FLAGS, MutableMap.of("container", getMachine()));

                // Create, manage and start the container
                DockerContainer added = getDockerContainerCluster().addChild(containerSpec);
                Entities.manage(added);
                getDockerContainerCluster().addMember(added);
                ((EntityLocal) added).setAttribute(DockerContainer.CONTAINER_ID, containerId);
                added.start(ImmutableList.of(getDynamicLocation().getMachine()));
            }
        }
    } finally {
        getDynamicLocation().getLock().unlock();
    }
}

From source file:com.palantir.atlasdb.transaction.impl.SnapshotTransaction.java

private List<Entry<Cell, byte[]>> getPostfilteredWithLocalWrites(final String tableName,
        final SortedMap<Cell, byte[]> postFiltered, final RangeRequest rangeRequest,
        List<RowResult<Value>> prePostFilter, final byte[] endRowExclusive) {
    Map<Cell, Value> prePostFilterCells = Cells.convertRowResultsToCells(prePostFilter);
    Collection<Entry<Cell, byte[]>> postFilteredCells = Collections2.filter(postFiltered.entrySet(), Predicates
            .compose(Predicates.in(prePostFilterCells.keySet()), MapEntries.<Cell, byte[]>getKeyFunction()));
    Collection<Entry<Cell, byte[]>> localWritesInRange = getLocalWritesForRange(tableName,
            rangeRequest.getStartInclusive(), endRowExclusive).entrySet();
    return ImmutableList.copyOf(mergeInLocalWrites(postFilteredCells.iterator(), localWritesInRange.iterator(),
            rangeRequest.isReverse()));/* w w  w .ja  v a2  s. c o m*/
}

From source file:com.eucalyptus.compute.common.internal.tags.FilterSupport.java

private static <T> Function<? super String, Predicate<? super T>> explodedLiteralFilter(
        final Function<? super T, ?> extractor, final Function<String, Collection> explodeFunction) {
    return new Function<String, Predicate<? super T>>() {
        @SuppressWarnings("unchecked")
        @Override/*w  w w.  j a  v a 2  s  .c  o m*/
        public Predicate<T> apply(final String filterValue) {
            Collection values = explodeFunction.apply(filterValue);
            return values == null ? Predicates.<T>alwaysTrue()
                    : Predicates.compose(Predicates.<Object>in(values),
                            Functions.compose(extractor, Functions.<T>identity()));
        }
    };
}

From source file:com.palantir.atlasdb.transaction.impl.SnapshotTransaction.java

private static Iterator<Entry<Cell, byte[]>> mergeInLocalWrites(
        Iterator<Entry<Cell, byte[]>> postFilterIterator, Iterator<Entry<Cell, byte[]>> localWritesInRange,
        boolean isReverse) {
    Ordering<Entry<Cell, byte[]>> ordering = Ordering.natural()
            .onResultOf(MapEntries.<Cell, byte[]>getKeyFunction());
    Iterator<Entry<Cell, byte[]>> mergeIterators = IteratorUtils.mergeIterators(postFilterIterator,
            localWritesInRange, isReverse ? ordering.reverse() : ordering,
            new Function<Pair<Entry<Cell, byte[]>, Entry<Cell, byte[]>>, Entry<Cell, byte[]>>() {
                @Override/*from ww w . j ava2  s. com*/
                public Map.Entry<Cell, byte[]> apply(
                        Pair<Map.Entry<Cell, byte[]>, Map.Entry<Cell, byte[]>> from) {
                    // always override their value with written values
                    return from.rhSide;
                }
            });
    return Iterators.filter(mergeIterators,
            Predicates.compose(Predicates.not(Value.IS_EMPTY), MapEntries.<Cell, byte[]>getValueFunction()));
}