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:org.apache.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;
    }//  www . j a  va 2s. com
    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);

            Config allConfig = ConfigUtils.propertiesToConfig(properties);
            // the kafka configuration is composed of the metrics reporting specific keys with a fallback to the shared
            // kafka config
            Config kafkaConfig = ConfigUtils
                    .getConfigOrEmpty(allConfig, PusherUtils.METRICS_REPORTING_KAFKA_CONFIG_PREFIX)
                    .withFallback(ConfigUtils.getConfigOrEmpty(allConfig,
                            ConfigurationKeys.SHARED_KAFKA_CONFIG_PREFIX));

            builder.withConfig(kafkaConfig);

            builder.withPusherClassName(properties.getProperty(PusherUtils.KAFKA_PUSHER_CLASS_NAME_KEY,
                    PusherUtils.DEFAULT_KAFKA_PUSHER_CLASS_NAME));

            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:pl.project13.jgit.DescribeResult.java

public DescribeResult(@NotNull ObjectReader objectReader, @NotNull ObjectId commitId, boolean dirty,
        @NotNull Optional<String> dirtyMarker) {
    this.objectReader = objectReader;

    this.commitId = Optional.of(commitId);
    this.abbreviatedObjectId = createAbbreviatedCommitId(objectReader, commitId, this.abbrev);

    this.dirty = dirty;
    this.dirtyMarker = dirtyMarker.or("");
}

From source file:ezbake.deployer.configuration.EzDeployerConfiguration.java

/**
 * Gets a property from configuration for the given Key
 *
 * @param key - key to get the value from
 * @return the value from configuration, or the default configured value for the key.
 * @throws java.lang.IllegalStateException - if the configuration parameter is not found and the key was marked required.
 *//*from   w w  w. ja v a2 s. c om*/
private Optional<String> get(Key key) {
    if (key.isRequired())
        return getOrThrow(key);
    Optional<String> val = Optional.fromNullable(configuration.getProperty(key.key()));
    return val.or(key.getDefaultValue());
}

From source file:at.ac.univie.isc.asio.d2rq.LoadD2rqModel.java

private Model doParse(final ByteSource source) throws IOException {
    // first pass : use default or overriding to avoid non-deterministic resolution
    Model model = readFrom(source, baseUri.or(D2rqTools.DEFAULT_BASE));
    final Optional<String> embeddedBaseUri = D2rqTools.findEmbeddedBaseUri(model);
    if (!baseUri.isPresent() && embeddedBaseUri.isPresent()) {
        // second pass : use retrieved base uri for resolution if no override set
        model.close();/*from w  w w.ja va 2  s.  c  o m*/
        model = readFrom(source, embeddedBaseUri.get());
    }
    injectBaseUri(model, baseUri.or(embeddedBaseUri.or(D2rqTools.DEFAULT_BASE)));
    return model;
}

From source file:org.locationtech.geogig.cli.porcelain.Show.java

public void printFormatted(GeogigCLI cli) throws IOException {
    ConsoleReader console = cli.getConsole();
    GeoGIG geogig = cli.getGeogig();//from  w  w  w.j a  v a  2s  . c  o  m
    for (String ref : refs) {
        Optional<RevObject> obj = geogig.command(RevObjectParse.class).setRefSpec(ref).call();
        if (!obj.isPresent()) {
            ref = getFullRef(ref);
            obj = geogig.command(RevObjectParse.class).setRefSpec(ref).call();
        }
        checkParameter(obj.isPresent(), "refspec did not resolve to any object.");
        RevObject revObject = obj.get();
        if (revObject instanceof RevFeature) {
            Optional<RevFeatureType> opt = geogig.command(ResolveFeatureType.class).setRefSpec(ref).call();
            if (opt.isPresent()) {
                RevFeatureType ft = opt.get();
                ImmutableList<PropertyDescriptor> attribs = ft.sortedDescriptors();
                RevFeature feature = (RevFeature) revObject;
                Ansi ansi = super.newAnsi(console.getTerminal());
                ansi.newline().fg(Color.YELLOW).a("ID:  ").reset().a(feature.getId().toString()).newline();
                ansi.fg(Color.YELLOW).a("FEATURE TYPE ID:  ").reset().a(ft.getId().toString()).newline()
                        .newline();
                ansi.a("ATTRIBUTES  ").newline();
                ansi.a("----------  ").newline();
                ImmutableList<Optional<Object>> values = feature.getValues();
                int i = 0;
                for (Optional<Object> value : values) {
                    ansi.fg(Color.YELLOW).a(attribs.get(i).getName() + ": ").reset();
                    ansi.a(value.or("[NULL]").toString()).newline();
                    i++;
                }
                console.println(ansi.toString());
            } else {
                CharSequence s = geogig.command(CatObject.class).setObject(Suppliers.ofInstance(revObject))
                        .call();
                console.println(s);
            }

        } else if (revObject instanceof RevTree) {
            RevTree tree = (RevTree) revObject;
            Optional<RevFeatureType> opt = geogig.command(ResolveFeatureType.class).setRefSpec(ref).call();
            checkParameter(opt.isPresent(), "Refspec must resolve to a commit, tree, feature or feature type");
            RevFeatureType ft = opt.get();
            Ansi ansi = super.newAnsi(console.getTerminal());

            ansi.fg(Color.YELLOW).a("TREE ID:  ").reset().a(tree.getId().toString()).newline();
            ansi.fg(Color.YELLOW).a("SIZE:  ").reset().a(Long.toString(tree.size())).newline();
            ansi.fg(Color.YELLOW).a("NUMBER Of SUBTREES:  ").reset()
                    .a(Integer.toString(tree.numTrees()).toString()).newline();

            printFeatureType(ansi, ft, true);

            console.println(ansi.toString());
        } else if (revObject instanceof RevCommit) {
            RevCommit commit = (RevCommit) revObject;
            Ansi ansi = super.newAnsi(console.getTerminal());
            ansi.a(Strings.padEnd("Commit:", 15, ' ')).fg(Color.YELLOW).a(commit.getId().toString()).reset()
                    .newline();
            ansi.a(Strings.padEnd("Author:", 15, ' ')).fg(Color.GREEN).a(formatPerson(commit.getAuthor()))
                    .reset().newline();
            ansi.a(Strings.padEnd("Committer:", 15, ' ')).fg(Color.GREEN).a(formatPerson(commit.getAuthor()))
                    .reset().newline();
            ansi.a(Strings.padEnd("Author date:", 15, ' ')).a("(").fg(Color.RED)
                    .a(estimateSince(geogig.getPlatform(), commit.getAuthor().getTimestamp())).reset().a(") ")
                    .a(new Date(commit.getAuthor().getTimestamp())).newline();
            ansi.a(Strings.padEnd("Committer date:", 15, ' ')).a("(").fg(Color.RED)
                    .a(estimateSince(geogig.getPlatform(), commit.getCommitter().getTimestamp())).reset()
                    .a(") ").a(new Date(commit.getCommitter().getTimestamp())).newline();
            ansi.a(Strings.padEnd("Subject:", 15, ' ')).a(commit.getMessage()).newline();
            console.println(ansi.toString());
        } else if (revObject instanceof RevFeatureType) {
            Ansi ansi = super.newAnsi(console.getTerminal());
            printFeatureType(ansi, (RevFeatureType) revObject, false);
            console.println(ansi.toString());
        } else {
            throw new InvalidParameterException(
                    "Refspec must resolve to a commit, tree, feature or feature type");
        }
        console.println();
    }

}

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

/**
 * Create a new instance./*from  ww w .  java  2  s.  c  o  m*/
 *
 * TODO: enable to launch more than one instace
 * 
 * @param userMetaData A map containing optional user-defined tags.
 * @return   Meta data object for the created instance.
 *
 * @throws RunNodesException   If the instance could not be started.
 */
NodeMetadata createInstance(AmazonNodeConfiguration nodeConfiguration,
        Optional<Map<String, String>> userMetaData) throws RunNodesException {
    logger.info("Creating a new instance...");
    ComputeService computeService = contextManager.getEagerContext().getComputeService();
    Template template = nodeConfiguration.getTemplate(computeService.templateBuilder());

    Optional<String> group = nodeConfiguration.getProfile().getGroup();
    String groupName = group.or(DEFAULT_GROUP_NAME);

    setTemplateOptions(template, nodeConfiguration, userMetaData);

    Set<? extends NodeMetadata> instances = computeService.createNodesInGroup(groupName, 1, template);

    NodeMetadata metadata = Iterables.getOnlyElement(instances);
    if (!nodeConfiguration.getCredentials().isPresent()) {
        AmazonGeneratedKeyPairCredentials credentials = new AmazonGeneratedKeyPairCredentials(
                String.format("node#%s", metadata.getId()), metadata.getCredentials().getUser(),
                metadata.getCredentials().getPrivateKey());
        nodeConfiguration.setCredentials(credentials);
    }
    logger.info("Instance {} created.", metadata.getId());
    return metadata;
}

From source file:com.gmail.walles.johan.headsetharry.handlers.CalendarPresenter.java

@Nullable
private List<TextWithLocale> createAnnouncementForEventId(int calendarEventId) {
    try (Cursor cursor = context.getContentResolver().query(CalendarContract.Events.CONTENT_URI,

            new String[] { CalendarContract.Events.TITLE, CalendarContract.Events.DESCRIPTION },

            String.format(Locale.ENGLISH, "%s=? AND %s!=?", //NON-NLS
                    CalendarContract.Events._ID, CalendarContract.Events.SELF_ATTENDEE_STATUS),
            new String[] { Integer.toString(calendarEventId),
                    Integer.toString(CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED) },

            null)) {/* ww  w  .jav a  2s  .co  m*/
        if (cursor == null) {
            throw new NullPointerException("Got null cursor from calendar query <event from event ID>");
        }

        if (cursor.getCount() != 1) {
            Timber.w("Didn't get exactly one calendar event for ID %d: %d", calendarEventId, cursor.getCount());
        }

        if (!cursor.moveToNext()) {
            return null;
        }

        String title = cursor.getString(0);
        String description = cursor.getString(1);

        Optional<Locale> eventLocale = identifyLanguage(title);
        if (!eventLocale.isPresent()) {
            eventLocale = identifyLanguage(description);
        }

        Translations translations = new Translations(context, eventLocale.or(Locale.getDefault()),
                R.string.calendar_event_colon_what);
        return translations.format(R.string.calendar_event_colon_what, eventLocale.or(Locale.getDefault()),
                title);
    } catch (SecurityException e) {
        boolean pref = PreferenceManager.getDefaultSharedPreferences(context)
                .getBoolean(getClass().getSimpleName(), true);

        // Warning because if things work as intended this would require somebody to:
        // 1. Enable calendar announcements
        // 2. Grant us READ_CALENDAR permissions
        // 3. Go to the system settings and remove our READ_CALENDAR permissions
        Timber.w(e, "Calendar access denied with pref=%b, resetting preference", pref);

        PreferenceManager.getDefaultSharedPreferences(context).edit()
                .putBoolean(getClass().getSimpleName(), false).apply();

        return null;
    }
}

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

@GET
public List<BuildBean> get(@QueryParam("commit") String scmCommit, @QueryParam("name") String buildName,
        @QueryParam("branch") String scmBranch, @QueryParam("pageIndex") Optional<Integer> pageIndex,
        @QueryParam("pageSize") Optional<Integer> pageSize, @QueryParam("before") Long before,
        @QueryParam("after") Long after) throws Exception {

    if (!StringUtils.isEmpty(scmCommit)) {
        return buildDAO.getByCommit7(StringUtils.substring(scmCommit, 0, 7), pageIndex.or(1),
                pageSize.or(DEFAULT_SIZE));
    }//from  ww w  . j  a  v  a  2  s .c om

    if (!StringUtils.isEmpty(buildName)) {
        if (before != null && after != null) {
            return buildDAO.getByNameDate(buildName, scmBranch, before, after);
        } else {
            return buildDAO.getByName(buildName, scmBranch, pageIndex.or(1), pageSize.or(DEFAULT_SIZE));
        }
    }

    throw new TeletaanInternalException(Response.Status.BAD_REQUEST,
            "Require either commit id or build name in the request.");
}

From source file:lcmc.cluster.service.storage.BlockDeviceService.java

private List<String> getCommonBlockDeviceNames(final Set<Host> hosts) {
    Optional<List<String>> namesIntersection = Optional.absent();
    for (final Host host : hosts) {
        final HostBlockDevices hostBlockDevices = hostBlockDevicesByHost.get(host);
        if (hostBlockDevices != null) {
            namesIntersection = hostBlockDevices.getBlockDevicesNamesIntersection(namesIntersection);
        }//  ww w . j a v a 2  s.  co  m
    }
    return namesIntersection.or(new ArrayList<String>());
}

From source file:org.opendaylight.netconf.ssh.osgi.NetconfSSHActivator.java

private SshProxyServer startSSHServer(final BundleContext bundleContext) throws IOException {
    final Optional<InetSocketAddress> maybeSshSocketAddress = NetconfConfigUtil
            .extractNetconfServerAddress(bundleContext, InfixProp.ssh);
    if (!maybeSshSocketAddress.isPresent()) {
        LOG.warn("SSH bridge not configured. Using default value {}",
                NetconfConfigUtil.DEFAULT_SSH_SERVER_ADRESS);
    }/*from   w w  w.j av a 2  s. c  o  m*/
    final InetSocketAddress sshSocketAddress = maybeSshSocketAddress
            .or(NetconfConfigUtil.DEFAULT_SSH_SERVER_ADRESS);
    LOG.info("Starting netconf SSH bridge at {}", sshSocketAddress);

    final LocalAddress localAddress = NetconfConfigUtil.getNetconfLocalAddress();

    authProviderTracker = new AuthProviderTracker(bundleContext);

    final Optional<String> maybePath = NetconfConfigUtil.getPrivateKeyPath(bundleContext);
    if (!maybePath.isPresent()) {
        LOG.warn("Private key path not configured. Using default value {}",
                NetconfConfigUtil.DEFAULT_PRIVATE_KEY_PATH);
    }
    final String path = maybePath.or(NetconfConfigUtil.DEFAULT_PRIVATE_KEY_PATH);
    LOG.trace("Starting netconf SSH bridge with path to ssh private key {}", path);

    final SshProxyServer sshProxyServer = new SshProxyServer(minaTimerExecutor, clientGroup, nioExecutor);
    sshProxyServer.bind(new SshProxyServerConfigurationBuilder().setBindingAddress(sshSocketAddress)
            .setLocalAddress(localAddress).setAuthenticator(authProviderTracker)
            .setKeyPairProvider(new PEMGeneratorHostKeyProvider(path, ALGORITHM, KEY_SIZE))
            .setIdleTimeout(DEFAULT_IDLE_TIMEOUT).createSshProxyServerConfiguration());
    return sshProxyServer;
}