Example usage for com.google.common.base Optional or

List of usage examples for com.google.common.base Optional or

Introduction

In this page you can find the example usage for com.google.common.base Optional or.

Prototype

@Beta
public abstract T or(Supplier<? extends T> supplier);

Source Link

Document

Returns the contained instance if it is present; supplier.get() otherwise.

Usage

From source file:com.github.nethad.clustermeister.provisioning.ec2.AmazonInstanceManager.java

private void openReverseChannel(NodeMetadata instanceMetadata, AmazonNodeConfiguration nodeConfig) {
    reverseTunnelMonitor.enter();//from w w w .  j  a  v a2s. c  o  m
    try {
        if (!instanceToJPPFReverseTunnel.containsKey(instanceMetadata.getId())) {
            SSHClientImpl sshClientForReverseTunnel = new SSHClientImpl();
            Credentials credentials = nodeConfig.getCredentials().get();
            try {
                if (credentials instanceof KeyPairCredentials) {
                    KeyPairCredentials keypair = credentials.as(KeyPairCredentials.class);
                    sshClientForReverseTunnel.setCredentials(keypair);
                    String publicIp = Iterables.getFirst(instanceMetadata.getPublicAddresses(), null);
                    sshClientForReverseTunnel.connect(publicIp, instanceMetadata.getLoginPort());
                    SocksTunnel socksJPPFReverseTunnel = sshClientForReverseTunnel.getNewSocksReverseTunnel();
                    instanceToJPPFReverseTunnel.put(instanceMetadata.getId(), socksJPPFReverseTunnel);
                    socksJPPFReverseTunnel.openTunnel(JPPFConstants.DEFAULT_SERVER_PORT, "localhost",
                            JPPFConstants.DEFAULT_SERVER_PORT);
                    //for remote logging
                    Optional<Boolean> remoteLoggingActivataed = nodeConfig.isRemoteLoggingActivataed();
                    if (remoteLoggingActivataed.or(Boolean.FALSE)) {
                        SocksTunnel socksLoggingReverseTunnel = sshClientForReverseTunnel
                                .getNewSocksReverseTunnel();
                        instanceToLoggingReverseTunnel.put(instanceMetadata.getId(), socksLoggingReverseTunnel);
                        Integer remoteLoggingPort = nodeConfig.getRemoteLoggingPort().or(52321);
                        socksLoggingReverseTunnel.openTunnel(remoteLoggingPort, "localhost", remoteLoggingPort);
                    }
                } else {
                    //TODO: add support for password credentials
                    throw new IllegalStateException(String.format("Unsupported Credentials: %s.", credentials));
                }
            } catch (Exception ex) {
                logger.warn("Could not open reverse channel.", ex);
            }
        }
    } finally {
        reverseTunnelMonitor.leave();
    }
}

From source file:com.facebook.presto.raptor.storage.OrcRowSink.java

public OrcRowSink(List<Long> columnIds, List<StorageType> columnTypes, Optional<Long> sampleWeightColumnId,
        File target) {//from w  ww.j ava  2 s .  com
    checkArgument(columnIds.size() == columnTypes.size(), "ids and types mismatch");
    checkArgument(isUnique(columnIds), "ids must be unique");

    fieldCount = columnIds.size();
    sampleWeightField = columnIds.indexOf(sampleWeightColumnId.or(-1L));

    Iterable<String> hiveTypeNames = ImmutableList.copyOf(transform(columnTypes, hiveTypeName()));
    List<String> columnNames = ImmutableList.copyOf(transform(columnIds, toStringFunction()));

    Properties properties = new Properties();
    properties.setProperty(META_TABLE_COLUMNS, Joiner.on(',').join(columnNames));
    properties.setProperty(META_TABLE_COLUMN_TYPES, Joiner.on(':').join(hiveTypeNames));

    serializer = createSerializer(JOB_CONF, properties);
    recordWriter = createRecordWriter(new Path(target.toURI()), JOB_CONF);

    tableInspector = getStandardStructObjectInspector(columnNames, getJavaObjectInspectors(columnTypes));
    structFields = ImmutableList.copyOf(tableInspector.getAllStructFieldRefs());
    row = tableInspector.create();
}

From source file:brooklyn.event.feed.windows.WindowsPerformanceCounterFeed.java

@Override
protected void preStart() {
    Set<WindowsPerformanceCounterPollConfig<?>> polls = getConfig(POLLS);

    long minPeriod = Integer.MAX_VALUE;
    SortedSet<String> performanceCounterNames = Sets.newTreeSet();
    for (WindowsPerformanceCounterPollConfig<?> config : polls) {
        minPeriod = Math.min(minPeriod, config.getPeriod());
        performanceCounterNames.add(config.getPerformanceCounterName());
    }/*www  .j a v a  2s  .  c o m*/

    SshMachineLocation machine = EffectorTasks.getSshMachine(getEntity());
    Iterable<String> allParams = ImmutableList.<String>builder().add("typeperf")
            .addAll(Iterables.transform(performanceCounterNames, QuoteStringFunction.INSTANCE)).add("-sc")
            .add("1").build();
    String command = JOINER_ON_SPACE.join(allParams);
    log.debug("Windows performance counter poll command will be: {}", command);

    final ProcessTaskFactory<Integer> taskFactory = SshTasks.newSshExecTaskFactory(machine, command)
            .allowingNonZeroExitCode().runAsCommand();

    final Callable<SshPollValue> queryForCounterValues = new Callable<SshPollValue>() {
        public SshPollValue call() throws Exception {
            ProcessTaskWrapper<Integer> taskWrapper = taskFactory.newTask();
            final ExecutionContext executionContext = ((EntityInternal) entity).getManagementSupport()
                    .getExecutionContext();
            executionContext.submit(taskWrapper);
            taskWrapper.block();
            Optional<Integer> exitCode = Optional.fromNullable(taskWrapper.getExitCode());
            return new SshPollValue(null, exitCode.or(-1), taskWrapper.getStdout(), taskWrapper.getStderr());
        }
    };

    getPoller().scheduleAtFixedRate(
            new CallInEntityExecutionContext<SshPollValue>(entity, queryForCounterValues),
            new SendPerfCountersToSensors(entity, polls), minPeriod);
}

From source file:com.pinterest.teletraan.resource.EnvCapacities.java

@PUT
public void update(@PathParam("envName") String envName, @PathParam("stageName") String stageName,
        @QueryParam("capacityType") Optional<CapacityType> capacityType, @NotEmpty List<String> names,
        @Context SecurityContext sc) throws Exception {
    EnvironBean envBean = Utils.getEnvStage(environDAO, envName, stageName);
    authorizer.authorize(sc, new Resource(envBean.getEnv_name(), Resource.Type.ENV), Role.OPERATOR);
    String operator = sc.getUserPrincipal().getName();
    if (capacityType.or(CapacityType.GROUP) == CapacityType.GROUP) {
        environHandler.updateGroups(envBean, names, operator);
        configHistoryHandler.updateConfigHistory(envBean.getEnv_id(), Constants.TYPE_ENV_GROUP_CAPACITY, names,
                operator);/*from www. ja v a  2 s.  c o  m*/
        configHistoryHandler.updateChangeFeed(Constants.CONFIG_TYPE_ENV, envBean.getEnv_id(),
                Constants.TYPE_ENV_GROUP_CAPACITY, operator);
    } else {
        environHandler.updateHosts(envBean, names, operator);
        configHistoryHandler.updateConfigHistory(envBean.getEnv_id(), Constants.TYPE_ENV_HOST_CAPACITY, names,
                operator);
        configHistoryHandler.updateChangeFeed(Constants.CONFIG_TYPE_ENV, envBean.getEnv_id(),
                Constants.TYPE_ENV_HOST_CAPACITY, operator);
    }
    LOG.info("Successfully updated env {}/{} capacity config as {} by {}.", envName, stageName, names,
            operator);
}

From source file:com.jivesoftware.os.miru.cluster.MiruReplicaSetDirector.java

public void moveReplica(MiruTenantId tenantId, MiruPartitionId partitionId, Optional<MiruHost> fromHost,
        MiruHost toHost) throws Exception {
    MiruReplicaHosts replicaHosts = replicas(tenantId, partitionId);

    List<MiruHost> hosts = new ArrayList<>(replicaHosts.replicaHosts);
    if (fromHost.isPresent() && !hosts.isEmpty()) {
        // list is small enough that direct removal is better than copying from intermediate set
        hosts.remove(fromHost.or(hosts.get(0)));
    }/*from w  w  w.j av a  2s.c o  m*/
    hosts.add(toHost);

    for (MiruHost host : hosts) {
        elect(host, tenantId, partitionId, Long.MAX_VALUE - orderIdProvider.nextId());
    }
}

From source file:com.viadeo.kasper.api.context.Context.java

/**
 * @return the version of the context/*w  ww . j  a v  a2 s  . co  m*/
 */
public Long getVersion() {
    Optional<Long> version = getGenericProperty(VERSION);
    return version.or(0L);
}

From source file:com.pinterest.teletraan.resource.EnvCapacities.java

@POST
public void add(@PathParam("envName") String envName, @PathParam("stageName") String stageName,
        @QueryParam("capacityType") Optional<CapacityType> capacityType, @NotEmpty String name,
        @Context SecurityContext sc) throws Exception {
    EnvironBean envBean = Utils.getEnvStage(environDAO, envName, stageName);
    authorizer.authorize(sc, new Resource(envBean.getEnv_name(), Resource.Type.ENV), Role.OPERATOR);
    String operator = sc.getUserPrincipal().getName();
    name = name.replaceAll("\"", "");
    if (capacityType.or(CapacityType.GROUP) == CapacityType.GROUP) {
        groupDAO.addGroupCapacity(envBean.getEnv_id(), name);
    } else {/*  w ww  . j  ava  2  s .  co m*/
        groupDAO.addHostCapacity(envBean.getEnv_id(), name);
    }
    LOG.info("Successfully added {} to env {}/{} capacity config by {}.", name, envName, stageName, operator);
}

From source file:com.pinterest.teletraan.resource.Groups.java

@PUT
@Path("/{groupName: [a-zA-Z0-9\\-_]+}/instances")
public List<String> launchNewInstances(@Context SecurityContext sc, @PathParam("groupName") String groupName,
        @QueryParam("instanceCount") Optional<Integer> instanceCnt,
        @NotEmpty @QueryParam("subnet") String subnet) throws Exception {
    Utils.authorizeGroup(environDAO, groupName, sc, authorizer, Role.OPERATOR);
    String operator = sc.getUserPrincipal().getName();
    List<String> instanceIds = provisionHandler.launchNewInstances(groupName, instanceCnt.or(1), subnet,
            operator);//from   ww  w  . j a  v  a  2s . c o  m
    if (!instanceIds.isEmpty()) {
        String configChange = String.format("%s", instanceIds);
        configHistoryHandler.updateConfigHistory(groupName, Constants.TYPE_HOST_LAUNCH, configChange, operator);
    }
    return instanceIds;
}

From source file:gobblin.runtime.spec_catalog.FlowCatalog.java

public FlowCatalog(Config config, Optional<Logger> log, Optional<MetricContext> parentMetricContext,
        boolean instrumentationEnabled) {
    this.log = log.isPresent() ? log.get() : LoggerFactory.getLogger(getClass());
    this.listeners = new SpecCatalogListenersList(log);
    if (instrumentationEnabled) {
        MetricContext realParentCtx = parentMetricContext
                .or(Instrumented.getMetricContext(new gobblin.configuration.State(), getClass()));
        this.metricContext = realParentCtx.childBuilder(FlowCatalog.class.getSimpleName()).build();
        this.metrics = new StandardMetrics(this);
    } else {/*w  w  w .ja v  a 2s. c  o m*/
        this.metricContext = null;
        this.metrics = null;
    }

    this.aliasResolver = new ClassAliasResolver<>(SpecStore.class);
    try {
        Config newConfig = config;
        if (config.hasPath(ConfigurationKeys.FLOWSPEC_STORE_DIR_KEY)) {
            newConfig = config.withValue(ConfigurationKeys.SPECSTORE_FS_DIR_KEY,
                    config.getValue(ConfigurationKeys.FLOWSPEC_STORE_DIR_KEY));
        }
        String specStoreClassName = DEFAULT_FLOWSPEC_STORE_CLASS;
        if (config.hasPath(ConfigurationKeys.FLOWSPEC_STORE_CLASS_KEY)) {
            specStoreClassName = config.getString(ConfigurationKeys.FLOWSPEC_STORE_CLASS_KEY);
        }
        this.log.info("Using audit sink class name/alias " + specStoreClassName);
        this.specStore = (SpecStore) ConstructorUtils.invokeConstructor(
                Class.forName(this.aliasResolver.resolve(specStoreClassName)), newConfig, this);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
            | ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}

From source file:gobblin.runtime.spec_catalog.TopologyCatalog.java

public TopologyCatalog(Config config, Optional<Logger> log, Optional<MetricContext> parentMetricContext,
        boolean instrumentationEnabled) {
    this.log = log.isPresent() ? log.get() : LoggerFactory.getLogger(getClass());
    this.listeners = new SpecCatalogListenersList(log);
    if (instrumentationEnabled) {
        MetricContext realParentCtx = parentMetricContext
                .or(Instrumented.getMetricContext(new gobblin.configuration.State(), getClass()));
        this.metricContext = realParentCtx.childBuilder(TopologyCatalog.class.getSimpleName()).build();
        this.metrics = new SpecCatalog.StandardMetrics(this);
    } else {// w  w w. j  av  a  2s .  co  m
        this.metricContext = null;
        this.metrics = null;
    }

    this.aliasResolver = new ClassAliasResolver<>(SpecStore.class);
    try {
        Config newConfig = config;
        if (config.hasPath(ConfigurationKeys.TOPOLOGYSPEC_STORE_DIR_KEY)) {
            newConfig = config.withValue(ConfigurationKeys.SPECSTORE_FS_DIR_KEY,
                    config.getValue(ConfigurationKeys.TOPOLOGYSPEC_STORE_DIR_KEY));
        }
        String specStoreClassName = DEFAULT_TOPOLOGYSPEC_STORE_CLASS;
        if (config.hasPath(ConfigurationKeys.TOPOLOGYSPEC_STORE_CLASS_KEY)) {
            specStoreClassName = config.getString(ConfigurationKeys.TOPOLOGYSPEC_STORE_CLASS_KEY);
        }
        this.log.info("Using SpecStore class name/alias " + specStoreClassName);
        this.specStore = (SpecStore) ConstructorUtils.invokeConstructor(
                Class.forName(this.aliasResolver.resolve(specStoreClassName)), newConfig, this);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException
            | ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}