Example usage for com.google.common.base Functions constant

List of usage examples for com.google.common.base Functions constant

Introduction

In this page you can find the example usage for com.google.common.base Functions constant.

Prototype

public static <E> Function<Object, E> constant(@Nullable E value) 

Source Link

Document

Creates a function that returns value for any input.

Usage

From source file:com.qcadoo.mes.productionPerShift.util.ProgressPerShiftViewSaver.java

private Either<? extends List<Entity>, Void> validateDailyProgressesFor(final Entity progressForDay) {
    List<Entity> savedDailyProgresses = FluentIterable
            .from(progressForDay.getHasManyField(ProgressForDayFields.DAILY_PROGRESS))
            .transform(new Function<Entity, Entity>() {

                @Override/*from  w  w  w.j  av  a 2s .c o m*/
                public Entity apply(final Entity dailyProgress) {
                    return tryValidateDailyProgress(dailyProgress).fold(Functions.<Entity>identity(),
                            Functions.constant(dailyProgress));
                }
            }).toList();
    if (Iterables.all(savedDailyProgresses, IS_VALID)) {
        return Either.right(null);
    }
    return Either.left(savedDailyProgresses);
}

From source file:brooklyn.entity.cloudfoundry.CloudFoundryEntityImpl.java

/**
 * For connecting the {@link #SERVICE_UP} sensor to the value of the
 * {@code getDriver().isRunning()} expression.
 * <p/>//from   w  ww .java  2 s .  co  m
 * Should be called inside {@link #connectSensors()}.
 *
 * @see #disconnectServiceUpIsRunning()
 */
protected void connectServiceUpIsRunning() {
    serviceProcessIsRunning = FunctionFeed.builder().entity(this).period(Duration.FIVE_SECONDS)
            .poll(new FunctionPollConfig<Boolean, Boolean>(SERVICE_PROCESS_IS_RUNNING)
                    .onException(Functions.constant(Boolean.FALSE)).callable(new Callable<Boolean>() {
                        public Boolean call() {
                            return getDriver().isRunning();
                        }
                    }))
            .build();
}

From source file:org.apache.brooklyn.entity.software.base.SoftwareProcessImpl.java

/**
 * For connecting the {@link #SERVICE_UP} sensor to the value of the {@code getDriver().isRunning()} expression.
 * <p>// www.j a  va  2s .c  o m
 * Should be called inside {@link #connectSensors()}.
 *
 * @see #disconnectServiceUpIsRunning()
 */
protected void connectServiceUpIsRunning() {
    serviceProcessIsRunning = FunctionFeed.builder().entity(this).period(Duration.FIVE_SECONDS)
            .poll(new FunctionPollConfig<Boolean, Boolean>(SERVICE_PROCESS_IS_RUNNING).suppressDuplicates(true)
                    .onException(Functions.constant(Boolean.FALSE)).callable(new Callable<Boolean>() {
                        public Boolean call() {
                            return getDriver().isRunning();
                        }
                    }))
            .build();
}

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

public void connectSensors() {
    sensors().set(Attributes.MAIN_URI, URI.create(config().get(MESOS_URL)));

    HttpFeed.Builder httpFeedBuilder = HttpFeed.builder().entity(this).period(1, TimeUnit.MINUTES)
            .baseUri(sensors().get(Attributes.MAIN_URI))
            .credentialsIfNotNull(config().get(MESOS_USERNAME), config().get(MESOS_PASSWORD))
            .poll(HttpPollConfig.forSensor(SERVICE_UP).suburl("/master/health")
                    .onSuccess(HttpValueFunctions.responseCodeEquals(200))
                    .onFailureOrException(Functions.constant(Boolean.FALSE)))
            .poll(HttpPollConfig.forSensor(CLUSTER_NAME).suburl("/master/state.json")
                    .onSuccess(HttpValueFunctions.jsonContents("cluster", String.class))
                    .onFailureOrException(Functions.constant("")))
            .poll(HttpPollConfig.forSensor(CLUSTER_ID).suburl("/master/state.json")
                    .onSuccess(HttpValueFunctions.jsonContents("id", String.class))
                    .onFailureOrException(Functions.constant("")))
            .poll(HttpPollConfig.forSensor(MESOS_VERSION).suburl("/master/state.json")
                    .onSuccess(HttpValueFunctions.jsonContents("version", String.class))
                    .onFailureOrException(Functions.constant("")))
            .poll(HttpPollConfig.forSensor(CPUS_TOTAL).suburl("/system/stats.json")
                    .onSuccess(HttpValueFunctions.jsonContents("cpus_total", Integer.class))
                    .onFailureOrException(Functions.constant(-1)))
            .poll(HttpPollConfig.forSensor(LOAD_1MIN).suburl("/system/stats.json")
                    .onSuccess(HttpValueFunctions.jsonContents("avg_load_1min", Double.class))
                    .onFailureOrException(Functions.constant(-1.0d)))
            .poll(HttpPollConfig.forSensor(LOAD_5MIN).suburl("/system/stats.json")
                    .onSuccess(HttpValueFunctions.jsonContents("avg_load_5min", Double.class))
                    .onFailureOrException(Functions.constant(-1.0d)))
            .poll(HttpPollConfig.forSensor(LOAD_15MIN).suburl("/system/stats.json")
                    .onSuccess(HttpValueFunctions.jsonContents("avg_load_15min", Double.class))
                    .onFailureOrException(Functions.constant(-1.0d)))
            .poll(HttpPollConfig.forSensor(MEMORY_FREE_BYTES).suburl("/system/stats.json")
                    .onSuccess(HttpValueFunctions.jsonContents("mem_free_bytes", Long.class))
                    .onFailureOrException(Functions.constant(-1L)))
            .poll(HttpPollConfig.forSensor(MEMORY_TOTAL_BYTES).suburl("/system/stats.json")
                    .onSuccess(HttpValueFunctions.jsonContents("mem_total_bytes", Long.class))
                    .onFailureOrException(Functions.constant(-1L)));
    httpFeed = httpFeedBuilder.build();/* www  .  j a v  a  2s . c  om*/

    Duration scanInterval = config().get(SCAN_INTERVAL);
    HttpFeed.Builder scanBuilder = HttpFeed.builder().entity(this).period(scanInterval)
            .baseUri(sensors().get(Attributes.MAIN_URI))
            .credentialsIfNotNull(config().get(MESOS_USERNAME), config().get(MESOS_PASSWORD))
            .poll(HttpPollConfig.forSensor(MESOS_SLAVE_LIST).description("Scan Cluster Slaves")
                    .suburl("/master/state.json").onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(),
                            JsonFunctions.walk("slaves"), new Function<JsonElement, List<String>>() {
                                @Override
                                public List<String> apply(JsonElement slaves) {
                                    try {
                                        return scanSlaves(slaves.getAsJsonArray());
                                    } catch (UnknownHostException e) {
                                        throw Exceptions.propagate(e);
                                    }
                                }
                            }))
                    .onFailureOrException(Functions.<List<String>>constant(null)))
            .poll(HttpPollConfig.forSensor(MESOS_FRAMEWORK_LIST).description("Scan Cluster Frameworks")
                    .suburl("/master/state.json").onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(),
                            JsonFunctions.walk("frameworks"), new Function<JsonElement, List<String>>() {
                                @Override
                                public List<String> apply(JsonElement frameworks) {
                                    return scanFrameworks(frameworks.getAsJsonArray());
                                }
                            }))
                    .onFailureOrException(Functions.<List<String>>constant(null)));
    scanner = scanBuilder.build();
}

From source file:com.palantir.atlasdb.keyvalue.rdbms.PostgresKeyValueService.java

@Override
public void put(final String tableName, final Map<Cell, byte[]> values, final long timestamp)
        throws KeyAlreadyExistsException {
    try {//ww  w. j  ava  2s  .  c o m
        batch(values.entrySet(), new Function<Collection<Entry<Cell, byte[]>>, Void>() {
            @Override
            @Nullable
            public Void apply(@Nullable final Collection<Entry<Cell, byte[]>> input) {
                getDbi().withHandle(new HandleCallback<Void>() {
                    @Override
                    public Void withHandle(Handle handle) throws Exception {
                        deleteInternalInTransaction(tableName,
                                Maps.transformValues(values, Functions.constant(timestamp)).entrySet(), handle);
                        putInternalInTransaction(tableName, input, timestamp, handle);
                        return null;
                    }
                });
                return null;
            }
        });
    } catch (RuntimeException e) {
        if (AtlasSqlUtils.isKeyAlreadyExistsException(e)) {
            throw new KeyAlreadyExistsException("Unique constraint violation", e);
        }
        throw e;
    }
}

From source file:org.pentaho.di.trans.dataservice.serialization.DataServiceMetaStoreUtil.java

static Map<Integer, String> createCacheEntries(DataServiceMeta dataService) {
    Set<Integer> keys = createCacheKeys(dataService.getServiceTrans(), dataService.getStepname());
    return Maps.asMap(keys, Functions.constant(dataService.getName()));
}

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

@Override
public Response getJobUpdateDiff(JobUpdateRequest mutableRequest) {
    IJobUpdateRequest request;/*from   w  w w.j  a va2 s  .c  o m*/
    try {
        request = IJobUpdateRequest
                .build(new JobUpdateRequest(mutableRequest).setTaskConfig(configurationManager
                        .validateAndPopulate(ITaskConfig.build(mutableRequest.getTaskConfig())).newBuilder()));
    } catch (TaskDescriptionException e) {
        return error(INVALID_REQUEST, e);
    }

    IJobKey job = request.getTaskConfig().getJob();

    return storage.read(storeProvider -> {
        if (storeProvider.getCronJobStore().fetchJob(job).isPresent()) {
            return invalidRequest(NO_CRON);
        }

        JobDiff diff = JobDiff.compute(storeProvider.getTaskStore(), job,
                JobDiff.asMap(request.getTaskConfig(), request.getInstanceCount()),
                request.getSettings().getUpdateOnlyTheseInstances());

        Map<Integer, ITaskConfig> replaced = diff.getReplacedInstances();
        Map<Integer, ITaskConfig> replacements = Maps.asMap(diff.getReplacementInstances(),
                Functions.constant(request.getTaskConfig()));

        Map<Integer, ITaskConfig> add = Maps.filterKeys(replacements,
                Predicates.in(Sets.difference(replacements.keySet(), replaced.keySet())));
        Map<Integer, ITaskConfig> remove = Maps.filterKeys(replaced,
                Predicates.in(Sets.difference(replaced.keySet(), replacements.keySet())));
        Map<Integer, ITaskConfig> update = Maps.filterKeys(replaced,
                Predicates.in(Sets.intersection(replaced.keySet(), replacements.keySet())));

        return ok(
                Result.getJobUpdateDiffResult(new GetJobUpdateDiffResult().setAdd(instancesToConfigGroups(add))
                        .setRemove(instancesToConfigGroups(remove)).setUpdate(instancesToConfigGroups(update))
                        .setUnchanged(instancesToConfigGroups(diff.getUnchangedInstances()))));
    });
}

From source file:de.bund.bfr.knime.nls.chart.ChartConfigPanel.java

public void init(String varY, List<String> variablesX, List<String> parameters) {
    String currentVarX = getVarX();

    yBox.removeAllItems();// w w w  .j  ava  2  s.  c  om
    yBox.addItem(varY);
    yBox.setSelectedIndex(0);
    xBox.removeAllItems();

    if (variablesX != null && !variablesX.isEmpty()) {
        variablesX.forEach(x -> xBox.addItem(x));

        if (variablesX.contains(currentVarX)) {
            xBox.setSelectedItem(currentVarX);
        } else {
            xBox.setSelectedIndex(0);
        }
    }

    if (outerParameterPanel != null) {
        outerParameterPanel.removeAll();
        parameterPanel = new VariablePanel(
                Maps.asMap(new LinkedHashSet<>(parameters != null ? parameters : Collections.emptySet()),
                        Functions.constant(new ArrayList<>())),
                null, null, false, true, true);
        parameterPanel.addValueListener(e -> fireConfigChanged());
        outerParameterPanel.add(parameterPanel, BorderLayout.WEST);

        Container container = getParent();

        while (container != null) {
            if (container instanceof JPanel) {
                ((JPanel) container).revalidate();
                break;
            }

            container = container.getParent();
        }
    }

    if (outerVariablePanel != null) {
        outerVariablePanel.removeAll();
        variablePanel = new VariablePanel(
                Maps.asMap(new LinkedHashSet<>(variablesX != null ? variablesX : Collections.emptySet()),
                        Functions.constant(new ArrayList<>())),
                null, null, false, true, true);
        variablePanel.setEnabled(getVarX(), false);
        variablePanel.addValueListener(e -> fireConfigChanged());
        outerVariablePanel.add(variablePanel, BorderLayout.WEST);

        Container container = getParent();

        while (container != null) {
            if (container instanceof JPanel) {
                ((JPanel) container).revalidate();
                break;
            }

            container = container.getParent();
        }
    }
}

From source file:com.eucalyptus.cluster.callback.reporting.CloudWatchHelper.java

private static <E extends Enum<E>> Map<String, String> metricsToUnitType(final Class<E> unitEnum) {
    return CollectionUtils.putAll(EnumSet.allOf(unitEnum), Maps.<String, String>newHashMap(),
            Functions.toStringFunction(), Functions.constant(unitEnum.getSimpleName()));
}

From source file:com.palantir.atlasdb.cleaner.Scrubber.java

void scrubImmediately(final TransactionManager txManager,
        final Multimap<String, Cell> tableNameToCell, final long scrubTimestamp, final long commitTimestamp) {
    if (log.isInfoEnabled()) {
        log.info("Scrubbing a total of " + tableNameToCell.size() + " cells immediately.");
    }//from w  w w . jav a2 s  .  c  o  m

    // Note that if the background scrub thread is also running at the same time, it will try to scrub
    // the same cells as the current thread (since these cells were queued for scrubbing right before
    // the hard delete transaction committed; while this is unfortunate (because it means we will be
    // doing more work than necessary), the behavior is still correct
    long nextImmutableTimestamp;
    while ((nextImmutableTimestamp = immutableTimestampSupplier.get()) < commitTimestamp) {
        try {
            if (log.isInfoEnabled()) {
                log.info(String.format(
                        "Sleeping because immutable timestamp %d has not advanced to at least commit timestamp %d",
                        nextImmutableTimestamp, commitTimestamp));
            }
            Thread.sleep(AtlasDbConstants.SCRUBBER_RETRY_DELAY_MILLIS);
        } catch (InterruptedException e) {
            log.error("Interrupted while waiting for immutableTimestamp to advance past commitTimestamp", e);
        }
    }

    List<Future<Void>> scrubFutures = Lists.newArrayList();
    for (List<Entry<String, Cell>> batch : Iterables.partition(tableNameToCell.entries(),
            batchSizeSupplier.get())) {
        final Multimap<String, Cell> batchMultimap = HashMultimap.create();
        for (Entry<String, Cell> e : batch) {
            batchMultimap.put(e.getKey(), e.getValue());
        }

        final Callable<Void> c = new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                if (log.isInfoEnabled()) {
                    log.info("Scrubbing " + batchMultimap.size() + " cells immediately.");
                }

                // Here we don't need to check scrub timestamps because we guarantee that scrubImmediately is called
                // AFTER the transaction commits
                scrubCells(txManager, batchMultimap, scrubTimestamp, TransactionType.AGGRESSIVE_HARD_DELETE);

                Multimap<Cell, Long> cellToScrubTimestamp = HashMultimap.create();

                cellToScrubTimestamp = Multimaps.invertFrom(
                        Multimaps.index(batchMultimap.values(), Functions.constant(scrubTimestamp)),
                        cellToScrubTimestamp);

                scrubberStore.markCellsAsScrubbed(cellToScrubTimestamp, batchSizeSupplier.get());

                if (log.isInfoEnabled()) {
                    log.info("Completed scrub immediately.");
                }
                return null;
            }
        };
        if (!inScrubThread.get()) {
            scrubFutures.add(exec.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    inScrubThread.set(true);
                    c.call();
                    return null;
                }
            }));
        } else {
            try {
                c.call();
            } catch (Exception e) {
                throw Throwables.throwUncheckedException(e);
            }
        }
    }

    for (Future<Void> future : scrubFutures) {
        try {
            future.get();
        } catch (InterruptedException e) {
            throw Throwables.throwUncheckedException(e);
        } catch (ExecutionException e) {
            throw Throwables.rewrapAndThrowUncheckedException(e);
        }
    }
}