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:brooklyn.entity.messaging.qpid.QpidBrokerImpl.java

@Override
protected void connectSensors() {
    super.connectSensors();
    String serverInfoMBeanName = "org.apache.qpid:type=ServerInformation,name=ServerInformation";

    jmxFeed = JmxFeed.builder().entity(this).period(500, TimeUnit.MILLISECONDS)
            .pollAttribute(new JmxAttributePollConfig<Boolean>(SERVICE_UP).objectName(serverInfoMBeanName)
                    .attributeName("ProductVersion").onSuccess(new Function<Object, Boolean>() {
                        private boolean hasWarnedOfVersionMismatch;

                        @Override
                        public Boolean apply(Object input) {
                            if (input == null)
                                return false;
                            if (!hasWarnedOfVersionMismatch
                                    && !getConfig(QpidBroker.SUGGESTED_VERSION).equals(input)) {
                                log.warn("Qpid version mismatch: ProductVersion is {}, requested version is {}",
                                        input, getConfig(QpidBroker.SUGGESTED_VERSION));
                                hasWarnedOfVersionMismatch = true;
                            }// w  w  w . ja v  a  2 s .  c o m
                            return true;
                        }
                    }).onException(Functions.constant(false)))
            .build();
}

From source file:brooklyn.entity.mesos.framework.marathon.MarathonFrameworkImpl.java

@Override
public void connectSensors() {
    super.connectSensors();

    HttpFeed.Builder httpFeedBuilder = HttpFeed.builder().entity(this).period(2000, TimeUnit.MILLISECONDS)
            .baseUri(sensors().get(FRAMEWORK_URL))
            .credentialsIfNotNull(config().get(MesosCluster.MESOS_USERNAME),
                    config().get(MesosCluster.MESOS_PASSWORD))
            .poll(HttpPollConfig.forSensor(MARATHON_APPLICATIONS).suppressDuplicates(true).suburl("/v2/apps/")
                    .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("apps"),
                            JsonFunctions.forEach(JsonFunctions.<String>getPath("id"))))
                    .onFailureOrException(Functions.constant(Arrays.asList(new String[0]))))
            .poll(HttpPollConfig.forSensor(MARATHON_VERSION).suppressDuplicates(true).suburl("/v2/info/")
                    .onSuccess(HttpValueFunctions.jsonContents("version", String.class))
                    .onFailureOrException(Functions.constant("")))
            .poll(HttpPollConfig.forSensor(SERVICE_UP).suppressDuplicates(true).suburl("/ping")
                    .onSuccess(HttpValueFunctions.responseCodeEquals(200))
                    .onFailureOrException(Functions.constant(Boolean.FALSE)));
    httpFeed = httpFeedBuilder.build();/*  ww w  .ja v a  2 s.co m*/
}

From source file:org.apache.brooklyn.entity.messaging.qpid.QpidBrokerImpl.java

@Override
protected void connectSensors() {
    super.connectSensors();
    String serverInfoMBeanName = "org.apache.qpid:type=ServerInformation,name=ServerInformation";

    jmxFeed = JmxFeed.builder().entity(this).period(500, TimeUnit.MILLISECONDS)
            .pollAttribute(new JmxAttributePollConfig<Boolean>(SERVICE_UP).objectName(serverInfoMBeanName)
                    .attributeName("ProductVersion").onSuccess(new Function<Object, Boolean>() {
                        private boolean hasWarnedOfVersionMismatch;

                        @Override
                        public Boolean apply(Object input) {
                            if (input == null)
                                return false;
                            if (!hasWarnedOfVersionMismatch
                                    && !getConfig(QpidBroker.SUGGESTED_VERSION).equals(input)) {
                                log.warn("Qpid version mismatch: ProductVersion is {}, requested version is {}",
                                        input, getConfig(QpidBroker.SUGGESTED_VERSION));
                                hasWarnedOfVersionMismatch = true;
                            }/*from  w  w  w. ja v  a2s  .  co  m*/
                            return true;
                        }
                    }).onException(Functions.constant(false)).suppressDuplicates(true))
            .build();
}

From source file:brooklyn.entity.cloudfoundry.webapp.CloudFoundryWebAppImpl.java

/**
 * For connecting the {@link #MEMORY} sensor.
 * <p>//  w w  w .ja v a2  s .c o  m
 * Should be called inside {@link #connectSensors()}.
 *
 * @see #disconnectMemorySensor()
 */
protected void connectMemorySensor() {
    usedMemory = FunctionFeed.builder().entity(this).period(Duration.seconds(2))
            .poll(new FunctionPollConfig<Integer, Integer>(MEMORY).onException(Functions.constant(0))
                    .callable(new Callable<Integer>() {
                        public Integer call() {
                            return getDriver().getMemory();
                        }
                    }))
            .build();
}

From source file:org.apache.brooklyn.entity.nosql.riak.RiakNodeImpl.java

@Override
public void connectSensors() {
    super.connectSensors();
    connectServiceUpIsRunning();//from   w ww. j a  va2 s. c  o m
    HostAndPort accessible = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, getRiakWebPort());

    if (isHttpMonitoringEnabled()) {
        HttpFeed.Builder httpFeedBuilder = HttpFeed.builder().entity(this).period(500, TimeUnit.MILLISECONDS)
                .baseUri(String.format("http://%s/stats", accessible.toString()))
                .poll(new HttpPollConfig<Integer>(NODE_GETS)
                        .onSuccess(HttpValueFunctions.jsonContents("node_gets", Integer.class))
                        .onFailureOrException(Functions.constant(-1)))
                .poll(new HttpPollConfig<Integer>(NODE_GETS_TOTAL)
                        .onSuccess(HttpValueFunctions.jsonContents("node_gets_total", Integer.class))
                        .onFailureOrException(Functions.constant(-1)))
                .poll(new HttpPollConfig<Integer>(NODE_PUTS)
                        .onSuccess(HttpValueFunctions.jsonContents("node_puts", Integer.class))
                        .onFailureOrException(Functions.constant(-1)))
                .poll(new HttpPollConfig<Integer>(NODE_PUTS_TOTAL)
                        .onSuccess(HttpValueFunctions.jsonContents("node_puts_total", Integer.class))
                        .onFailureOrException(Functions.constant(-1)))
                .poll(new HttpPollConfig<Integer>(VNODE_GETS)
                        .onSuccess(HttpValueFunctions.jsonContents("vnode_gets", Integer.class))
                        .onFailureOrException(Functions.constant(-1)))
                .poll(new HttpPollConfig<Integer>(VNODE_GETS_TOTAL)
                        .onSuccess(HttpValueFunctions.jsonContents("vnode_gets_total", Integer.class))
                        .onFailureOrException(Functions.constant(-1)))
                .poll(new HttpPollConfig<Integer>(VNODE_PUTS)
                        .onSuccess(HttpValueFunctions.jsonContents("vnode_puts", Integer.class))
                        .onFailureOrException(Functions.constant(-1)))
                .poll(new HttpPollConfig<Integer>(VNODE_PUTS_TOTAL)
                        .onSuccess(HttpValueFunctions.jsonContents("vnode_puts_total", Integer.class))
                        .onFailureOrException(Functions.constant(-1)))
                .poll(new HttpPollConfig<Integer>(READ_REPAIRS_TOTAL)
                        .onSuccess(HttpValueFunctions.jsonContents("read_repairs_total", Integer.class))
                        .onFailureOrException(Functions.constant(-1)))
                .poll(new HttpPollConfig<Integer>(COORD_REDIRS_TOTAL)
                        .onSuccess(HttpValueFunctions.jsonContents("coord_redirs_total", Integer.class))
                        .onFailureOrException(Functions.constant(-1)))
                .poll(new HttpPollConfig<Integer>(MEMORY_PROCESSES_USED)
                        .onSuccess(HttpValueFunctions.jsonContents("memory_processes_used", Integer.class))
                        .onFailureOrException(Functions.constant(-1)))
                .poll(new HttpPollConfig<Integer>(SYS_PROCESS_COUNT)
                        .onSuccess(HttpValueFunctions.jsonContents("sys_process_count", Integer.class))
                        .onFailureOrException(Functions.constant(-1)))
                .poll(new HttpPollConfig<Integer>(PBC_CONNECTS)
                        .onSuccess(HttpValueFunctions.jsonContents("pbc_connects", Integer.class))
                        .onFailureOrException(Functions.constant(-1)))
                .poll(new HttpPollConfig<Integer>(PBC_ACTIVE)
                        .onSuccess(HttpValueFunctions.jsonContents("pbc_active", Integer.class))
                        .onFailureOrException(Functions.constant(-1)))
                .poll(new HttpPollConfig<List<String>>(RING_MEMBERS).onSuccess(
                        Functionals.chain(HttpValueFunctions.jsonContents("ring_members", String[].class),
                                new Function<String[], List<String>>() {
                                    @Nullable
                                    @Override
                                    public List<String> apply(@Nullable String[] strings) {
                                        return Arrays.asList(strings);
                                    }
                                }))
                        .onFailureOrException(Functions.constant(Arrays.asList(new String[0]))));

        for (AttributeSensor<Integer> sensor : ONE_MINUTE_SENSORS) {
            httpFeedBuilder.poll(new HttpPollConfig<Integer>(sensor).period(Duration.ONE_MINUTE)
                    .onSuccess(HttpValueFunctions.jsonContents(sensor.getName().substring(5), Integer.class))
                    .onFailureOrException(Functions.constant(-1)));
        }

        httpFeed = httpFeedBuilder.build();
    }

    enrichers().add(
            Enrichers.builder().combining(NODE_GETS, NODE_PUTS).computingSum().publishing(NODE_OPS).build());
    enrichers().add(Enrichers.builder().combining(NODE_GETS_TOTAL, NODE_PUTS_TOTAL).computingSum()
            .publishing(NODE_OPS_TOTAL).build());
    WebAppServiceMethods.connectWebAppServerPolicies(this);
}

From source file:brooklyn.event.feed.FeedConfig.java

public F setOnResult(T val) {
    return onResult(Functions.constant(val));
}

From source file:com.facebook.buck.thrift.ThriftPythonEnhancer.java

@Override
public PythonLibrary createBuildRule(TargetGraph targetGraph, BuildRuleParams params,
        BuildRuleResolver resolver, ThriftConstructorArg args, ImmutableMap<String, ThriftSource> sources,
        ImmutableSortedSet<BuildRule> deps) {

    ImmutableMap.Builder<Path, SourcePath> modulesBuilder = ImmutableMap.builder();

    // Iterate over all the thrift source, finding the python modules they generate and
    // building up a map of them.
    for (ImmutableMap.Entry<String, ThriftSource> ent : sources.entrySet()) {
        ThriftSource source = ent.getValue();
        Path outputDir = source.getOutputDir();

        for (String module : getGeneratedSources(params.getBuildTarget(), args, ent.getKey(),
                source.getServices())) {
            Path path = outputDir.resolve("gen-" + getLanguage()).resolve(module);
            modulesBuilder.put(Paths.get(module.endsWith(".py") ? module : module + ".py"),
                    new BuildTargetSourcePath(source.getCompileRule().getBuildTarget(), path));
        }/*from  w  ww  .  j a  v  a2 s.  c  om*/

    }

    ImmutableMap<Path, SourcePath> modules = modulesBuilder.build();

    // Create params which only use the language specific deps.
    BuildRuleParams langParams = params.copyWithChanges(params.getBuildTarget(), Suppliers.ofInstance(deps),
            Suppliers.ofInstance(ImmutableSortedSet.of()));

    // Construct a python library and return it as our language specific build rule.  Dependents
    // will use this to pull the generated sources into packages/PEXs.
    Function<? super PythonPlatform, ImmutableMap<Path, SourcePath>> resources = Functions
            .constant(ImmutableMap.<Path, SourcePath>of());
    return new PythonLibrary(langParams, new SourcePathResolver(new SourcePathRuleFinder(resolver)),
            Functions.constant(modules), resources, Optional.of(true));
}

From source file:org.apache.brooklyn.core.feed.FeedConfig.java

/** @see #onFailure(Function) */
public F setOnFailure(T val) {
    return onFailure(Functions.constant(val));
}

From source file:org.caleydo.view.domino.internal.data.Numerical1DMixin.java

public void fill(Builder b, TypedList data, EDimension dim, boolean[] existNeigbhor) {
    final Histogram hist = createHist(data);
    b.put(Histogram.class, hist);
    b.put("distribution.colors", getHistColors(hist, data));
    b.put("distribution.labels", getHistLabels(hist, data));
    b.put("distribution.largestBin", maxBinSize);
    b.put("distribution.total", size);

    b.put("id2double", toRaw);
    final MappedDoubleList<Integer> list = new MappedDoubleList<>(data, toRaw);
    b.put("min", min);
    b.put("max", max);
    b.put(IDoubleList.class, list);

    // FIXME hack, if we have positive and negatives to a centered bar plot
    if (min < 0 && max > 0)
        b.put("hbar.bar.center", 0);
    else {// w w  w .j ava  2  s  . c o m
        boolean leftN = existNeigbhor[EDirection.getPrimary(dim.opposite()).ordinal()];
        boolean rightN = existNeigbhor[EDirection.getPrimary(dim.opposite()).opposite().ordinal()];
        b.put("hbar.bar.left", (!rightN || (leftN && rightN)) && !(dim.isHorizontal() && !leftN && !rightN));
    }

    // b.put("hbar.id2color", new AlternatingColors(Color.BLACK, Color.LIGHT_GRAY, even(data)));
    b.put("hbar.id2color", Functions.constant(Color.BLACK));
    b.put("hbar.outline", Color.WHITE);
    // b.set("kaplanmeier.fillCurve");

    b.set("boxandwhiskers.showOutliers");
    b.set("boxandwhiskers.showMinMax");
    b.put("sheatmap.frameColor", Color.LIGHT_GRAY);

    if (dim.isVertical())
        b.set("axis.invertOrder");
}

From source file:com.google.devtools.build.lib.runtime.InvocationPolicyEnforcer.java

/**
 * Applies this OptionsPolicyEnforcer's policy to the given OptionsParser.
 *
 * @param parser The OptionsParser to enforce policy on.
 * @param command The command to which the options in the OptionsParser apply.
 * @throws OptionsParsingException//from   w  ww.j  av  a  2  s .  c  o  m
 */
public void enforce(OptionsParser parser, String command) throws OptionsParsingException {
    if (invocationPolicy == null) {
        return;
    }

    if (invocationPolicy.getFlagPoliciesCount() == 0) {
        LOG.warning("InvocationPolicy contains no flag policies.");
    }

    Function<Object, String> sourceFunction = Functions.constant("Invocation policy");

    for (FlagPolicy flagPolicy : invocationPolicy.getFlagPoliciesList()) {
        String flagName = flagPolicy.getFlagName();

        // Skip the flag policy if it doesn't apply to this command.
        if (!flagPolicy.getCommandsList().isEmpty() && !flagPolicy.getCommandsList().contains(command)) {
            LOG.info(String.format(
                    "Skipping flag policy for flag '%s' because it "
                            + "applies only to commands %s and the current command is '%s'",
                    flagName, flagPolicy.getCommandsList(), command));
            continue;
        }

        OptionValueDescription valueDescription;
        try {
            valueDescription = parser.getOptionValueDescription(flagName);
        } catch (IllegalArgumentException e) {
            // This flag doesn't exist. We are deliberately lenient if the flag policy has a flag
            // we don't know about. This is for better future proofing so that as new flags are added,
            // new policies can use the new flags without worrying about older versions of Bazel. 
            LOG.info(String.format("Flag '%s' specified by invocation policy does not exist", flagName));
            continue;
        }

        OptionDescription optionDescription = parser.getOptionDescription(flagName);
        // getOptionDescription() will return null if the option does not exist, however
        // getOptionValueDescription() above would have thrown an IllegalArgumentException if that
        // were the case.
        Verify.verifyNotNull(optionDescription);

        switch (flagPolicy.getOperationCase()) {
        case SET_VALUE:
            applySetValueOperation(parser, sourceFunction, flagPolicy, flagName, valueDescription,
                    optionDescription);
            break;

        case USE_DEFAULT:
            applyUseDefaultOperation(parser, flagName);
            break;

        case ALLOW_VALUES:
            applyAllowValuesOperation(parser, sourceFunction, flagPolicy, flagName, valueDescription,
                    optionDescription);
            break;

        case DISALLOW_VALUES:
            applyDisallowValuesOperation(parser, sourceFunction, flagPolicy, flagName, valueDescription,
                    optionDescription);
            break;

        case OPERATION_NOT_SET:
            throw new OptionsParsingException(
                    String.format("Flag policy for flag '%s' does not " + "have an operation", flagName));

        default:
            LOG.warning(String.format("Unknown operation '%s' from invocation policy for flag '%s'",
                    flagPolicy.getOperationCase(), flagName));
            break;
        }
    }
}