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:org.grouplens.lenskit.eval.traintest.FunctionModelMetric.java

@Nonnull
@Override//from  w  w  w . j a v a2s  .c o  m
public List<Object> getResults(List<Object> context) {
    if (context == null) {
        return Lists.transform(columnHeaders, Functions.constant(null));
    } else {
        return context;
    }
}

From source file:org.apache.brooklyn.entity.nosql.hazelcast.HazelcastNodeImpl.java

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

    if (LOG.isDebugEnabled()) {
        LOG.debug("Connecting sensors for node: {} ", getAttribute(Attributes.HOSTNAME));
    }//from   w w  w  . j a  v  a  2s  . co  m

    HostAndPort hp = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, getNodePort());

    String nodeUri = String.format("http://%s:%d/hazelcast/rest/cluster", hp.getHostText(), hp.getPort());
    sensors().set(Attributes.MAIN_URI, URI.create(nodeUri));

    if (LOG.isDebugEnabled()) {
        LOG.debug("Node {} is using {} as a main URI", this, nodeUri);
    }

    httpFeed = HttpFeed.builder().entity(this).period(3000, TimeUnit.MILLISECONDS).baseUri(nodeUri)
            .poll(new HttpPollConfig<Boolean>(SERVICE_UP).onSuccess(HttpValueFunctions.responseCodeEquals(200))
                    .onFailureOrException(Functions.constant(false)))
            .build();
}

From source file:com.facebook.presto.sql.planner.assertions.TopNMatcher.java

@Override
public MatchResult detailMatches(PlanNode node, PlanNodeCost planNodeCost, Session session, Metadata metadata,
        SymbolAliases symbolAliases) {//from   w ww .j av  a2 s.c  o m
    checkState(shapeMatches(node),
            "Plan testing framework error: shapeMatches returned false in detailMatches in %s",
            this.getClass().getName());
    TopNNode topNNode = (TopNNode) node;

    if (topNNode.getCount() != count) {
        return NO_MATCH;
    }

    List<Symbol> expectedOrderBy = orderBySymbols.stream().map(alias -> alias.toSymbol(symbolAliases))
            .collect(toImmutableList());

    if (!topNNode.getOrderBy().equals(expectedOrderBy)) {
        return NO_MATCH;
    }

    Map<Symbol, SortOrder> expectedOrderings = Maps.toMap(expectedOrderBy,
            Functions.constant(SortOrder.ASC_NULLS_FIRST));

    if (!topNNode.getOrderings().equals(expectedOrderings)) {
        return NO_MATCH;
    }

    return match();
}

From source file:brooklyn.entity.nosql.couchdb.CouchDBNodeImpl.java

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

    connectServiceUpIsRunning();//from w w w  . ja  v  a 2s .  c  o m

    httpFeed = HttpFeed.builder().entity(this).period(500, TimeUnit.MILLISECONDS)
            .baseUri(
                    String.format("http://%s:%d/_stats", getAttribute(HOSTNAME), getHttpPort()))
            .poll(new HttpPollConfig<Integer>(REQUEST_COUNT)
                    .onSuccess(HttpValueFunctions.jsonContents(new String[] { "httpd", "requests", "count" },
                            Integer.class))
                    .onFailureOrException(Functions.constant(-1)))
            .poll(new HttpPollConfig<Integer>(ERROR_COUNT)
                    .onSuccess(HttpValueFunctions
                            .jsonContents(new String[] { "httpd_status_codes", "404", "count" }, Integer.class))
                    .onFailureOrException(Functions.constant(-1)))
            .poll(new HttpPollConfig<Integer>(TOTAL_PROCESSING_TIME)
                    .onSuccess(
                            HttpValueFunctions.jsonContents(new String[] { "couchdb", "request_time", "count" },
                                    Integer.class))
                    .onFailureOrException(Functions.constant(-1)))
            .poll(new HttpPollConfig<Integer>(MAX_PROCESSING_TIME)
                    .onSuccess(
                            HttpValueFunctions.chain(
                                    HttpValueFunctions.jsonContents(
                                            new String[] { "couchdb", "request_time", "max" }, Double.class),
                                    new Function<Double, Integer>() {
                                        @Override
                                        public Integer apply(@Nullable Double input) {
                                            return Integer.valueOf(input.intValue());
                                        }
                                    }))
                    .onFailureOrException(Functions.constant(-1)))
            .build();

    WebAppServiceMethods.connectWebAppServerPolicies(this);
}

From source file:brooklyn.entity.webapp.jboss.JBoss6ServerImpl.java

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

    String requestProcessorMbeanName = "jboss.web:type=GlobalRequestProcessor,name=http-*";
    String serverMbeanName = "jboss.system:type=Server";

    jmxFeed = JmxFeed.builder().entity(this).period(500, TimeUnit.MILLISECONDS)
            .pollAttribute(new JmxAttributePollConfig<Integer>(ERROR_COUNT)
                    .objectName(requestProcessorMbeanName).attributeName("errorCount"))
            .pollAttribute(new JmxAttributePollConfig<Integer>(REQUEST_COUNT)
                    .objectName(requestProcessorMbeanName).attributeName("requestCount"))
            .pollAttribute(new JmxAttributePollConfig<Integer>(TOTAL_PROCESSING_TIME)
                    .objectName(requestProcessorMbeanName).attributeName("processingTime"))
            .pollAttribute(new JmxAttributePollConfig<Boolean>(SERVICE_UP).objectName(serverMbeanName)
                    .attributeName("Started").onException(Functions.constant(false)))
            .build();/*from   www  .j  a v  a2  s  .  c  o m*/
}

From source file:org.caleydo.view.heatmap.v2.internal.SingleHeatMapElementFactory.java

@SuppressWarnings("unchecked")
@Override/*from  www.j a v  a2s.  co  m*/
public GLElement create(GLElementFactoryContext context) {
    EDetailLevel detailLevel = context.get(EDetailLevel.class, EDetailLevel.LOW);

    IHeatMapDataProvider data;
    EDimension dim;
    Function<? super Integer, Color> id2color;

    if (hasTablePerspective(context)) {
        final TablePerspectiveDataProvider d = new TablePerspectiveDataProvider(context.getData());
        data = d;
        dim = EDimension.get(context.getData().getNrRecords() == 1);
        final Integer id = d.getData(dim.opposite()).get(0);
        BasicBlockColorer c = new BasicBlockColorer(d.getDataDomain());
        if (dim.isDimension()) {
            id2color = Functions2.partial(c, id);
        } else {
            id2color = Functions2.partial2(c, id);
        }
    } else {
        dim = context.get(EDimension.class, EDimension.RECORD);
        IDType idType = context.get(IDType.class, null);
        List<Integer> list = context.get(List.class, null);
        DimensionData d = new DimensionData(list, Functions.constant("UnNamed"), Collections.<Group>emptyList(),
                idType);
        //define data
        data = new ListDataProvider(dim.select(null, d), dim.select(d, null), toId2label(context, dim));
        id2color = context.get("id2color", Function.class, null);
    }
    SingleHeatMapPlotElement elem = new SingleHeatMapPlotElement(data, detailLevel, dim, id2color);
    setSelectionStrategies(elem, context);
    return elem;
}

From source file:org.apache.brooklyn.entity.webapp.jboss.JBoss6ServerImpl.java

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

    String requestProcessorMbeanName = "jboss.web:type=GlobalRequestProcessor,name=http-*";
    String serverMbeanName = "jboss.system:type=Server";
    boolean retrieveUsageMetrics = getConfig(RETRIEVE_USAGE_METRICS);

    if (isJmxEnabled()) {
        jmxFeed = JmxFeed.builder().entity(this).period(500, TimeUnit.MILLISECONDS)
                .pollAttribute(new JmxAttributePollConfig<Boolean>(SERVICE_UP)
                        // TODO instead of setting SERVICE_UP directly, want to use equivalent of 
                        // addEnricher(Enrichers.builder().updatingMap(Attributes.SERVICE_NOT_UP_INDICATORS).key("serverMBean")...
                        // but not supported in feed?
                        .objectName(serverMbeanName).attributeName("Started")
                        .onException(Functions.constant(false)).suppressDuplicates(true))
                .pollAttribute(// ww  w  . jav a2 s  . c o m
                        new JmxAttributePollConfig<Integer>(ERROR_COUNT).objectName(requestProcessorMbeanName)
                                .attributeName("errorCount").enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Integer>(REQUEST_COUNT)
                        .objectName(requestProcessorMbeanName).attributeName("requestCount")
                        .onFailureOrException(EntityFunctions.attribute(this, REQUEST_COUNT))
                        .enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Integer>(TOTAL_PROCESSING_TIME)
                        .objectName(requestProcessorMbeanName).attributeName("processingTime")
                        .enabled(retrieveUsageMetrics))
                .build();
    } else {
        // if not using JMX
        log.warn(this + " running without JMX monitoring; limited visibility of service available");
        connectServiceUpIsRunning();
    }
}

From source file:org.caleydo.view.heatmap.v2.internal.SingleBarElementFactory.java

@SuppressWarnings("unchecked")
@Override// w  w  w. j  av a 2  s  .c  o  m
public GLElement create(GLElementFactoryContext context) {
    EDetailLevel detailLevel = context.get(EDetailLevel.class, EDetailLevel.LOW);

    IHeatMapDataProvider data;
    EDimension dim;
    Function<? super Integer, Double> id2double;
    Function<? super Double, Vec2f> value2bar;
    Function<? super Integer, Color> id2color;

    if (hasTablePerspective(context)) {
        final TablePerspectiveDataProvider d = new TablePerspectiveDataProvider(context.getData());
        data = d;
        dim = EDimension.get(context.getData().getNrRecords() == 1);
        final Integer id = d.getData(dim.opposite()).get(0);
        if (dim.isDimension()) {
            id2double = Functions2.partial(d, id);
        } else {
            id2double = Functions2.partial2(d, id);
        }
    } else {
        dim = context.get(EDimension.class, EDimension.RECORD);
        IDType idType = context.get(IDType.class, null);
        List<Integer> list = context.get(List.class, null);
        DimensionData d = new DimensionData(list, Functions.constant("UnNamed"), Collections.<Group>emptyList(),
                idType);
        //define data
        data = new ListDataProvider(dim.select(null, d), dim.select(d, null),
                SingleHeatMapElementFactory.toId2label(context, dim));
        id2double = context.get("id2double", Function.class, null);
    }
    id2color = context.get("id2color", Function.class,
            Functions.constant(context.get("color", Color.class, Color.BLACK)));
    value2bar = extractValue2Bar(context);
    SingleBarPlotElement elem = new SingleBarPlotElement(data, detailLevel, dim, id2double, value2bar,
            id2color);
    elem.setFrameColor(context.get("frameColor", Color.class, elem.getFrameColor()));
    elem.setOutline(context.get("outline", Color.class, elem.getOutline()));
    setSelectionStrategies(elem, context);
    return elem;
}

From source file:org.sosy_lab.cpachecker.cpa.invariants.formula.ReplaceVisitor.java

/**
 * Creates a new replace visitor for replacing occurrences of the first given
 * formula by the second given formula in visited formulae.
 *
 * @param pToReplace the formula to be replaced.
 * @param pReplacement the replacement formula.
 *//*from  w  w w .ja va 2s . c  o m*/
public ReplaceVisitor(NumeralFormula<T> pToReplace, NumeralFormula<T> pReplacement) {
    this(pToReplace == null ? Predicates.<NumeralFormula<T>>alwaysFalse()
            : Predicates.<NumeralFormula<T>>equalTo(pToReplace), Functions.constant(pReplacement),
            Predicates.<BooleanFormula<T>>alwaysFalse(), Functions.<BooleanFormula<T>>identity());
}

From source file:brooklyn.entity.nosql.redis.RedisStoreImpl.java

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

    connectServiceUpIsRunning();//from ww  w . ja  v  a  2  s .c om

    // Find an SshMachineLocation for the UPTIME feed
    Optional<Location> location = Iterables.tryFind(getLocations(),
            Predicates.instanceOf(SshMachineLocation.class));
    if (!location.isPresent())
        throw new IllegalStateException("Could not find SshMachineLocation in list of locations");
    SshMachineLocation machine = (SshMachineLocation) location.get();
    String statsCommand = getDriver().getRunDir() + "/bin/redis-cli -p " + getRedisPort() + " info stats";

    sshFeed = SshFeed.builder().entity(this).machine(machine).period(5, TimeUnit.SECONDS)
            .poll(new SshPollConfig<Integer>(UPTIME)
                    .command(getDriver().getRunDir() + "/bin/redis-cli -p " + getRedisPort() + " info server")
                    .onFailureOrException(Functions.constant(-1)).onSuccess(infoFunction("uptime_in_seconds")))
            .poll(new SshPollConfig<Integer>(TOTAL_CONNECTIONS_RECEIVED).command(statsCommand)
                    .onFailureOrException(Functions.constant(-1))
                    .onSuccess(infoFunction("total_connections_received")))
            .poll(new SshPollConfig<Integer>(TOTAL_COMMANDS_PROCESSED).command(statsCommand)
                    .onFailureOrException(Functions.constant(-1))
                    .onSuccess(infoFunction("total_commands_processed")))
            .poll(new SshPollConfig<Integer>(EXPIRED_KEYS).command(statsCommand)
                    .onFailureOrException(Functions.constant(-1)).onSuccess(infoFunction("expired_keys")))
            .poll(new SshPollConfig<Integer>(EVICTED_KEYS).command(statsCommand)
                    .onFailureOrException(Functions.constant(-1)).onSuccess(infoFunction("evicted_keys")))
            .poll(new SshPollConfig<Integer>(KEYSPACE_HITS).command(statsCommand)
                    .onFailureOrException(Functions.constant(-1)).onSuccess(infoFunction("keyspace_hits")))
            .poll(new SshPollConfig<Integer>(KEYSPACE_MISSES).command(statsCommand)
                    .onFailureOrException(Functions.constant(-1)).onSuccess(infoFunction("keyspace_misses")))
            .build();
}