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

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

Introduction

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

Prototype

public abstract boolean isPresent();

Source Link

Document

Returns true if this holder contains a (non-null) instance.

Usage

From source file:org.openqa.selenium.testing.drivers.ExternalDriverSupplier.java

private static Optional<Supplier<WebDriver>> createDelegate(Capabilities desiredCapabilities,
        Capabilities requiredCapabilities) {
    Optional<Class<? extends Supplier>> supplierClass = getDelegateClass();
    if (supplierClass.isPresent()) {
        Class<? extends Supplier> clazz = supplierClass.get();
        logger.info("Using delegate supplier: " + clazz.getName());
        try {//from   w w w  . ja  v  a  2 s .  c  o m
            @SuppressWarnings("unchecked")
            Constructor<Supplier<WebDriver>> ctor = (Constructor<Supplier<WebDriver>>) clazz
                    .getConstructor(Capabilities.class, Capabilities.class);
            return Optional.of(ctor.newInstance(desiredCapabilities, requiredCapabilities));
        } catch (InvocationTargetException e) {
            throw Throwables.propagate(e.getTargetException());
        } catch (Exception e) {
            throw Throwables.propagate(e);
        }
    }
    return Optional.absent();
}

From source file:org.locationtech.geogig.cli.app.Logging.java

static void tryConfigureLogging(Platform platform, @Nullable final String repoURI) {
    System.setProperty("hsqldb.reconfig_logging", "false"); // stop hsql from reseting logging
    // instantiate and call ResolveGeogigDir directly to avoid calling getGeogig() and hence get
    // some logging events before having configured logging
    Hints hints = new Hints();
    try {/*w w w. j a v a  2  s. c  om*/
        if (repoURI != null) {
            URI uri = new URI(repoURI);
            hints.set(Hints.REPOSITORY_URL, uri);
        }
    } catch (URISyntaxException ignore) {
        // not our call to do anything with a wrong URI here
    }
    final Optional<URI> geogigDirUrl = new ResolveGeogigURI(platform, hints).call();
    if (!geogigDirUrl.isPresent() || !"file".equalsIgnoreCase(geogigDirUrl.get().getScheme())) {
        // redirect java.util.logging to SLF4J anyways
        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();
        return;
    }

    final File geogigDir = new File(geogigDirUrl.get());

    if (repoURI == null && geogigDir.equals(geogigDirLoggingConfiguration)) {
        return;
    }

    if (!geogigDir.exists() || !geogigDir.isDirectory()) {
        return;
    }
    final URL loggingFile = getOrCreateLoggingConfigFile(geogigDir);

    if (loggingFile == null) {
        return;
    }

    try {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        loggerContext.reset();
        /*
         * Set the geogigdir variable for the config file can resolve the default location
         * ${geogigdir}/log/geogig.log
         */
        loggerContext.putProperty("geogigdir", geogigDir.getAbsolutePath());
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(loggerContext);
        configurator.doConfigure(loggingFile);

        // redirect java.util.logging to SLF4J
        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();
        geogigDirLoggingConfiguration = geogigDir;
    } catch (JoranException e) {
        LOGGER.error("Error configuring logging from file {}. '{}'", loggingFile, e.getMessage(), e);
    }
}

From source file:io.mesosphere.mesos.util.ProtoUtils.java

@NotNull
public static Optional<Double> resourceValueDouble(@NotNull final Optional<Resource> resource) {
    if (resource.isPresent()) {
        if (resource.get().getType() != Value.Type.SCALAR) {
            throw new IllegalArgumentException("Resource must be of type SCALAR");
        }//w  w  w  .  j  a v a2  s.  co m
        return Optional.of(resource.get().getScalar().getValue());
    } else {
        return Optional.absent();
    }
}

From source file:org.opendaylight.netconf.cli.CommandArgHandlerRegistry.java

private static SchemaContext getRemoteSchema(final Class<?> handlerType,
        final SchemaContextRegistry schemaContextRegistry) {
    final Optional<SchemaContext> remoteSchemaContext = schemaContextRegistry.getRemoteSchemaContext();
    Preconditions.checkState(remoteSchemaContext.isPresent(),
            "Remote schema context not acquired yet, cannot get handler %s", handlerType);
    return remoteSchemaContext.get();
}

From source file:org.opendaylight.vbd.impl.transaction.VbdNetconfTransaction.java

/**
 * Remove data from remote device. Data are read and deleted only if exist. Transaction is restarted if failed.
 *
 * @param mountpoint   to access remote device
 * @param iid          data identifier// w  w w  . ja v a  2  s .c o m
 * @param retryCounter number of attempts
 * @param <T>          generic data type. Has to be child of {@link DataObject}
 * @return true if transaction is successful, false otherwise
 */
public synchronized static <T extends DataObject> boolean deleteIfExists(final DataBroker mountpoint,
        final InstanceIdentifier<T> iid, byte retryCounter) {
    LOG.trace("Netconf DELETE transaction started. Data will be read at first. RetryCounter: {}", retryCounter);
    Preconditions.checkNotNull(mountpoint);
    final Optional<T> optionalObject = read(mountpoint, LogicalDatastoreType.CONFIGURATION, iid, RETRY_COUNT);
    if (!optionalObject.isPresent()) {
        LOG.warn(
                "Netconf DELETE transaction aborted. Data to remove are not present or cannot be read. Iid: {}",
                iid);
        // Return true, this state is not considered as an error
        return true;
    }
    final ReadWriteTransaction rwTx = mountpoint.newReadWriteTransaction();
    try {
        rwTx.delete(LogicalDatastoreType.CONFIGURATION, iid);
        final CheckedFuture<Void, TransactionCommitFailedException> futureTask = rwTx.submit();
        futureTask.get();
        LOG.trace("Netconf DELETE transaction done for {}", iid);
        return true;
    } catch (Exception e) {
        // Retry
        if (retryCounter > 0) {
            LOG.warn("Netconf DELETE transaction failed to {}. Restarting transaction ... ", e.getMessage());
            return deleteIfExists(mountpoint, iid, --retryCounter);
        } else {
            LOG.warn("Netconf DELETE transaction unsuccessful. Maximal number of attempts reached. Trace: {}",
                    e);
            return false;
        }
    }
}

From source file:io.mesosphere.mesos.util.ProtoUtils.java

@NotNull
public static Optional<Long> resourceValueLong(@NotNull final Optional<Resource> resource) {
    if (resource.isPresent()) {
        if (resource.get().getType() != Value.Type.SCALAR) {
            throw new IllegalArgumentException("Resource must be of type SCALAR");
        }//from   w  w w. j  a v  a2s  . co m
        final long value = (long) resource.get().getScalar().getValue();
        return Optional.of(value);
    } else {
        return Optional.absent();
    }
}

From source file:org.opendaylight.controller.md.sal.dom.store.impl.tree.data.StoreMetadataNode.java

public static Optional<StoreMetadataNode> getChild(final Optional<StoreMetadataNode> parent,
        final PathArgument child) {
    if (parent.isPresent()) {
        return parent.get().getChild(child);
    }//from   w w  w  . j  a  v  a2 s  .co m
    return Optional.absent();
}

From source file:org.ldp4j.tutorial.frontend.person.PersonMapper.java

static Typed<Person> toPerson(Individual<?, ?> individual) {
    MutablePerson person = new MutablePerson();
    Typed<Person> result = Typed.<Person>create(person);
    for (URI uri : Mapper.create(individual).types()) {
        result.withType(uri.toString());
    }/*from  w  ww .j  a v  a2s . c  o m*/
    Optional<URI> email = Optional.fromNullable(firstIndividualValue(individual, EMAIL));
    person.setEmail(email.isPresent() ? email.get().toString() : null);
    person.setName(firstLiteralValue(individual, NAME, String.class));
    Optional<URI> location = Optional.fromNullable(firstIndividualValue(individual, LOCATION));
    person.setLocation(location.isPresent() ? location.get().toString() : null);
    Optional<URI> workplaceHomepage = Optional
            .fromNullable(firstIndividualValue(individual, WORKPLACE_HOMEPAGE));
    person.setWorkplaceHomepage(workplaceHomepage.isPresent() ? workplaceHomepage.get().toString() : null);
    return result;
}

From source file:com.facebook.buck.testutil.MoreAsserts.java

public static <T> void assertOptionalValueEquals(String userMessage, T expectedValue,
        Optional<T> optionalValue) {
    if (!optionalValue.isPresent()) {
        failWith(userMessage, "Optional value is not present.");
    }//www .j  a v a  2s  . c  o  m

    assertEquals(userMessage, expectedValue, optionalValue.get());
}

From source file:org.opendaylight.controller.config.yangjmxgenerator.plugin.CodeWriter.java

private static List<File> persistGeneratedObjects(final File targetBaseDir, final File mainBaseDir,
        final Map<GeneratedObject, Boolean> gos) throws IOException {
    List<File> generatedFiles = new ArrayList<>();
    for (Entry<GeneratedObject, Boolean> entry : gos.entrySet()) {
        boolean overwrite = entry.getValue();
        File dst;/*from  w  ww  . j a va  2s . co  m*/
        if (overwrite) {
            dst = targetBaseDir;
        } else {
            dst = mainBaseDir;
        }
        Optional<Entry<FullyQualifiedName, File>> maybePersistEntry = entry.getKey().persist(dst, overwrite);

        if (maybePersistEntry.isPresent()) {
            generatedFiles.add(maybePersistEntry.get().getValue());
        }
    }
    return generatedFiles;
}