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:gobblin.runtime.job_catalog.JobCatalogBase.java

public JobCatalogBase(Optional<Logger> log, Optional<MetricContext> parentMetricContext,
        boolean instrumentationEnabled) {
    this.log = log.isPresent() ? log.get() : LoggerFactory.getLogger(getClass());
    this.listeners = new JobCatalogListenersList(log);
    if (instrumentationEnabled) {
        MetricContext realParentCtx = parentMetricContext
                .or(Instrumented.getMetricContext(new gobblin.configuration.State(), getClass()));
        this.metricContext = realParentCtx.childBuilder(JobCatalog.class.getSimpleName()).build();
        this.metrics = new StandardMetrics(this);
    } else {/*from  w w  w  .java2  s.com*/
        this.metricContext = null;
        this.metrics = null;
    }
}

From source file:com.voxelplugineering.voxelsniper.brush.effect.OldBlendBrush.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();
    }/* w  ww. jav  a2  s  . c om*/

    Optional<Shape> s = args.get(BrushKeys.SHAPE, Shape.class);
    if (!s.isPresent()) {
        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);
    System.out.println("Using strings " + kernalShape.or("empty") + " and " + kernalSize.or(0.0));
    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;
                }

                // Represents a histogram of material occurrences hit by the
                // structuring element.
                Map<Material, Integer> mats = Maps.newHashMapWithExpectedSize(10);

                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();
                            // Discludes the target block from the
                            // calculation.
                            if (!(a0 == 0 && b0 == 0 && c0 == 0)) {
                                // TODO: Use world bounds instead of
                                // hardcoded magical values from Minecraft.
                                int clampedY = Maths.clamp(y0 + b0, 0, 255);
                                Material mat = world.getBlock(x0 + a0, clampedY, z0 + c0).get().getMaterial();
                                if (mats.containsKey(mat)) {
                                    mats.put(mat, mats.get(mat) + 1);
                                } else {
                                    mats.put(mat, 1);
                                }
                            }
                        }
                    }
                }

                // Select the material which occured the most.
                int n = 0;
                Material winner = null;
                for (Map.Entry<Material, Integer> e : mats.entrySet()) {
                    if (e.getValue() > n && !(excludeFluid && e.getKey().isLiquid())) {
                        winner = e.getKey();
                        n = e.getValue();
                    }
                }

                // If multiple materials occurred the most, the tie check
                // will become true.
                boolean tie = false;
                for (Map.Entry<Material, Integer> e : mats.entrySet()) {
                    if (e.getValue() == n && !(excludeFluid && e.getKey().isLiquid())
                            && !e.getKey().equals(winner)) {
                        tie = true;
                    }
                }

                // If a tie is found, no change is made.
                if (!tie) {
                    ms.setMaterial(x, y, z, false, winner);
                }
            }
        }
    }
    new ShapeChangeQueue(player, loc, ms).flush();
    return ExecutionResult.continueExecution();
}

From source file:io.bazel.rules.closure.webfiles.WebfilesValidator.java

private void addRelationship(Path path, Webpath origin, Webpath relativeDest) {
    if (relativeDest.isAbsolute()) {
        // Even though this code supports absolute paths, we're going to forbid them anyway, because
        // we might want to write a rule in the future that allows the user to reposition a
        // transitive closure of webfiles into a subdirectory on the web server.
        errors.put(ABSOLUTE_PATH_ERROR,/*from ww w . ja va 2 s. c  om*/
                String.format("%s: Please use relative path for asset: %s", path, relativeDest));
        return;
    }
    Webpath dest = origin.lookup(relativeDest);
    if (dest == null) {
        errors.put(PATH_NORMALIZATION_ERROR,
                String.format("%s: Could not normalize %s against %s", path, relativeDest, origin));
        return;
    }
    if (relationships.put(origin, dest) && !accessibleAssets.contains(dest)) {
        Optional<String> label = tryToFindLabelOfTargetProvidingAsset(dest);
        errors.put(STRICT_DEPENDENCIES_ERROR, String.format("%s: Referenced %s (%s) without depending on %s",
                path, relativeDest, dest, label.or("a web_library() rule providing it")));
        return;
    }
}

From source file:com.netflix.hystrix.contrib.javanica.utils.MethodProvider.java

/**
 * Gets fallback method for command method.
 *
 * @param type          type/*from   w w w. j  av a2  s. c  om*/
 * @param commandMethod the command method. in the essence it can be a fallback
 *                      method annotated with HystrixCommand annotation that has a fallback as well.
 * @param extended      true if the given commandMethod was derived using additional parameter, otherwise - false
 * @return new instance of {@link FallbackMethod} or {@link FallbackMethod#ABSENT} if there is no suitable fallback method for the given command
 */
public FallbackMethod getFallbackMethod(Class<?> type, Method commandMethod, boolean extended) {
    if (commandMethod.isAnnotationPresent(HystrixCommand.class)) {
        HystrixCommand hystrixCommand = commandMethod.getAnnotation(HystrixCommand.class);
        if (StringUtils.isNotBlank(hystrixCommand.fallbackMethod())) {
            Class<?>[] parameterTypes = commandMethod.getParameterTypes();
            if (extended && parameterTypes[parameterTypes.length - 1] == Throwable.class) {
                parameterTypes = ArrayUtils.remove(parameterTypes, parameterTypes.length - 1);
            }
            Class<?>[] exParameterTypes = Arrays.copyOf(parameterTypes, parameterTypes.length + 1);
            exParameterTypes[parameterTypes.length] = Throwable.class;
            Optional<Method> exFallbackMethod = getMethod(type, hystrixCommand.fallbackMethod(),
                    exParameterTypes);
            Optional<Method> fMethod = getMethod(type, hystrixCommand.fallbackMethod(), parameterTypes);
            Method method = exFallbackMethod.or(fMethod).orNull();
            if (method == null) {
                throw new FallbackDefinitionException("fallback method wasn't found: "
                        + hystrixCommand.fallbackMethod() + "(" + Arrays.toString(parameterTypes) + ")");
            }
            return new FallbackMethod(method, exFallbackMethod.isPresent());
        }
    }
    return FallbackMethod.ABSENT;
}

From source file:gobblin.metrics.kafka.KafkaReporterFactory.java

@Override
public ScheduledReporter newScheduledReporter(MetricRegistry registry, Properties properties)
        throws IOException {
    if (!Boolean.valueOf(properties.getProperty(ConfigurationKeys.METRICS_REPORTING_KAFKA_ENABLED_KEY,
            ConfigurationKeys.DEFAULT_METRICS_REPORTING_KAFKA_ENABLED))) {
        return null;
    }/*from   w w w  .  j a  va2  s .c o m*/
    log.info("Reporting metrics to Kafka");

    Optional<String> defaultTopic = Optional
            .fromNullable(properties.getProperty(ConfigurationKeys.METRICS_KAFKA_TOPIC));
    Optional<String> metricsTopic = Optional
            .fromNullable(properties.getProperty(ConfigurationKeys.METRICS_KAFKA_TOPIC_METRICS));
    Optional<String> eventsTopic = Optional
            .fromNullable(properties.getProperty(ConfigurationKeys.METRICS_KAFKA_TOPIC_EVENTS));

    boolean metricsEnabled = metricsTopic.or(defaultTopic).isPresent();
    if (metricsEnabled)
        log.info("Reporting metrics to Kafka");
    boolean eventsEnabled = eventsTopic.or(defaultTopic).isPresent();
    if (eventsEnabled)
        log.info("Reporting events to Kafka");

    try {
        Preconditions.checkArgument(properties.containsKey(ConfigurationKeys.METRICS_KAFKA_BROKERS),
                "Kafka metrics brokers missing.");
        Preconditions.checkArgument(metricsTopic.or(eventsTopic).or(defaultTopic).isPresent(),
                "Kafka topic missing.");
    } catch (IllegalArgumentException exception) {
        log.error("Not reporting metrics to Kafka due to missing Kafka configuration(s).", exception);
        return null;
    }

    String brokers = properties.getProperty(ConfigurationKeys.METRICS_KAFKA_BROKERS);

    String reportingFormat = properties.getProperty(ConfigurationKeys.METRICS_REPORTING_KAFKA_FORMAT,
            ConfigurationKeys.DEFAULT_METRICS_REPORTING_KAFKA_FORMAT);

    KafkaReportingFormats formatEnum;
    try {
        formatEnum = KafkaReportingFormats.valueOf(reportingFormat.toUpperCase());
    } catch (IllegalArgumentException exception) {
        log.warn("Kafka metrics reporting format " + reportingFormat
                + " not recognized. Will report in json format.", exception);
        formatEnum = KafkaReportingFormats.JSON;
    }

    if (metricsEnabled) {
        try {
            formatEnum.metricReporterBuilder(properties).build(brokers, metricsTopic.or(defaultTopic).get(),
                    properties);
        } catch (IOException exception) {
            log.error("Failed to create Kafka metrics reporter. Will not report metrics to Kafka.", exception);
        }
    }

    if (eventsEnabled) {
        try {
            KafkaEventReporter.Builder<?> builder = formatEnum.eventReporterBuilder(RootMetricContext.get(),
                    properties);
            return builder.build(brokers, eventsTopic.or(defaultTopic).get());
        } catch (IOException exception) {
            log.error("Failed to create Kafka events reporter. Will not report events to Kafka.", exception);
        }
    }

    log.info("Will start reporting metrics to Kafka");
    return null;
}

From source file:org.apache.rya.indexing.pcj.fluo.api.InsertTriples.java

/**
 * Insert a batch of triples into Fluo.//from   w  ww.j  ava  2s .  co m
 *
 * @param fluo - A connection to the Fluo table that will be updated. (not null)
 * @param triples - The triples to insert. (not null)
 * @param visibility - The visibility/permissions required to view the triples once stored.
 * Note: The same visibility will be applied to each triple.(not null)
 */
public void insert(final FluoClient fluo, final Collection<RyaStatement> triples,
        final Optional<String> visibility) {
    checkNotNull(fluo);
    checkNotNull(triples);
    checkNotNull(visibility);

    try (Transaction tx = fluo.newTransaction()) {
        for (final RyaStatement triple : triples) {
            try {
                tx.set(spoFormat(triple), FluoQueryColumns.TRIPLES, Bytes.of(visibility.or("")));
            } catch (final TripleRowResolverException e) {
                log.error("Could not convert a Triple into the SPO format: " + triple);
            }
        }

        tx.commit();
    }
}

From source file:google.registry.batch.MapreduceEntityCleanupAction.java

private String requestDeletion(Set<String> actualJobIds, boolean verbose) {
    Optional<StringBuilder> payloadChunkBuilder = verbose ? Optional.of(new StringBuilder())
            : Optional.<StringBuilder>absent();
    int errorCount = 0;
    for (String actualJobId : actualJobIds) {
        Optional<String> error = mapreduceEntityCleanupUtil.deleteJobAsync(datastore, actualJobId,
                force.or(false));//from   w w  w. ja  va  2  s. com
        if (error.isPresent()) {
            errorCount++;
        }
        logger.infofmt("%s: %s", actualJobId, error.or("deletion requested"));
        if (payloadChunkBuilder.isPresent()) {
            payloadChunkBuilder.get()
                    .append(String.format("%s: %s\n", actualJobId, error.or("deletion requested")));
        }
    }
    logger.infofmt("successfully requested async deletion of %s job(s); errors received on %s",
            actualJobIds.size() - errorCount, errorCount);
    if (payloadChunkBuilder.isPresent()) {
        payloadChunkBuilder.get()
                .append(String.format(
                        "successfully requested async deletion of %d job(s); errors received on %d\n",
                        actualJobIds.size() - errorCount, errorCount));
        return payloadChunkBuilder.get().toString();
    } else {
        return "";
    }
}

From source file:gobblin.writer.TrackerBasedWatermarkManager.java

public TrackerBasedWatermarkManager(WatermarkStorage storage, FineGrainedWatermarkTracker watermarkTracker,
        long commitIntervalMillis, Optional<Logger> logger) {
    Preconditions.checkArgument(storage != null, "WatermarkStorage cannot be null");
    Preconditions.checkArgument(watermarkTracker != null, "WatermarkTracker cannot be null");
    _watermarkTracker = watermarkTracker;
    _watermarkStorage = storage;//  w w w  . jav  a  2s . com
    _commitIntervalMillis = commitIntervalMillis;
    _logger = logger.or(LoggerFactory.getLogger(TrackerBasedWatermarkManager.class));
    _watermarkCommitThreadPool = new ScheduledThreadPoolExecutor(1,
            ExecutorsUtils.newThreadFactory(logger, Optional.of("WatermarkManager-%d")));
    _retrievalStatus = new RetrievalStatus();
    _commitStatus = new CommitStatus();
}

From source file:org.basepom.mojo.propertyhelper.AbstractPropertyHelperMojo.java

protected void loadPropertyElements() throws Exception {
    final ImmutableList.Builder<PropertyElement> propertyElements = ImmutableList.builder();

    numberFields = NumberField.createNumbers(valueCache, numbers);
    propertyElements.addAll(numberFields);
    propertyElements.addAll(StringField.createStrings(valueCache, strings));
    propertyElements.addAll(DateField.createDates(valueCache, dates));
    propertyElements.addAll(MacroField.createMacros(valueCache, macros, this));
    propertyElements.addAll(UuidField.createUuids(valueCache, uuids));

    for (final PropertyElement pe : propertyElements.build()) {
        final Optional<String> value = pe.getPropertyValue();
        values.put(pe.getPropertyName(), value.orNull());

        if (pe.isExport()) {
            final String result = value.or("");
            project.getProperties().setProperty(pe.getPropertyName(), result);
            LOG.debug("Exporting Property name: %s, value: %s", pe.getPropertyName(), result);
        } else {/*from w  w  w .  ja va 2 s. c  o  m*/
            LOG.debug("Property name: %s, value: %s", pe.getPropertyName(), value.or("<null>"));
        }
    }

    // Now generate the property groups.
    final ImmutableMap.Builder<String, Map.Entry<PropertyGroup, List<PropertyElement>>> builder = ImmutableMap
            .builder();

    final Set<String> propertyNames = Sets.newHashSet();

    if (propertyGroups != null) {
        for (final PropertyGroup propertyGroup : propertyGroups) {
            final List<PropertyElement> propertyFields = PropertyField.createProperties(project.getModel(),
                    values, propertyGroup);
            builder.put(propertyGroup.getId(),
                    new AbstractMap.SimpleImmutableEntry<>(propertyGroup, propertyFields));
        }
    }

    final Map<String, Map.Entry<PropertyGroup, List<PropertyElement>>> propertyPairs = builder.build();

    if (activeGroups != null) {
        for (final String activeGroup : activeGroups) {
            final Map.Entry<PropertyGroup, List<PropertyElement>> propertyElement = propertyPairs
                    .get(activeGroup);
            checkState(propertyElement != null, "activated group '%s' does not exist", activeGroup);

            final PropertyGroup propertyGroup = propertyElement.getKey();
            if ((propertyGroup.isActiveOnRelease() && !isSnapshot)
                    || (propertyGroup.isActiveOnSnapshot() && isSnapshot)) {
                for (final PropertyElement pe : propertyElement.getValue()) {
                    final Optional<String> value = pe.getPropertyValue();
                    final String propertyName = pe.getPropertyName();
                    IgnoreWarnFail.checkState(propertyGroup.getOnDuplicateProperty(),
                            !propertyNames.contains(propertyName), "property name '" + propertyName + "'");
                    propertyNames.add(propertyName);

                    project.getProperties().setProperty(propertyName, value.or(""));
                }
            } else {
                LOG.debug("Skipping property group %s: Snapshot: %b, activeOnSnapshot: %b, activeOnRelease: %b",
                        activeGroup, isSnapshot, propertyGroup.isActiveOnSnapshot(),
                        propertyGroup.isActiveOnRelease());
            }
        }
    }
}

From source file:org.apache.gobblin.runtime.job_catalog.JobCatalogBase.java

public JobCatalogBase(Optional<Logger> log, Optional<MetricContext> parentMetricContext,
        boolean instrumentationEnabled, Optional<Config> sysConfig) {
    this.log = log.isPresent() ? log.get() : LoggerFactory.getLogger(getClass());
    this.listeners = new JobCatalogListenersList(log);
    if (instrumentationEnabled) {
        MetricContext realParentCtx = parentMetricContext
                .or(Instrumented.getMetricContext(new org.apache.gobblin.configuration.State(), getClass()));
        this.metricContext = realParentCtx.childBuilder(JobCatalog.class.getSimpleName()).build();
        this.metrics = createStandardMetrics(sysConfig);
        this.addListener(this.metrics);
    } else {/*  w w  w .j a v a  2  s  .  c  o  m*/
        this.metricContext = null;
        this.metrics = null;
    }
}