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.opendaylight.vtn.manager.it.util.inventory.InventoryUtils.java

/**
 * Determine whether the given node has at least one edge port in up state
 * or not./*ww w  .j  a v a  2  s.  c om*/
 *
 * @param rtx  A read-only MD-SAL datastore transaction.
 * @param nid  The node identifier string.
 * @return  {@code true} is returned if the given node has at least one
 *          edge port in up state. Otherwise {@code false} is returned.
 */
public static boolean hasEdgePort(ReadTransaction rtx, String nid) {
    Optional<VtnNode> opt = DataStoreUtils.read(rtx, getVtnNodeIdentifier(nid));
    return (opt.isPresent()) ? hasEdgePort(opt.get()) : false;
}

From source file:com.google.devtools.build.lib.bazel.repository.downloader.HttpConnection.java

/**
 * Attempts to detect the encoding the HTTP reponse is using.
 *
 * <p>This attempts to read the Content-Encoding header, then the Content-Type header,
 * then just falls back to UTF-8.</p>
 *
 * @throws IOException If something goes wrong (the encoding isn't parsable or is, but isn't
 * supported by the system)./* ww w  . ja va2 s. c  o m*/
 */
@VisibleForTesting
static Charset getEncoding(HttpURLConnection connection) throws IOException {
    String encoding = connection.getContentEncoding();
    if (encoding != null) {
        if (Charset.availableCharsets().containsKey(encoding)) {
            try {
                return Charset.forName(encoding);
            } catch (IllegalArgumentException | UnsupportedOperationException e) {
                throw new IOException("Got invalid encoding from " + connection.getURL() + ": " + encoding);
            }
        } else {
            throw new IOException("Got unavailable encoding from " + connection.getURL() + ": " + encoding);
        }
    }
    encoding = connection.getContentType();
    if (encoding == null) {
        return StandardCharsets.UTF_8;
    }
    try {
        MediaType mediaType = MediaType.parse(encoding);
        if (mediaType == null) {
            return StandardCharsets.UTF_8;
        }
        Optional<Charset> charset = mediaType.charset();
        if (charset.isPresent()) {
            return charset.get();
        }
    } catch (IllegalArgumentException | IllegalStateException e) {
        throw new IOException("Got invalid encoding from " + connection.getURL() + ": " + encoding);
    }
    return StandardCharsets.UTF_8;
}

From source file:io.mesosphere.mesos.frameworks.cassandra.framework.Main.java

static String frameworkName(final Optional<String> clusterName) {
    if (clusterName.isPresent()) {
        return "cassandra." + clusterName.get();
    } else {//from   w  ww.ja  v  a 2  s .  c  o  m
        return "cassandra";
    }
}

From source file:org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNodes.java

public static <T extends StoreTreeNode<T>> Entry<YangInstanceIdentifier, T> findClosestsOrFirstMatch(
        final T tree, final YangInstanceIdentifier path, final Predicate<T> predicate) {
    Optional<T> parent = Optional.of(tree);
    Optional<T> current = Optional.of(tree);

    int nesting = 0;
    Iterator<PathArgument> pathIter = path.getPathArguments().iterator();
    while (current.isPresent() && pathIter.hasNext() && !predicate.apply(current.get())) {
        parent = current;/* www  .j a  v  a2  s  . co m*/
        current = current.get().getChild(pathIter.next());
        nesting++;
    }
    if (current.isPresent()) {
        final YangInstanceIdentifier currentPath = path.getAncestor(nesting);
        return new SimpleImmutableEntry<>(currentPath, current.get());
    }

    /*
     * Subtracting 1 from nesting level at this point is safe, because we
     * cannot reach here with nesting == 0: that would mean the above check
     * for current.isPresent() failed, which it cannot, as current is always
     * present. At any rate we verify state just to be on the safe side.
     */
    Verify.verify(nesting > 0);
    return new SimpleImmutableEntry<>(path.getAncestor(nesting - 1), parent.get());
}

From source file:com.eucalyptus.util.async.AsyncRequests.java

private static <A extends BaseMessage, B extends BaseMessage> B sendSync(final ServiceConfiguration config,
        final Optional<CallerContext> callerContext, final A msg) throws Exception {
    if (callerContext.isPresent()) {
        callerContext.get().apply(msg);/*  w  ww. j a  v  a 2s . com*/
    }

    if (config.isVmLocal()) {
        return ServiceContext.send(config.getComponentId(), msg);
    } else {
        try {
            Request<A, B> req = newRequest(new MessageCallback<A, B>() {
                {
                    this.setRequest(msg);
                }

                @Override
                public void fire(B msg) {
                    Logs.extreme().debug(msg.toSimpleString());
                }
            });
            return req.sendSync(config);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
            throw ex;
        }
    }
}

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

/**
 * Find a single resource with given rdf:type in the model if one is present.
 *
 * @param model model to search in/*from w  w  w . j a va 2  s  .c  o  m*/
 * @param type  type of required resource
 * @return the resource if present
 * @throws IllegalArgumentException if multiple resources with matching type are found
 */
static Optional<Resource> findSingleOfType(final Model model, final Resource type) {
    final ResIterator it = model.listResourcesWithProperty(RDF.type, type);
    final Optional<Resource> found = it.hasNext() ? Optional.of(it.nextResource())
            : Optional.<Resource>absent();
    if (found.isPresent() && it.hasNext()) {
        throw new IllegalArgumentException("found multiple <" + type + "> resources");
    }
    return found;
}

From source file:google.registry.request.RequestParameters.java

/**
 * Returns first request parameter associated with {@code name} parsed as an optional
 * {@link InetAddress} (which might be IPv6).
 *
 * @throws BadRequestException if request parameter named {@code name} is present but could not
 *     be parsed as an {@link InetAddress}
 *///from   w w  w  .ja v a 2  s .c  o  m
public static Optional<InetAddress> extractOptionalInetAddressParameter(HttpServletRequest req, String name) {
    Optional<String> paramVal = extractOptionalParameter(req, name);
    if (!paramVal.isPresent()) {
        return Optional.absent();
    }
    try {
        return Optional.of(InetAddresses.forString(paramVal.get()));
    } catch (IllegalArgumentException e) {
        throw new BadRequestException("Not an IPv4 or IPv6 address: " + name);
    }
}

From source file:dagger2.internal.codegen.Util.java

/**
 * Wraps an {@link Optional} of a type in an {@code Optional} of a {@link Wrapper} for that type.
 *//*from   w w  w . ja v a2s  .c  om*/
static <T> Optional<Equivalence.Wrapper<T>> wrapOptionalInEquivalence(Equivalence<T> equivalence,
        Optional<T> optional) {
    return optional.isPresent() ? Optional.of(equivalence.wrap(optional.get()))
            : Optional.<Equivalence.Wrapper<T>>absent();
}

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

/**
 * Replace any existing {@link de.fuberlin.wiwiss.d2rq.vocab.D2RConfig#baseURI} with the given.
 * If no {@link de.fuberlin.wiwiss.d2rq.vocab.D2RConfig#Server} is present, create one and attach the given uri.
 *
 * @param model   given configuration/*from   w ww  .j  av  a2  s.c  om*/
 * @param baseUri uri that should be injected
 * @return modified model
 */
static Model injectBaseUri(final Model model, final String baseUri) {
    final Optional<Resource> maybeServer = D2rqTools.findSingleOfType(model, D2RConfig.Server);
    final Resource server;
    if (maybeServer.isPresent()) {
        server = maybeServer.get();
    } else { // create an empty one
        server = model.createResource().addProperty(RDF.type, D2RConfig.Server);
    }
    server.removeAll(D2RConfig.baseURI);
    server.addProperty(D2RConfig.baseURI, model.createResource(baseUri));
    return model;
}

From source file:org.opendaylight.controller.netconf.util.messages.NetconfMessageAdditionalHeader.java

public static String toString(String userName, String hostAddress, String port, String transport,
        Optional<String> sessionIdentifier) {
    Preconditions.checkNotNull(userName);
    Preconditions.checkNotNull(hostAddress);
    Preconditions.checkNotNull(port);//from  w ww  .  j  av a2s  . co m
    Preconditions.checkNotNull(transport);
    String identifier = sessionIdentifier.isPresent() ? sessionIdentifier.get() : "";
    return "[" + userName + SC + hostAddress + ":" + port + SC + transport + SC + identifier + SC + "]"
            + System.lineSeparator();
}