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.cloud.CloudMachineImpl.java

protected void connectSensors() {
    sensorFeed = FunctionFeed.builder().entity(this).period(Duration.TEN_SECONDS)
            .poll(new FunctionPollConfig<Boolean, Boolean>(CloudMachine.SSH_AVAILABLE)
                    .callable(new Callable<Boolean>() {
                        @Override
                        public Boolean call() throws Exception {
                            return getSshMachine().isSshable();
                        }/*  w  w  w . j  av a 2s  .  c om*/
                    }))
            .poll(new FunctionPollConfig<String, Double>(CloudMachine.CPU_USAGE)
                    .callable(new Callable<String>() {
                        @Override
                        public String call() throws Exception {
                            ProcessTaskWrapper<Integer> task = SshEffectorTasks.ssh(ImmutableList.of("uptime"))
                                    .machine(getSshMachine()).requiringExitCodeZero().summary("cpuUsage")
                                    .newTask();
                            DynamicTasks.queueIfPossible(task).orSubmitAsync(CloudMachineImpl.this);
                            return task.block().getStdout();
                        }
                    }).onFailureOrException(Functions.constant(0d)).onSuccess(new Function<String, Double>() {
                        @Override
                        public Double apply(@Nullable String input) {
                            log.info("Uptime: {}", input);
                            // TODO parse uptime output
                            return 1d;
                        }
                    }))
            .build();
}

From source file:org.apache.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;/*from  ww  w  . j  a  v  a  2s.c  o  m*/
    }

    // From AbstractController.connectSensors
    if (getUrl() == null) {
        sensors().set(MAIN_URI, URI.create(inferUrl()));
        sensors().set(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
        subscriptions().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 = policies()
                .add(PolicySpec.create(UrlMappingsMemberTrackerPolicy.class).configure("group", urlMappings));
    }
}

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

@Override
protected void connectSensors() {
    connectServiceUpIsRunning();/*w  ww  .  j a  v  a2s.com*/

    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)))
                .pollAttribute(
                        new JmxAttributePollConfig<Long>(TOTAL_FETCH_TIME).objectName(SOCKET_SERVER_STATS_MBEAN)
                                .attributeName("TotalFetchRequestMs").onException(Functions.constant(-1l)))
                .pollAttribute(
                        new JmxAttributePollConfig<Double>(MAX_FETCH_TIME).objectName(SOCKET_SERVER_STATS_MBEAN)
                                .attributeName("MaxFetchRequestMs").onException(Functions.constant(-1.0d)))
                .pollAttribute(new JmxAttributePollConfig<Long>(PRODUCE_REQUEST_COUNT)
                        .objectName(SOCKET_SERVER_STATS_MBEAN).attributeName("NumProduceRequests")
                        .onException(Functions.constant(-1l)))
                .pollAttribute(new JmxAttributePollConfig<Long>(TOTAL_PRODUCE_TIME)
                        .objectName(SOCKET_SERVER_STATS_MBEAN).attributeName("TotalProduceRequestMs")
                        .onException(Functions.constant(-1l)))
                .pollAttribute(new JmxAttributePollConfig<Double>(MAX_PRODUCE_TIME)
                        .objectName(SOCKET_SERVER_STATS_MBEAN).attributeName("MaxProduceRequestMs")
                        .onException(Functions.constant(-1.0d)))
                .pollAttribute(
                        new JmxAttributePollConfig<Long>(BYTES_RECEIVED).objectName(SOCKET_SERVER_STATS_MBEAN)
                                .attributeName("TotalBytesRead").onException(Functions.constant(-1l)))
                .pollAttribute(
                        new JmxAttributePollConfig<Long>(BYTES_SENT).objectName(SOCKET_SERVER_STATS_MBEAN)
                                .attributeName("TotalBytesWritten").onException(Functions.constant(-1l)))
                .build();
    }

    setBrokerUrl();
}

From source file:com.android.builder.files.IncrementalRelativeFileSets.java

/**
 * Reads a zip file and adds all files in the file in a new incremental relative set. The
 * status of each file is set to {@code status}.
 *
 * @param zip the zip file to read, must be a valid, existing zip file
 * @param status the status to set the files to
 * @return the file set/*  w  w  w.j  a  va2s.  co  m*/
 * @throws IOException failed to read the zip file
 */
@NonNull
public static ImmutableMap<RelativeFile, FileStatus> fromZip(@NonNull File zip, FileStatus status)
        throws IOException {
    Preconditions.checkArgument(zip.isFile(), "!zip.isFile()");

    Set<RelativeFile> files = Sets.newHashSet();

    Closer closer = Closer.create();
    try {
        ZFile zipReader = closer.register(new ZFile(zip));
        for (StoredEntry entry : zipReader.entries()) {
            if (entry.getType() == StoredEntryType.FILE) {
                File file = new File(zip,
                        FileUtils.toSystemDependentPath(entry.getCentralDirectoryHeader().getName()));
                files.add(new RelativeFile(zip, file));
            }
        }
    } catch (Throwable t) {
        throw closer.rethrow(t, IOException.class);
    } finally {
        closer.close();
    }

    Map<RelativeFile, FileStatus> map = Maps.asMap(files, Functions.constant(status));
    return ImmutableMap.copyOf(map);
}

From source file:com.eucalyptus.autoscaling.common.internal.tags.Tag.java

@SuppressWarnings("unchecked")
public static Tag withOwner(@Nonnull final OwnerFullName ownerFullName) {
    Preconditions.checkNotNull(ownerFullName, "ownerFullName");
    return new Tag(null, Functions.constant(null), ownerFullName, null, null, null);
}

From source file:brooklyn.entity.software.ssh.SshCommandSensor.java

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

    if (LOG.isDebugEnabled()) {
        LOG.debug("Adding SSH sensor {} to {}", name, entity);
    }/*from w  w  w  . j  a  va  2 s.co  m*/

    Supplier<Map<String, String>> envSupplier = new Supplier<Map<String, String>>() {
        @Override
        public Map<String, String> get() {
            return MutableMap.copyOf(Strings.toStringMap(entity.getConfig(SoftwareProcess.SHELL_ENVIRONMENT)));
        }
    };

    Supplier<String> commandSupplier = new Supplier<String>() {
        @Override
        public String get() {
            String finalCommand = command;
            String runDir = entity.getAttribute(SoftwareProcess.RUN_DIR);
            if (runDir != null) {
                finalCommand = "cd '" + runDir + "' && " + finalCommand;
            }
            return finalCommand;
        }
    };

    SshPollConfig<T> pollConfig = new SshPollConfig<T>(sensor).period(period).env(envSupplier)
            .command(commandSupplier).checkSuccess(SshValueFunctions.exitStatusEquals(0))
            .onFailureOrException(Functions.constant((T) null))
            .onSuccess(Functions.compose(new Function<String, T>() {
                @Override
                public T apply(String input) {
                    return TypeCoercions.coerce(input, getType(type));
                }
            }, SshValueFunctions.stdout()));

    SshFeed.builder().entity(entity).onlyIfServiceUp().poll(pollConfig).build();
}

From source file:org.apache.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());
    sensors().set(MANAGEMENT_URL, managementUri);

    if (isHttpMonitoringEnabled()) {
        log.debug("JBoss sensors for " + this + " reading from " + managementUri);
        Map<String, String> includeRuntimeUriVars = ImmutableMap.of("include-runtime", "true");
        boolean retrieveUsageMetrics = getConfig(RETRIEVE_USAGE_METRICS);

        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()).suppressDuplicates(true))
                .poll(new HttpPollConfig<Boolean>(MANAGEMENT_URL_UP)
                        .onSuccess(HttpValueFunctions.responseCodeEquals(200))
                        .onFailureOrException(Functions.constant(false)).suppressDuplicates(true))
                .poll(new HttpPollConfig<Integer>(REQUEST_COUNT).vars(includeRuntimeUriVars)
                        .onSuccess(HttpValueFunctions.jsonContents("requestCount", Integer.class))
                        .onFailureOrException(EntityFunctions.attribute(this, REQUEST_COUNT))
                        .enabled(retrieveUsageMetrics))
                .poll(new HttpPollConfig<Integer>(ERROR_COUNT).vars(includeRuntimeUriVars)
                        .onSuccess(HttpValueFunctions.jsonContents("errorCount", Integer.class))
                        .enabled(retrieveUsageMetrics))
                .poll(new HttpPollConfig<Integer>(TOTAL_PROCESSING_TIME).vars(includeRuntimeUriVars)
                        .onSuccess(HttpValueFunctions.jsonContents("processingTime", Integer.class))
                        .enabled(retrieveUsageMetrics))
                .poll(new HttpPollConfig<Integer>(MAX_PROCESSING_TIME).vars(includeRuntimeUriVars)
                        .onSuccess(HttpValueFunctions.jsonContents("maxTime", Integer.class))
                        .enabled(retrieveUsageMetrics))
                .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))
                        .enabled(retrieveUsageMetrics))
                .poll(new HttpPollConfig<Long>(BYTES_SENT).vars(includeRuntimeUriVars)
                        .onSuccess(HttpValueFunctions.jsonContents("bytesSent", Long.class))
                        .enabled(retrieveUsageMetrics))
                .build();//from   ww w . ja v  a 2s. c o  m

        enrichers().add(Enrichers.builder().updatingMap(Attributes.SERVICE_NOT_UP_INDICATORS)
                .from(MANAGEMENT_URL_UP)
                .computing(Functionals.ifNotEquals(true).value("Management URL not reachable")).build());
    }

    connectServiceUpIsRunning();
}

From source file:com.qcadoo.mes.deviationCausesReporting.listeners.DeviationsReportGeneratorViewListeners.java

private DateTime extractDateTo(final ViewDefinitionState view) {

    return FluentOptional.wrap(getComponentValue(view, DeviationReportGeneratorViewReferences.DATE_TO))
            .flatMap(new Function<String, Optional<DateTime>>() {

                @Override/* w ww.ja  v a2  s.  co m*/
                public Optional<DateTime> apply(final String dateFromComponentValue) {
                    return DateUtils.tryParse(dateFromComponentValue).fold(
                            Functions.constant(Optional.<DateTime>absent()),
                            Functions.<Optional<DateTime>>identity());
                }
            }).or(DeviationsReportCriteria.getDefaultDateTo());
}

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

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

    httpFeed = 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]))))
            .build();

    WebAppServiceMethods.connectWebAppServerPolicies(this);
}

From source file:brooklyn.entity.nosql.elasticsearch.ElasticSearchNodeImpl.java

@Override
protected void connectSensors() {
    super.connectSensors();
    Integer rawPort = getAttribute(HTTP_PORT);
    checkNotNull(rawPort, "HTTP_PORT sensors not set for %s; is an acceptable port available?", this);
    HostAndPort hp = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, rawPort);
    Function<Maybe<JsonElement>, String> getNodeId = new Function<Maybe<JsonElement>, String>() {
        @Override/*  w  w w.j  av a 2  s .co m*/
        public String apply(Maybe<JsonElement> input) {
            if (input.isAbsent()) {
                return null;
            }
            return input.get().getAsJsonObject().entrySet().iterator().next().getKey();
        }
    };
    httpFeed = HttpFeed.builder().entity(this).period(1000)
            .baseUri(String.format("http://%s:%s/_nodes/_local/stats", hp.getHostText(), hp.getPort()))
            .poll(new HttpPollConfig<Boolean>(SERVICE_UP).onSuccess(HttpValueFunctions.responseCodeEquals(200))
                    .onFailureOrException(Functions.constant(false)))
            .poll(new HttpPollConfig<String>(NODE_ID)
                    .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(),
                            MaybeFunctions.<JsonElement>wrap(), JsonFunctions.walkM("nodes"), getNodeId))
                    .onFailureOrException(Functions.constant("")))
            .poll(getSensorFromNodeStat(NODE_NAME, "name"))
            .poll(getSensorFromNodeStat(DOCUMENT_COUNT, "indices", "docs", "count"))
            .poll(getSensorFromNodeStat(STORE_BYTES, "indices", "store", "size_in_bytes"))
            .poll(getSensorFromNodeStat(GET_TOTAL, "indices", "get", "total"))
            .poll(getSensorFromNodeStat(GET_TIME_IN_MILLIS, "indices", "get", "time_in_millis"))
            .poll(getSensorFromNodeStat(SEARCH_QUERY_TOTAL, "indices", "search", "query_total"))
            .poll(getSensorFromNodeStat(SEARCH_QUERY_TIME_IN_MILLIS, "indices", "search",
                    "query_time_in_millis"))
            .poll(new HttpPollConfig<String>(CLUSTER_NAME)
                    .onSuccess(HttpValueFunctions.jsonContents("cluster_name", String.class)))
            .build();
}