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.cloudfoundry.webapp.CloudFoundryWebAppImpl.java

/**
 * For connecting the {@link #INSTANCES_NUM} sensor.
 * <p>//from ww w .  jav  a2s.c o  m
 * Should be called inside {@link #connectSensors()}.
 *
 * @see #disconnectInstancesNumberSensor()
 */
protected void connectInstancesNumberSensor() {
    usedNumberOfInstances = FunctionFeed.builder().entity(this).period(Duration.seconds(2))
            .poll(new FunctionPollConfig<Integer, Integer>(INSTANCES_NUM).onException(Functions.constant(0))
                    .callable(new Callable<Integer>() {
                        public Integer call() {
                            return getDriver().getInstancesNumber();
                        }
                    }))
            .build();
}

From source file:brooklyn.entity.software.http.HttpRequestSensor.java

@Override
public void apply(final EntityLocal entity) {
    super.apply(entity);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Adding HTTP JSON sensor {} to {}", name, entity);
    }/*  w  w  w.  j  a  v  a 2  s  .  c om*/

    HttpPollConfig<T> pollConfig = new HttpPollConfig<T>(sensor)
            .checkSuccess(HttpValueFunctions.responseCodeEquals(200))
            .onFailureOrException(Functions.constant((T) null))
            .onSuccess(HttpValueFunctions.<T>jsonContentsFromPath(jsonPath)).period(period);

    HttpFeed.builder().entity(entity).baseUri(uri).credentialsIfNotNull(username, password).poll(pollConfig)
            .build();
}

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

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

    HostAndPort hp = BrooklynAccessUtils.getBrooklynAccessibleAddress(this,
            getAttribute(MANAGEMENT_HTTP_PORT) + getConfig(PORT_INCREMENT));

    String managementUri = String.format("http://%s:%s/management/subsystem/web/connector/http/read-resource",
            hp.getHostText(), hp.getPort());
    setAttribute(MANAGEMENT_URL, managementUri);
    log.debug("JBoss sensors for " + this + " reading from " + managementUri);
    Map<String, String> includeRuntimeUriVars = ImmutableMap.of("include-runtime", "true");

    httpFeed = HttpFeed.builder().entity(this).period(200).baseUri(managementUri)
            .credentials(getConfig(MANAGEMENT_USER), getConfig(MANAGEMENT_PASSWORD))
            .poll(new HttpPollConfig<Integer>(MANAGEMENT_STATUS).onSuccess(HttpValueFunctions.responseCode()))
            .poll(new HttpPollConfig<Boolean>(MANAGEMENT_URL_UP)
                    .onSuccess(HttpValueFunctions.responseCodeEquals(200))
                    .onFailureOrException(Functions.constant(false)))
            .poll(new HttpPollConfig<Integer>(REQUEST_COUNT).vars(includeRuntimeUriVars)
                    .onSuccess(HttpValueFunctions.jsonContents("requestCount", Integer.class)))
            .poll(new HttpPollConfig<Integer>(ERROR_COUNT).vars(includeRuntimeUriVars)
                    .onSuccess(HttpValueFunctions.jsonContents("errorCount", Integer.class)))
            .poll(new HttpPollConfig<Integer>(TOTAL_PROCESSING_TIME).vars(includeRuntimeUriVars)
                    .onSuccess(HttpValueFunctions.jsonContents("processingTime", Integer.class)))
            .poll(new HttpPollConfig<Integer>(MAX_PROCESSING_TIME).vars(includeRuntimeUriVars)
                    .onSuccess(HttpValueFunctions.jsonContents("maxTime", Integer.class)))
            .poll(new HttpPollConfig<Long>(BYTES_RECEIVED).vars(includeRuntimeUriVars)
                    // jboss seems to report 0 even if it has received lots of requests; dunno why.
                    .onSuccess(HttpValueFunctions.jsonContents("bytesReceived", Long.class)))
            .poll(new HttpPollConfig<Long>(BYTES_SENT).vars(includeRuntimeUriVars)
                    .onSuccess(HttpValueFunctions.jsonContents("bytesSent", Long.class)))
            .build();//  ww w . j a va2 s .  c  o  m

    connectServiceUp();
}

From source file:com.appenginefan.toolkit.common.PersistentQueue.java

/**
 * Helper: fetches the head of the queue
 * //from   w w w  . j a  va  2  s .c om
 * @param delete
 *          if set to true, delete the head from the store
 * @return the head object or null if it was empty
 */
private T fetch(boolean delete) {
    List<Entry<String, T>> firstElement = Utilities.scanByPrefix(store, prefix, 1);
    if (firstElement.isEmpty()) {
        return null;
    }
    if (delete) {
        store.mutate(firstElement.get(0).getKey(), Functions.constant((T) null));
    }
    return firstElement.get(0).getValue();
}

From source file:zotmc.collect.Conversions.java

public static <E> Function<?, E> constant(E value) {
    return Functions.constant(value);
}

From source file:com.android.tools.idea.npw.importing.ImportUIUtil.java

/**
 * Returns a relative path string to be shown in the UI. Wizard logic
 * operates with VirtualFile's so these paths are only for user. The paths
 * shown are relative to the file system location user specified, showing
 * relative paths will be easier for the user to read.
 *///from w w  w  .j  av  a2  s.  co m
static String getRelativePath(@Nullable VirtualFile baseFile, @Nullable VirtualFile file) {
    if (file == null) {
        return "";
    }
    String path = file.getPath();
    if (baseFile == null) {
        return path;
    } else if (file.equals(baseFile)) {
        return ".";
    } else if (!baseFile.isDirectory()) {
        return getRelativePath(baseFile.getParent(), file);
    } else {
        String basePath = baseFile.getPath();
        if (path.startsWith(basePath + "/")) {
            return path.substring(basePath.length() + 1);
        } else if (file.getFileSystem().equals(baseFile.getFileSystem())) {
            StringBuilder builder = new StringBuilder(basePath.length());
            String prefix = Strings.commonPrefix(path, basePath);
            if (!prefix.endsWith("/")) {
                prefix = prefix.substring(0, prefix.lastIndexOf("/") + 1);
            }
            if (!path.startsWith(basePath)) {
                Iterable<String> segments = Splitter.on("/").split(basePath.substring(prefix.length()));
                Joiner.on("/").appendTo(builder, Iterables.transform(segments, Functions.constant("..")));
                builder.append("/");
            }
            builder.append(path.substring(prefix.length()));
            return builder.toString();
        } else {
            return path;
        }
    }
}

From source file:brooklyn.qa.load.SimulatedNginxControllerImpl.java

@Override
public void connectSensors() {
    boolean simulateEntity = getConfig(SIMULATE_ENTITY);
    boolean simulateExternalMonitoring = getConfig(SIMULATE_EXTERNAL_MONITORING);

    if (!simulateEntity && !simulateExternalMonitoring) {
        super.connectSensors();
        return;//  www . ja v a2s .  c  o m
    }

    // From AbstractController.connectSensors
    if (getUrl() == null) {
        setAttribute(MAIN_URI, URI.create(inferUrl()));
        setAttribute(ROOT_URL, inferUrl());
    }
    addServerPoolMemberTrackingPolicy();

    // From NginxController.connectSensors
    ConfigToAttributes.apply(this);

    if (!simulateExternalMonitoring) {
        // if simulating entity, then simulate work of periodic HTTP request; TODO but not parsing JSON response
        String uriToPoll = (simulateEntity) ? "http://localhost:8081" : getAttribute(MAIN_URI).toString();

        httpFeed = HttpFeed.builder().entity(this).period(getConfig(HTTP_POLL_PERIOD)).baseUri(uriToPoll)
                .poll(new HttpPollConfig<Boolean>(SERVICE_UP).onSuccess(Functions.constant(true))
                        .onFailureOrException(Functions.constant(true)))
                .build();
    }

    functionFeed = FunctionFeed.builder().entity(this).period(getConfig(HTTP_POLL_PERIOD))
            .poll(new FunctionPollConfig<Boolean, Boolean>(SERVICE_UP).callable(new Callable<Boolean>() {
                public Boolean call() {
                    return true;
                }
            })).build();

    // Can guarantee that parent/managementContext has been set
    Group urlMappings = getConfig(URL_MAPPINGS);
    if (urlMappings != null) {
        // Listen to the targets of each url-mapping changing
        subscribeToMembers(urlMappings, UrlMapping.TARGET_ADDRESSES,
                new SensorEventListener<Collection<String>>() {
                    @Override
                    public void onEvent(SensorEvent<Collection<String>> event) {
                        updateNeeded();
                    }
                });

        // Listen to url-mappings being added and removed
        urlMappingsMemberTrackerPolicy = addPolicy(
                PolicySpec.create(UrlMappingsMemberTrackerPolicy.class).configure("group", urlMappings));
    }
}

From source file:brooklyn.entity.messaging.activemq.ActiveMQBrokerImpl.java

@Override
protected void connectSensors() {
    setAttribute(BROKER_URL,/* w w w . ja  v a 2s .  com*/
            String.format("tcp://%s:%d", getAttribute(HOSTNAME), getAttribute(OPEN_WIRE_PORT)));

    String brokerMbeanName = "org.apache.activemq:type=Broker,brokerName=" + getBrokerName();

    jmxFeed = JmxFeed.builder().entity(this).period(500, TimeUnit.MILLISECONDS)
            .pollAttribute(new JmxAttributePollConfig<Boolean>(SERVICE_UP).objectName(brokerMbeanName)
                    .attributeName("BrokerName").onSuccess(Functions.forPredicate(Predicates.notNull()))
                    .onFailureOrException(Functions.constant(false)))
            .build();
}

From source file:org.apache.brooklyn.entity.messaging.activemq.ActiveMQBrokerImpl.java

@Override
protected void connectSensors() {
    sensors().set(BROKER_URL,//ww  w . java 2  s . co m
            String.format("tcp://%s:%d", getAttribute(HOSTNAME), getAttribute(OPEN_WIRE_PORT)));

    String brokerMbeanName = "org.apache.activemq:type=Broker,brokerName=" + getBrokerName();

    jmxFeed = JmxFeed.builder().entity(this).period(500, TimeUnit.MILLISECONDS)
            .pollAttribute(new JmxAttributePollConfig<Boolean>(SERVICE_UP).objectName(brokerMbeanName)
                    .attributeName("BrokerName").onSuccess(Functions.forPredicate(Predicates.notNull()))
                    .onFailureOrException(Functions.constant(false)).suppressDuplicates(true))
            .build();
}

From source file:org.apache.brooklyn.entity.messaging.kafka.KafkaBrokerImpl.java

@Override
protected void connectSensors() {
    connectServiceUpIsRunning();/*from w  w  w  . jav  a 2 s. c om*/
    boolean retrieveUsageMetrics = getConfig(RETRIEVE_USAGE_METRICS);

    if (((KafkaBrokerDriver) getDriver()).isJmxEnabled()) {
        jmxFeed = JmxFeed.builder().entity(this).period(500, TimeUnit.MILLISECONDS)
                .pollAttribute(new JmxAttributePollConfig<Long>(FETCH_REQUEST_COUNT)
                        .objectName(SOCKET_SERVER_STATS_MBEAN).attributeName("NumFetchRequests")
                        .onException(Functions.constant(-1l)).enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Long>(TOTAL_FETCH_TIME)
                        .objectName(SOCKET_SERVER_STATS_MBEAN).attributeName("TotalFetchRequestMs")
                        .onException(Functions.constant(-1l)).enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Double>(MAX_FETCH_TIME)
                        .objectName(SOCKET_SERVER_STATS_MBEAN).attributeName("MaxFetchRequestMs")
                        .onException(Functions.constant(-1.0d)).enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Long>(PRODUCE_REQUEST_COUNT)
                        .objectName(SOCKET_SERVER_STATS_MBEAN).attributeName("NumProduceRequests")
                        .onException(Functions.constant(-1l)).enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Long>(TOTAL_PRODUCE_TIME)
                        .objectName(SOCKET_SERVER_STATS_MBEAN).attributeName("TotalProduceRequestMs")
                        .onException(Functions.constant(-1l)).enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Double>(MAX_PRODUCE_TIME)
                        .objectName(SOCKET_SERVER_STATS_MBEAN).attributeName("MaxProduceRequestMs")
                        .onException(Functions.constant(-1.0d)).enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Long>(BYTES_RECEIVED)
                        .objectName(SOCKET_SERVER_STATS_MBEAN).attributeName("TotalBytesRead")
                        .onException(Functions.constant(-1l)).enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Long>(BYTES_SENT)
                        .objectName(SOCKET_SERVER_STATS_MBEAN).attributeName("TotalBytesWritten")
                        .onException(Functions.constant(-1l)).enabled(retrieveUsageMetrics))
                .build();
    }

    setBrokerUrl();
}