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:fr.ippon.wip.filter.PerformanceFilter.java

private void writePerformance(StringBuilder data) {
    Optional<Long> optionalTime;

    optionalTime = Optional.fromNullable(HTMLTransformer.timeProcess.get());
    data.append(optionalTime.or(0L) + "\t");
    if (optionalTime.isPresent())
        HTMLTransformer.timeProcess.remove();

    optionalTime = Optional.fromNullable(CSSTransformer.timeProcess.get());
    data.append(optionalTime.or(0L) + "\t");
    if (optionalTime.isPresent())
        CSSTransformer.timeProcess.remove();

    optionalTime = Optional.fromNullable(JSTransformer.timeProcess.get());
    data.append(optionalTime.or(0L) + "\t");
    if (optionalTime.isPresent())
        JSTransformer.timeProcess.remove();

    optionalTime = Optional.fromNullable(HttpClientDecorator.timeProcess.get());
    data.append(optionalTime.or(0L) + "\t");
    if (optionalTime.isPresent())
        HttpClientDecorator.timeProcess.remove();

    data.append("\n");

    try {//from   w w  w.j  av  a 2  s .c o m
        out.write(data.toString());
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:co.paralleluniverse.fibers.dropwizard.MyDropwizardApp.java

@GET
@Timed//from w ww.  ja va 2s  .  c  o m
public Saying get(@QueryParam("name") Optional<String> name,
        @QueryParam("sleep") Optional<Integer> sleepParameter) throws InterruptedException, SuspendExecution {
    Fiber.sleep(sleepParameter.or(10));
    return new Saying(ai.incrementAndGet(), name.or("name"));
}

From source file:com.boundary.metrics.vmware.client.metrics.MetricClient.java

/**
 * Adds metric measurements and sends to Boundary APIs
 * /*from   www.j av a2s.co  m*/
 * @param sourceId meter source id
 * @param measurements measurements to associate with the source
 * @param optionalTimestamp time of the metrics
 */
public void addMeasurements(int sourceId, Map<String, Number> measurements,
        Optional<DateTime> optionalTimestamp) {
    List<List<Object>> payload = Lists.newArrayList();
    final long timestamp = optionalTimestamp.or(new DateTime()).getMillis();
    for (Map.Entry<String, Number> m : measurements.entrySet()) {
        LOG.debug("Measurement: {}, {}, {}, {}", String.valueOf(sourceId), m.getKey(), m.getValue(), timestamp);
        payload.add(ImmutableList.<Object>of(String.valueOf(sourceId), m.getKey(), m.getValue(), timestamp));
    }
    sendMeasurements(payload);
}

From source file:ninja.thymeleaf.template.TemplateEngineThymeleafI18nMessageResolver.java

@Override
public MessageResolution resolveMessage(Arguments arguments, String key, Object[] messageParameters) {
    Locale locale = null;// w  w  w.ja v  a2s .c o m
    if (arguments != null) {
        locale = arguments.getContext().getLocale();
    }

    Optional<String> lang = Optional.absent();
    if (locale != null) {
        // to conform to rfc5646 and BCP 47
        lang = Optional.of(locale.toString().replace('_', '-'));
    }

    Optional<String> i18nMessage = Optional.absent();
    i18nMessage = messages.get(key, lang, messageParameters);

    if (!i18nMessage.isPresent()) {
        return null;
    }

    return new MessageResolution(i18nMessage.or(""));
}

From source file:com.facebook.buck.java.JavaBuckConfig.java

public JavaCompilerEnvironment getJavaCompilerEnvironment(ProcessExecutor processExecutor) {
    Optional<Path> javac = getJavac();
    Optional<JavacVersion> javacVersion = Optional.absent();
    if (javac.isPresent()) {
        javacVersion = Optional.of(getJavacVersion(processExecutor, javac.get()));
    }//from w w w .  ja va  2 s.c  o m
    Optional<String> sourceLevel = delegate.getValue("java", "source_level");
    Optional<String> targetLevel = delegate.getValue("java", "target_level");
    return new JavaCompilerEnvironment(javac, javacVersion, sourceLevel.or(TARGETED_JAVA_VERSION),
            targetLevel.or(TARGETED_JAVA_VERSION));
}

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

@GET
public List<HotfixBean> getAll(@QueryParam("envName") String envName,
        @QueryParam("pageIndex") Optional<Integer> pageIndex,
        @QueryParam("pageSize") Optional<Integer> pageSize) throws Exception {
    return hotfixDAO.getHotfixes(envName, pageIndex.or(1), pageSize.or(DEFAULT_SIZE));
}

From source file:com.arpnetworking.tsdcore.statistics.SumStatistic.java

/**
 * {@inheritDoc}/*w ww .j ava 2  s.  c om*/
 */
@Override
public Quantity calculateAggregations(final List<AggregatedData> aggregations) {
    double sum = 0;
    Optional<Unit> unit = Optional.absent();
    for (final AggregatedData aggregation : aggregations) {
        sum += aggregation.getValue().getValue();
        unit = unit.or(aggregation.getValue().getUnit());
    }
    return new Quantity.Builder().setValue(sum).setUnit(unit.orNull()).build();
}

From source file:com.voxelplugineering.voxelsniper.brush.effect.morphological.FilterBrush.java

@Override
public ExecutionResult run(Player player, BrushVars args) {
    boolean excludeFluid = true;
    if (args.has(BrushKeys.EXCLUDE_FLUID)) {
        excludeFluid = args.get(BrushKeys.EXCLUDE_FLUID, Boolean.class).get();
    }//from  w ww . ja v  a2s .c om

    Optional<Shape> s = args.get(BrushKeys.SHAPE, Shape.class);
    if (!s.isPresent()) {
        player.sendMessage("You must have at least one shape brush before your" + this.getName() + "brush.");
        return ExecutionResult.abortExecution();
    }
    Optional<Material> m = args.get(BrushKeys.MATERIAL, Material.class);
    if (!m.isPresent()) {
        player.sendMessage("You must select a material.");
        return ExecutionResult.abortExecution();
    }

    Optional<String> kernalShape = args.get(BrushKeys.KERNEL, String.class);
    Optional<Double> kernalSize = args.get(BrushKeys.KERNEL_SIZE, Double.class);
    double size = kernalSize.or(1.0);
    String kernelString = kernalShape.or("voxel");
    Optional<Shape> se = PrimativeShapeFactory.createShape(kernelString, size);
    if (!se.isPresent()) {
        se = Optional.<Shape>of(new CuboidShape(3, 3, 3, new Vector3i(1, 1, 1)));
    }

    Optional<Block> l = args.get(BrushKeys.TARGET_BLOCK, Block.class);
    MaterialShape ms = new ComplexMaterialShape(s.get(), m.get());

    World world = player.getWorld();
    Location loc = l.get().getLocation();
    Shape shape = s.get();
    Shape structElem = se.get();

    // Extract the location in the world to x0, y0 and z0.
    for (int x = 0; x < ms.getWidth(); x++) {
        int x0 = loc.getFlooredX() + x - shape.getOrigin().getX();
        for (int y = 0; y < ms.getHeight(); y++) {
            int y0 = loc.getFlooredY() + y - shape.getOrigin().getY();
            for (int z = 0; z < ms.getLength(); z++) {
                int z0 = loc.getFlooredZ() + z - shape.getOrigin().getZ();
                if (!shape.get(x, y, z, false)) {
                    continue;
                }
                for (int a = 0; a < structElem.getWidth(); a++) {
                    for (int b = 0; b < structElem.getHeight(); b++) {
                        for (int c = 0; c < structElem.getLength(); c++) {

                            if (!structElem.get(a, b, c, false)) {
                                continue;
                            }

                            int a0 = a - structElem.getOrigin().getX();
                            int b0 = b - structElem.getOrigin().getY();
                            int c0 = c - structElem.getOrigin().getZ();

                            if (excludeFluid && world.getBlock(x0 + a0, y0 + b0, z0 + c0).get().getMaterial()
                                    .isLiquid()) {
                                continue;
                            }

                            // Request visitor to perform check operation on
                            // relevant voxel.
                            operation.checkPosition(x0, y0, z0, a0, b0, c0, world,
                                    world.getBlock(x0 + a0, y0 + b0, z0 + c0).get().getMaterial());
                        }
                    }
                }

                // Request visitor to decide final material.
                if (operation.getResult().isPresent()) {
                    ms.setMaterial(x, y, z, false, operation.getResult().get());
                }
                operation.reset();
            }
        }
    }
    new ShapeChangeQueue(player, loc, ms).flush();
    return ExecutionResult.continueExecution();
}

From source file:gobblin.util.filesystem.PathAlterationObserverScheduler.java

/**
 * Create and attach {@link PathAlterationObserverScheduler}s for the given
 * root directory and any nested subdirectories under the root directory to the given
 * {@link PathAlterationObserverScheduler}.
 * @param detector  a {@link PathAlterationObserverScheduler}
 * @param listener a {@link gobblin.util.filesystem.PathAlterationListener}
 * @param observerOptional Optional observer object. For testing routine, this has been initialized by user.
 *                         But for general usage, the observer object is created inside this method.
 * @param rootDirPath root directory/* ww w.ja  v a 2s .com*/
 * @throws IOException
 */
public void addPathAlterationObserver(PathAlterationListener listener,
        Optional<PathAlterationObserver> observerOptional, Path rootDirPath) throws IOException {
    PathAlterationObserver observer = observerOptional.or(new PathAlterationObserver(rootDirPath));
    observer.addListener(listener);
    addObserver(observer);
}

From source file:com.facebook.buck.rules.ExportFileRule.java

@VisibleForTesting
ExportFileRule(BuildRuleParams params, Optional<String> src, Optional<String> out) {
    super(params);

    String shortName = params.getBuildTarget().getShortName();

    this.src = src.or(shortName);

    final String outName = out.or(shortName);

    this.out = Suppliers.memoize(new Supplier<File>() {
        @Override//from w  w w  .j  a  v a  2s.c om
        public File get() {
            String name = new File(outName).getName();
            String outputPath = String.format("%s/%s%s", BuckConstant.GEN_DIR,
                    getBuildTarget().getBasePathWithSlash(), name);

            return new File(outputPath);
        }
    });
}