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.locationtech.geogig.repository.impl.WorkingTreeImpl.java

/**
 * Returns true if there are no unstaged changes, false otherwise
 *///from   w  w  w . j a va2 s .c  o  m
@Override
public boolean isClean() {
    Optional<ObjectId> resolved = context.command(ResolveTreeish.class).setTreeish(Ref.STAGE_HEAD).call();
    return getTree().getId().equals(resolved.or(ObjectId.NULL));
}

From source file:org.restcomm.media.control.mgcp.command.CreateConnectionCommand.java

private String loadRemoteDescription(Parameters<MgcpParameterType> parameters) throws MgcpCommandException {
    Optional<String> remoteSdp = parameters.getString(MgcpParameterType.SDP);
    Optional<String> secondEndpointId = parameters.getString(MgcpParameterType.SECOND_ENDPOINT);
    if (secondEndpointId.isPresent() && remoteSdp.isPresent()) {
        throw new MgcpCommandException(MgcpResponseCode.PROTOCOL_ERROR.code(), "Z2 and SDP present in message");
    }// ww  w  .j a va  2s .c om
    return remoteSdp.or("");
}

From source file:gobblin.util.PortUtils.java

/**
 * Finds an open port. {@param portStart} and {@param portEnd} can be absent
 *
 * ______________________________________________________
 * | portStart | portEnd  | takenPort                   |
 * |-----------|----------|-----------------------------|
 * |  absent   | absent   | random                      |
 * |  absent   | provided | 1024 < port <= portEnd      |
 * |  provided | absent   | portStart <= port <= 65535  |
 * |  provided | provided | portStart = port = portEnd  |
 * ------------------------------------------------------
 *
 * @param portStart the inclusive starting port
 * @param portEnd the inclusive ending port
 * @return The selected open port./*from   w  w w  .j  a v a  2 s.c  o m*/
 */
private synchronized Optional<Integer> takePort(Optional<Integer> portStart, Optional<Integer> portEnd) {
    if (!portStart.isPresent() && !portEnd.isPresent()) {
        for (int i = 0; i < 65535; i++) {
            try {
                int port = this.portLocator.random();
                Boolean wasAssigned = assignedPorts.putIfAbsent(port, true);
                if (wasAssigned == null || !wasAssigned) {
                    return Optional.of(port);
                }
            } catch (Exception ignored) {
            }
        }
    }

    for (int port = portStart.or(MINIMUM_PORT); port <= portEnd.or(MAXIMUM_PORT); port++) {
        try {
            this.portLocator.specific(port);
            Boolean wasAssigned = assignedPorts.putIfAbsent(port, true);
            if (wasAssigned == null || !wasAssigned) {
                return Optional.of(port);
            }
        } catch (Exception ignored) {
        }
    }

    throw new RuntimeException(String.format("No open port could be found for %s to %s", portStart, portEnd));
}

From source file:com.abiquo.bond.api.OutboundAPIClient.java

/**
 * The purpose of the constructor is to identify and load plugins.
 *
 * @param data Configuration data for the client. See {@link ConfigurationData} for details of
 *            what data is required.//from ww w  .j  a  va2  s  .com
 * @param version The version indicated by the client
 * @throws OutboundAPIClientException
 */
public OutboundAPIClient(final ConfigurationData data, final File propertiesFile, final String version)
        throws OutboundAPIClientException {
    this.config = new ConfigurationData(data);

    apiconn = new APIConnection(config.getMServer(), config.getMUser(), config.getMUserPassword());
    currUserEditLink = apiconn.getCurrentUserLink();
    String apiVersion = apiconn.getAPIVersion().trim();
    if (!apiVersion.trim().equalsIgnoreCase(version)) {
        throw new OutboundAPIClientException(String.format(
                "Api version indicated to start plugin (%s) mismatch with api version in use (%s)", version,
                apiVersion));
    }

    // Create a cache of the REST links associated with each VM
    mapNameToVMLinks = new NameToVMLinks(config.getMServer(), config.getMUser(), config.getMUserPassword());

    Properties properties = new Properties();
    try {
        FileInputStream inputStream = new FileInputStream(propertiesFile);
        properties.load(inputStream);
    } catch (IOException e) {
        Throwables.propagate(e);
    }

    long timePeriod = new Long(properties.getProperty("avbc_responses_handler_period", "10")).longValue();
    String timeUnitValue = properties.getProperty("avbc_responses_handler_timeunit", "minutes");
    Optional<TimeUnit> timeUnitEnum = Enums.getIfPresent(TimeUnit.class, timeUnitValue.toUpperCase());
    if (!timeUnitEnum.isPresent()) {
        logger.warn("{} is not a valid java.util.concurrent.TimeUnit, using MINUTES as default", timeUnitValue);
    }
    TimeUnit timeUnit = timeUnitEnum.or(TimeUnit.MINUTES);

    // Set up response handlers to fetch data from the third party applications and update
    // Abiquo server with it
    // We need to get the repeat time from the configuration at some point - for now default it
    // to 10 minutes.
    responses = new ResponsesHandler(config.getMServer(), config.getMUser(), config.getMUserPassword(),
            mapNameToVMLinks, timePeriod, timeUnit);

    // Find and load any plugins on the classpath that support the returning of data from the
    // third party app to Abiquo. At the moment this just means Backup plugins
    Set<PluginInterface> plugins = new HashSet<>();
    ServiceLoader<BackupPluginInterface> bsl = ServiceLoader.load(BackupPluginInterface.class);
    Iterator<BackupPluginInterface> biterator = bsl.iterator();
    while (biterator.hasNext()) {
        try {
            BackupPluginInterface handler = biterator.next();
            logger.info("Loaded backup plugin: " + handler.getName());
            plugins.add(handler);
            handlersWithResponses.add(handler);
            // responses.addBackupPlugin(handler);
        } catch (Throwable t) {
            logger.error("Loading of plugin failed", t);
            failures.add(t);
        }
    }

    // Find and load all other plugins
    ServiceLoader<PluginInterface> sl = ServiceLoader.load(PluginInterface.class);
    Iterator<PluginInterface> iterator = sl.iterator();
    while (iterator.hasNext()) {
        try {
            PluginInterface handler = iterator.next();
            logger.info("Loaded plugin: " + handler.getName());
            plugins.add(handler);
        } catch (Throwable t) {
            logger.error("Loading of plugin failed", t);
            failures.add(t);
        }
    }

    handlers = Collections.unmodifiableSet(plugins);

    eventDispatcher = new EventDispatcher(handlers, 1);

    // Initialise the class that will fecth events from the permanent store that may have been
    // missed since the last time the client was run
    eventstore = new EventStore(config.getMServer(), config.getMUser(), config.getMUserPassword(),
            currUserEditLink, mapNameToVMLinks);
}

From source file:org.apache.james.mailbox.store.mail.model.impl.MessageParser.java

private MessageAttachment retrieveAttachment(MessageWriter messageWriter, Entity entity) throws IOException {
    Optional<ContentTypeField> contentTypeField = getContentTypeField(entity);
    Optional<String> contentType = contentType(contentTypeField);
    Optional<String> name = name(contentTypeField);
    Optional<Cid> cid = cid(castField(entity.getHeader().getField(CONTENT_ID), ContentIdField.class));
    boolean isInline = isInline(
            castField(entity.getHeader().getField(CONTENT_DISPOSITION), ContentDispositionField.class));

    return MessageAttachment.builder()
            .attachment(Attachment.builder().bytes(getBytes(messageWriter, entity.getBody()))
                    .type(contentType.or(DEFAULT_CONTENT_TYPE)).build())
            .name(name.orNull()).cid(cid.orNull()).isInline(isInline).build();
}

From source file:com.iskrembilen.quasseldroid.util.QuasseldroidNotificationManager.java

public Notification getConnectingNotification(Optional<String> status) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.stat_connecting).setContentTitle(context.getText(R.string.app_name))
            .setContentText(status.or(context.getText(R.string.notification_connecting).toString()))
            .setPriority(NotificationCompat.PRIORITY_LOW).setWhen(System.currentTimeMillis());

    Intent launch = new Intent(context, MainActivity.class);
    launch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    if (contentIntent != null)
        contentIntent.cancel();// www . ja  v a  2s .co m
    contentIntent = PendingIntent.getActivity(context, 0, launch, 0);
    builder.setContentIntent(contentIntent);
    builder.setColor(context.getResources().getColor(R.color.primary));
    return builder.build();

}

From source file:hihex.cs.Config.java

public Optional<Writer> startRecording(final int pid, final Optional<String> processName, final Date timestamp)
        throws IOException {
    final Writer[] optWriter = { null };
    try {/*from   w w w  .java 2s .c o  m*/
        pidDatabase.startRecording(pid, processName, logFiles, timestamp, new Function<PidEntry, Void>() {
            @Override
            public Void apply(final PidEntry entry) {
                final Writer writer = entry.writer.get();
                optWriter[0] = writer;
                try {
                    renderer.writeHeader(writer, entry.pid, processName.or(entry.processName), timestamp);
                } catch (final IOException e) {
                    throw new UncheckedExecutionException(e);
                }
                return null;
            }
        });
    } catch (final UncheckedExecutionException e) {
        final Throwable cause = e.getCause();
        Throwables.propagateIfInstanceOf(cause, IOException.class);
        throw Throwables.propagate(cause);
    }
    Events.bus.post(new Events.RecordCount(pidDatabase.countRecordingEntries()));
    return Optional.fromNullable(optWriter[0]);
}

From source file:info.archinnov.achilles.internal.statement.prepared.PreparedStatementBinder.java

public BoundStatementWrapper bindForInsert(PreparedStatement ps, EntityMeta entityMeta, Object entity,
        ConsistencyLevel consistencyLevel, Optional<Integer> ttlO) {
    log.trace("Bind prepared statement {} for insert of entity {}", ps.getQueryString(), entity);
    List<Object> values = new ArrayList<>();
    Object primaryKey = entityMeta.getPrimaryKey(entity);
    values.addAll(bindPrimaryKey(primaryKey, entityMeta.getIdMeta()));

    List<PropertyMeta> fieldMetas = new ArrayList<>(entityMeta.getColumnsMetaToInsert());

    for (PropertyMeta pm : fieldMetas) {
        Object value = pm.getAndEncodeValueForCassandra(entity);
        values.add(value);/*from ww  w. ja  va  2 s  . c om*/
    }

    // TTL or default value 0
    values.add(ttlO.or(0));
    BoundStatement bs = ps.bind(values.toArray());
    return new BoundStatementWrapper(bs, values.toArray(), getCQLLevel(consistencyLevel));
}

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

@NonNull
@Override/*from www.jav a 2 s . co m*/
public Optional<List<TextWithLocale>> getAnnouncement(Intent intent) {
    CharSequence sender = intent.getCharSequenceExtra(EXTRA_SENDER);
    if (TextUtils.isEmpty(sender)) {
        throw new IllegalArgumentException("Sender must not be empty: " + sender);
    }

    // We don't always get the subject from Google Inbox
    CharSequence subject = intent.getCharSequenceExtra(EXTRA_SUBJECT);

    // It's OK for the body to be empty; we don't always get it and we don't need to present it
    CharSequence body = intent.getCharSequenceExtra(EXTRA_BODY);

    Optional<Locale> emailLocale = identifyLanguage(subject);
    boolean hasBody = !TextUtils.isEmpty(body);
    if (hasBody && !emailLocale.isPresent()) {
        emailLocale = identifyLanguage(body);
        if (emailLocale.isPresent()) {
            Timber.d("Email locale identified from body: %s", emailLocale.get());
        } else {
            Timber.d("Failed to identify email locale from body");
        }
    }

    Translations translations = new Translations(context, emailLocale.or(Locale.getDefault()),
            R.string.email_from_who_colon_subject, R.string.email_from_whom);
    if (TextUtils.isEmpty(subject)) {
        return Optional.of(translations.format(R.string.email_from_whom, sender));
    } else {
        return Optional.of(translations.format(R.string.email_from_who_colon_subject, sender,
                emailLocale.or(Locale.getDefault()), subject));
    }
}

From source file:de.azapps.mirakel.model.task.TaskBase.java

public void setReminder(final @NonNull Optional<Calendar> newReminder, final boolean force) {
    if (this.reminder.or(new GregorianCalendar()).equals(newReminder.or(new GregorianCalendar())) && !force) {
        return;//  w ww .ja v a2  s  . c o m
    }
    this.reminder = newReminder;
    this.edited.put(TaskBase.REMINDER, true);
    if (!newReminder.isPresent()) {
        setRecurringReminder(-1L);
    }
}