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

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

Introduction

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

Prototype

public abstract <V> Optional<V> transform(Function<? super T, V> function);

Source Link

Document

If the instance is present, it is transformed with the given Function ; otherwise, Optional#absent is returned.

Usage

From source file:org.apache.gobblin.instrumented.Instrumented.java

/**
 * Returns a {@link com.codahale.metrics.Timer.Context} only if {@link org.apache.gobblin.metrics.MetricContext} is defined.
 * @param context an Optional&lt;{@link org.apache.gobblin.metrics.MetricContext}$gt;
 * @param name name of the timer./*from   w w  w . j a  v a  2 s . c o m*/
 * @return an Optional&lt;{@link com.codahale.metrics.Timer.Context}$gt;
 */
public static Optional<Timer.Context> timerContext(Optional<MetricContext> context, final String name) {
    return context.transform(new Function<MetricContext, Timer.Context>() {
        @Override
        public Timer.Context apply(@Nonnull MetricContext input) {
            return input.timer(name).time();
        }
    });
}

From source file:org.apache.gobblin.instrumented.Instrumented.java

/**
 * Updates a timer only if it is defined.
 * @param timer an Optional&lt;{@link com.codahale.metrics.Timer}&gt;
 * @param duration/* w ww .  jav  a2 s  .  c om*/
 * @param unit
 */
public static void updateTimer(Optional<Timer> timer, final long duration, final TimeUnit unit) {
    timer.transform(new Function<Timer, Timer>() {
        @Override
        public Timer apply(@Nonnull Timer input) {
            input.update(duration, unit);
            return input;
        }
    });
}

From source file:org.apache.aurora.scheduler.filter.ConstraintMatcher.java

/**
 * Gets the veto (if any) for a scheduling constraint based on the {@link AttributeAggregate} this
 * filter was created with./*from   w w  w .j a  va 2  s  .c  o m*/
 *
 * @param constraint Scheduling filter to check.
 * @return A veto if the constraint is not satisfied based on the existing state of the job.
 */
static Optional<Veto> getVeto(AttributeAggregate cachedjobState, Iterable<IAttribute> hostAttributes,
        IConstraint constraint) {

    Iterable<IAttribute> sameNameAttributes = Iterables.filter(hostAttributes,
            new NameFilter(constraint.getName()));
    Optional<IAttribute> attribute;
    if (Iterables.isEmpty(sameNameAttributes)) {
        attribute = Optional.absent();
    } else {
        Set<String> attributeValues = ImmutableSet
                .copyOf(Iterables.concat(Iterables.transform(sameNameAttributes, GET_VALUES)));
        attribute = Optional.of(IAttribute.build(new Attribute(constraint.getName(), attributeValues)));
    }

    ITaskConstraint taskConstraint = constraint.getConstraint();
    switch (taskConstraint.getSetField()) {
    case VALUE:
        boolean matches = AttributeFilter.matches(attribute.transform(GET_VALUES).or(ImmutableSet.of()),
                taskConstraint.getValue());
        return matches ? Optional.absent() : Optional.of(Veto.constraintMismatch(constraint.getName()));

    case LIMIT:
        if (!attribute.isPresent()) {
            return Optional.of(Veto.constraintMismatch(constraint.getName()));
        }

        boolean satisfied = AttributeFilter.matches(attribute.get(), taskConstraint.getLimit().getLimit(),
                cachedjobState);
        return satisfied ? Optional.absent() : Optional.of(Veto.unsatisfiedLimit(constraint.getName()));

    default:
        throw new SchedulerException(
                "Failed to recognize the constraint type: " + taskConstraint.getSetField());
    }
}

From source file:sparkjni.utils.SparkJni.java

@Builder.Factory
static SparkJni sparkJniSingleton(Optional<String> appName, String nativePath, Optional<String> jdkPath,
        final Optional<String> classpath) {
    if (sparkJniSingleton == null) {
        sparkJniSingleton = new SparkJni();
        sparkJniSingleton.initVars(appName.isPresent() ? appName.get() : null, nativePath,
                jdkPath.isPresent() ? jdkPath.get() : null);
        classpath.transform(new Function<String, Void>() {
            @Nullable//from w  w  w .  ja va2 s.com
            @Override
            public Void apply(@Nullable String s) {
                sparkJniSingleton.addToClasspath(s);
                return null;
            }
        });
    }
    return sparkJniSingleton;
}

From source file:com.eucalyptus.auth.euare.identity.region.RegionConfigurationManager.java

private static NonNullFunction<Region, RegionInfo> regionToRegionInfoTransform(
        final Optional<RegionConfiguration> regionConfigurationOptional) {
    return new NonNullFunction<Region, RegionInfo>() {
        @Nonnull/*from   www  . j av a  2 s  .c  om*/
        @Override
        public RegionInfo apply(final Region region) {
            return new RegionInfo(region.getName(), region.getIdentifierPartitions(),
                    Collections2.transform(region.getServices(),
                            TypeMappers.lookup(Service.class, RegionService.class)),
                    buildCidrs(regionConfigurationOptional
                            .transform(RegionConfigurationToCidrListTransform.REMOTE).orNull(),
                            region.getRemoteCidrs()),
                    buildCidrs(
                            regionConfigurationOptional
                                    .transform(RegionConfigurationToCidrListTransform.FORWARDED_FOR).orNull(),
                            region.getForwardedForCidrs()),
                    region.getCertificateFingerprintDigest(), region.getCertificateFingerprint(),
                    region.getSslCertificateFingerprintDigest(), region.getSslCertificateFingerprint());
        }
    };
}

From source file:com.facebook.buck.shell.ExportFileBuildRuleFactory.java

@Override
protected void amendBuilder(ExportFile.Builder builder, BuildRuleFactoryParams params)
        throws NoSuchBuildTargetException {
    Optional<String> src = params.getOptionalStringAttribute("src");
    builder.setSrc(src.transform(params.getResolveFilePathRelativeToBuildFileDirectoryTransform()));

    Optional<String> out = params.getOptionalStringAttribute("out");
    builder.setOut(out);//from  ww  w.  j av a2  s  . c om
}

From source file:de.zalando.hackweek.bpm.engine.impl.cassandra.db.handler.SelectHistoricTaskInstanceByIdHandler.java

@Override
public Object selectOne(final Session session, final Object parameter) {
    final String id = (String) parameter;
    final Optional<Row> optionalRow = fromNullable(session.execute(QUERY, id).one());
    return optionalRow.transform(HistoricTaskInstanceMapping.INSTANCE).orNull();
}

From source file:de.zalando.hackweek.bpm.engine.impl.cassandra.db.handler.SelectHistoricTaskInstanceEventByIdHandler.java

@Override
public Object selectOne(final Session session, final Object parameter) {
    final String id = (String) parameter;
    final Optional<Row> optionalRow = fromNullable(session.execute(QUERY, id).one());
    return optionalRow.transform(HistoricTaskInstanceEventMapping.INSTANCE).orNull();
}

From source file:org.glassfish.jersey.tests.integration.jersey2612.Resource.java

@Path("square")
@GET// www  . j a v  a 2 s  .c  o m
@Produces("text/plain")
public int echo(@QueryParam("value") final Optional<Integer> value) {
    return value.transform(new Function<Integer, Integer>() {
        @Override
        public Integer apply(final Integer integer) {
            return integer * integer;
        }
    }).or(0);
}

From source file:de.zalando.hackweek.bpm.engine.impl.cassandra.db.handler.SelectTaskByIdHandler.java

@Override
public Object selectOne(final Session session, final Object parameter) {
    final String id = (String) parameter;

    final Optional<Row> optionalResult = Optional.fromNullable(session.execute(QUERY, id).one());

    return optionalResult.transform(TaskMapping.INSTANCE).orNull();
}