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:io.cloudsoft.marklogic.nodes.MarkLogicNodeImpl.java

/**
 * Sets up the polling of sensors./*from  w  ww  . j av  a 2s  .c o  m*/
 */
@Override
protected void connectSensors() {
    super.connectSensors();
    serviceUp = FunctionFeed.builder().entity(this).period(5000)
            .poll(new FunctionPollConfig<Boolean, Boolean>(SERVICE_UP)
                    .onException(Functions.constant(Boolean.FALSE)).callable(new Callable<Boolean>() {
                        public Boolean call() {
                            return getDriver().isRunning();
                        }
                    }))
            .build();
}

From source file:brooklyn.event.basic.DependentConfiguration.java

public static <T> Task<T> valueWhenAttributeReady(Entity source, AttributeSensor<T> sensor, T value) {
    return DependentConfiguration.<T, T>attributePostProcessedWhenReady(source, sensor,
            GroovyJavaMethods.truthPredicate(), Functions.constant(value));
}

From source file:org.terasology.rendering.nui.layers.mainMenu.settings.PlayerSettingsScreen.java

@Override
public void initialise() {
    setAnimationSystem(MenuAnimationSystems.createDefaultSwipeAnimation());

    storageServiceStatus = find("storageServiceStatus", UILabel.class);
    storageServiceAction = find("storageServiceAction", UIButton.class);
    updateStorageServiceStatus();//  w ww. j a v  a2  s. co  m

    nametext = find("playername", UIText.class);
    if (nametext != null) {
        nametext.setTooltipDelay(0);
        nametext.bindTooltipString(new ReadOnlyBinding<String>() {
            @Override
            public String get() {
                return validateScreen();
            }
        });
    }
    img = find("image", UIImage.class);
    if (img != null) {
        ResourceUrn uri = TextureUtil.getTextureUriForColor(Color.WHITE);
        Texture tex = Assets.get(uri, Texture.class).get();
        img.setImage(tex);
    }

    slider = find("tone", UISlider.class);
    if (slider != null) {
        slider.setIncrement(0.01f);
        Function<Object, String> constant = Functions.constant("  "); // ensure a certain width
        slider.setLabelFunction(constant);
    }

    heightSlider = find("height", UISlider.class);
    if (heightSlider != null) {
        heightSlider.setMinimum(1.5f);
        heightSlider.setIncrement(0.1f);
        heightSlider.setRange(0.5f);
        heightSlider.setPrecision(1);
    }

    eyeHeightSlider = find("eye-height", UISlider.class);
    if (eyeHeightSlider != null) {
        eyeHeightSlider.setMinimum(0.5f);
        eyeHeightSlider.setIncrement(0.1f);
        eyeHeightSlider.setRange(1f);
        eyeHeightSlider.setPrecision(1);
    }

    language = find("language", UIDropdownScrollable.class);
    if (language != null) {
        SimpleUri menuUri = new SimpleUri("engine:menu");
        TranslationProject menuProject = translationSystem.getProject(menuUri);
        List<Locale> locales = new ArrayList<>(menuProject.getAvailableLocales());
        for (Locale languageExcluded : languagesExcluded) {
            locales.remove(languageExcluded);
        }
        Collections.sort(locales, ((Object o1, Object o2) -> (o1.toString().compareTo(o2.toString()))));
        language.setOptions(Lists.newArrayList(locales));
        language.setVisibleOptions(5); // Set maximum number of options visible for scrolling
        language.setOptionRenderer(new LocaleRenderer(translationSystem));
    }

    WidgetUtil.trySubscribe(this, "close", button -> triggerBackAnimation());

    WidgetUtil.trySubscribe(this, "storageServiceAction", widget -> {
        if (storageService.getStatus() == StorageServiceWorkerStatus.LOGGED_IN) {
            ThreeButtonPopup logoutPopup = getManager().pushScreen(ThreeButtonPopup.ASSET_URI,
                    ThreeButtonPopup.class);
            logoutPopup.setMessage(translationSystem.translate("${engine:menu#storage-service-log-out}"),
                    translationSystem.translate("${engine:menu#storage-service-log-out-popup}"));
            logoutPopup.setLeftButton(translationSystem.translate("${engine:menu#dialog-yes}"),
                    () -> storageService.logout(true));
            logoutPopup.setCenterButton(translationSystem.translate("${engine:menu#dialog-no}"),
                    () -> storageService.logout(false));
            logoutPopup.setRightButton(translationSystem.translate("${engine:menu#dialog-cancel}"), () -> {
            });
        } else if (storageService.getStatus() == StorageServiceWorkerStatus.LOGGED_OUT) {
            getManager().pushScreen(StorageServiceLoginPopup.ASSET_URI, StorageServiceLoginPopup.class);
        }
    });

    UIButton okButton = find("ok", UIButton.class);
    if (okButton != null) {
        okButton.subscribe(button -> {
            savePlayerSettings();
            triggerBackAnimation();
        });
        okButton.bindEnabled(new ReadOnlyBinding<Boolean>() {
            @Override
            public Boolean get() {
                return Strings.isNullOrEmpty(validateScreen());
            }
        });
        okButton.setTooltipDelay(0);
        okButton.bindTooltipString(new ReadOnlyBinding<String>() {
            @Override
            public String get() {
                return validateScreen();
            }
        });
    }
}

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

public F setOnException(T val) {
    return onException(Functions.constant(val));
}

From source file:org.apache.brooklyn.entity.cloudfoundry.webapp.java.JavaCloudFoundryPaasWebAppImpl.java

private void connectServiceRequestPerSecondSensor() {
    requestPerSecondLatencyFeed = FunctionFeed.builder().entity(this).period(Duration.seconds(1))
            .poll(new FunctionPollConfig<Double, Double>(REQUEST_PER_SECOND)
                    .onException(Functions.constant(0.0)).callable(new Callable<Double>() {
                        public Double call() {
                            Double currentRequestPerSecond = getAttribute(SERVER_REQUESTS) - lastTotalRequest;
                            if (currentRequestPerSecond >= 0) {
                                lastTotalRequest = getAttribute(SERVER_REQUESTS);
                                return currentRequestPerSecond;
                            } else {
                                return getAttribute(SERVER_REQUESTS);
                            }//from  w  ww.j  a va  2 s  .  c  o  m
                        }
                    }))
            .build();
}

From source file:com.palantir.atlasdb.keyvalue.impl.Cells.java

public static <K, V> Map<K, V> constantValueMap(Set<K> keys, V v) {
    return Maps.asMap(keys, Functions.constant(v));
}

From source file:org.apache.brooklyn.util.repeat.Repeater.java

/**
 * Set how long to wait between loop iterations, as a constant function in {@link #delayOnIteration}
 *///from  w  ww.  jav a2 s . c o  m
public Repeater every(Duration duration) {
    Preconditions.checkNotNull(duration, "duration must not be null");
    Preconditions.checkArgument(duration.toMilliseconds() > 0, "period must be positive: %s", duration);
    return delayOnIteration(Functions.constant(duration));
}

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

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

From source file:io.brooklyn.ambari.server.AmbariServerImpl.java

@Override
protected void connectSensors() {
    super.connectSensors();
    connectServiceUpIsRunning();// w w w. jav a 2s.c  o m

    HostAndPort hp = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, getAttribute(HTTP_PORT));

    ambariUri = String.format("http://%s:%d", hp.getHostText(), hp.getPort());

    setAttribute(Attributes.MAIN_URI, URI.create(ambariUri));

    sensors().set(AmbariServer.USERNAME, USERNAME);
    usernamePasswordCredentials = new UsernamePasswordCredentials(USERNAME,
            getAttribute(AmbariServer.PASSWORD) == null ? INITIAL_PASSWORD
                    : getAttribute(AmbariServer.PASSWORD));

    restAdapter = new RestAdapter.Builder().setEndpoint(ambariUri)
            .setRequestInterceptor(new AmbariRequestInterceptor(usernamePasswordCredentials))
            .setLogLevel(RestAdapter.LogLevel.FULL).build();

    serviceUpHttpFeed = HttpFeed.builder().entity(this).period(500, TimeUnit.MILLISECONDS).baseUri(ambariUri)
            .poll(new HttpPollConfig<Boolean>(URL_REACHABLE)
                    .onSuccess(HttpValueFunctions.responseCodeEquals(200))
                    .onFailureOrException(Functions.constant(false)))
            .build();

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

    connectAuthenticatedSensors();
}

From source file:org.apache.brooklyn.core.sensor.windows.WinRmCommandSensor.java

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

    if (LOG.isDebugEnabled()) {
        LOG.debug("Adding WinRM sensor {} to {}", name, entity);
    }/*from  w ww.ja v  a  2s. c o  m*/

    final Boolean suppressDuplicates = EntityInitializers.resolve(params, SUPPRESS_DUPLICATES);
    final Duration logWarningGraceTimeOnStartup = EntityInitializers.resolve(params,
            LOG_WARNING_GRACE_TIME_ON_STARTUP);
    final Duration logWarningGraceTime = EntityInitializers.resolve(params, LOG_WARNING_GRACE_TIME);

    Supplier<Map<String, String>> envSupplier = new Supplier<Map<String, String>>() {
        @SuppressWarnings("serial")
        @Override
        public Map<String, String> get() {
            Map<String, String> env = MutableMap.copyOf(entity.getConfig(SENSOR_ENVIRONMENT));

            // Add the shell environment entries from our configuration
            if (sensorEnv != null)
                env.putAll(sensorEnv);

            // Try to resolve the configuration in the env Map
            try {
                env = Tasks.resolveDeepValueExactly(env, new TypeToken<Map<String, String>>() {
                }, ((EntityInternal) entity).getExecutionContext());
            } catch (InterruptedException | ExecutionException e) {
                Exceptions.propagateIfFatal(e);
            }

            // Convert the environment into strings with the serializer
            ShellEnvironmentSerializer serializer = new ShellEnvironmentSerializer(
                    ((EntityInternal) entity).getManagementContext());
            return serializer.serialize(env);
        }
    };

    Supplier<String> commandSupplier = new Supplier<String>() {
        @Override
        public String get() {
            return makeCommandExecutingInDirectory(command, executionDir, entity);
        }
    };

    CommandPollConfig<T> pollConfig = new CommandPollConfig<T>(sensor).period(period).env(envSupplier)
            .command(commandSupplier).suppressDuplicates(Boolean.TRUE.equals(suppressDuplicates))
            .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(Strings.trimEnd(input), (Class<T>) sensor.getType());
                }
            }, SshValueFunctions.stdout())).logWarningGraceTimeOnStartup(logWarningGraceTimeOnStartup)
            .logWarningGraceTime(logWarningGraceTime);

    CmdFeed feed = CmdFeed.builder().entity(entity).onlyIfServiceUp().poll(pollConfig).build();

    entity.addFeed(feed);
}