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:bear.task.TaskResult.java

public static <T extends TaskResult<?>> Optional<T> okOrAbsent(@Nonnull Optional<T> result) {
    Preconditions.checkNotNull(result);//from  www  .  j  a  v  a  2 s  .  c  om

    if (!result.isPresent() || !result.get().ok())
        return Optional.absent();

    return result;
}

From source file:org.onos.yangtools.yang.data.impl.schema.tree.AbstractDataTreeCandidateNode.java

static Collection<DataTreeCandidateNode> deltaChildren(
        @Nullable final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> oldData,
        @Nullable final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> newData) {
    if (newData == null) {
        return Collections2.transform(oldData.getValue(), TO_DELETED_NODE);
    }//from  w w w  .ja v  a 2s .com
    if (oldData == null) {
        return Collections2.transform(newData.getValue(), TO_WRITTEN_NODE);
    }

    /*
     * This is slightly inefficient, as it requires N*F(M)+M*F(N) lookup operations, where
     * F is dependent on the implementation of NormalizedNodeContainer.getChild().
     *
     * We build the return collection by iterating over new data and looking each child up
     * in old data. Based on that we construct replaced/written nodes. We then proceed to
     * iterate over old data and looking up each child in new data.
     */
    final Collection<DataTreeCandidateNode> result = new ArrayList<>();
    for (NormalizedNode<?, ?> child : newData.getValue()) {
        final DataTreeCandidateNode node;
        final Optional<NormalizedNode<?, ?>> maybeOldChild = oldData.getChild(child.getIdentifier());

        if (maybeOldChild.isPresent()) {
            // This does not find children which have not in fact been modified, as doing that
            // reliably would require us running a full equals() on the two nodes.
            node = AbstractRecursiveCandidateNode.replaceNode(maybeOldChild.get(), child);
        } else {
            node = AbstractRecursiveCandidateNode.writeNode(child);
        }

        result.add(node);
    }

    // Process removals next, looking into new data to see if we processed it
    for (NormalizedNode<?, ?> child : oldData.getValue()) {
        if (!newData.getChild(child.getIdentifier()).isPresent()) {
            result.add(AbstractRecursiveCandidateNode.deleteNode(child));
        }
    }

    return result;
}

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

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

    int nesting = 0;
    Iterator<PathArgument> pathIter = path.getPath().iterator();
    while (current.isPresent() && pathIter.hasNext() && !predicate.apply(current.get())) {
        parent = current;/* w ww  .j  a v  a  2s.c o  m*/
        current = current.get().getChild(pathIter.next());
        nesting++;
    }
    if (current.isPresent()) {
        final InstanceIdentifier currentPath = new InstanceIdentifier(path.getPath().subList(0, nesting));
        return new SimpleEntry<InstanceIdentifier, T>(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 check state just to be on the safe side.
     */
    Preconditions.checkState(nesting > 0);
    final InstanceIdentifier parentPath = new InstanceIdentifier(path.getPath().subList(0, nesting - 1));

    return new SimpleEntry<InstanceIdentifier, T>(parentPath, parent.get());
}

From source file:com.publicuhc.pluginframework.util.YamlUtil.java

/**
 * Loads the given file from the harddrive with it's defaults set to the JAR version (and saved to the HDD)
 *
 * @param path the path to the file to load
 * @param loader the classloader to load from
 * @param dataDir the directory to save/load from
 *
 * @return optional fileconfiguration. Absent if jar AND hdd version don't exist
 * @throws IOException/*from   w w w  .j  a va2  s. co  m*/
 * @throws InvalidConfigurationException if HDD or JAR file failed to parse
 */
public static Optional<FileConfiguration> loadConfigWithDefaults(String path, ClassLoader loader, File dataDir)
        throws IOException, InvalidConfigurationException {
    Optional<YamlConfiguration> jarOptional = YamlUtil.loadYamlFromJAR(path, loader);

    Optional<YamlConfiguration> hardDriveOptional = YamlUtil.loadYamlFromDir(path, dataDir);

    if (!hardDriveOptional.isPresent() && !jarOptional.isPresent()) {
        return Optional.absent();
    }

    YamlConfiguration hardDrive = hardDriveOptional.or(new YamlConfiguration());

    if (jarOptional.isPresent()) {
        YamlConfiguration jar = jarOptional.get();
        hardDrive.setDefaults(jar);
        hardDrive.options().copyDefaults(true);
    }

    YamlUtil.saveConfiguration(hardDrive, dataDir, path);

    return Optional.of((FileConfiguration) hardDrive);
}

From source file:org.apache.gobblin.metrics.event.EventSubmitter.java

/**
 * Calls submit on submitter if present.
 *//*  ww  w .  j a v a2 s  . c  o m*/
public static void submit(Optional<EventSubmitter> submitter, String name,
        Map<String, String> additionalMetadata) {
    if (submitter.isPresent()) {
        submitter.get().submit(name, additionalMetadata);
    }
}

From source file:org.opendaylight.faas.fabrics.vxlan.adapters.ovs.utils.OfFlowUtils.java

public static Flow getFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder, ReadOnlyTransaction readTx,
        final LogicalDatastoreType store) {
    try {//from  w  ww. j  a v a2 s.c  om
        Optional<Flow> data = readTx.read(store, createFlowPath(flowBuilder, nodeBuilder)).get();
        if (data.isPresent()) {
            return data.get();
        }
    } catch (InterruptedException | ExecutionException e) {
        LOG.error("Failed to get flow {}", flowBuilder.getFlowName(), e);
    }

    LOG.info("Cannot find data for Flow {} in {}", flowBuilder.getFlowName(), store);
    return null;
}

From source file:com.complexible.common.collect.Iterators2.java

public static <T> Iterator<T> present(final Iterator<Optional<T>> theIter) {
    return new AbstractIterator<T>() {
        @Override//w  w w  . jav a  2 s  .co  m
        protected T computeNext() {
            while (theIter.hasNext()) {
                Optional<T> aOptional = theIter.next();
                if (aOptional.isPresent()) {
                    return aOptional.get();
                }
            }
            return endOfData();
        }
    };
}

From source file:jcomposition.processor.utils.AnnotationUtils.java

public static TypeElement getBindClassType(TypeElement element, ProcessingEnvironment env) {
    Optional<AnnotationValue> value = getParameterFrom(element, Bind.class, "value", env);

    if (value.isPresent()) {
        TypeElement typeElement = MoreTypes.asTypeElement((Type) value.get().getValue());
        AnnotationMirror bindMirror = MoreElements.getAnnotationMirror(typeElement, Bind.class).orNull();

        if (!typeElement.getKind().isClass()) {
            env.getMessager().printMessage(Diagnostic.Kind.ERROR, "Bind's annotation value must be class",
                    element, bindMirror, value.get());

            return null;
        }//from ww w .  j  av  a 2  s.  c  o m

        /**
         * Bind annotation is not valid if Bind's class value isn't implements element interface
         */
        javax.lang.model.util.Types types = env.getTypeUtils();

        if (!types.isAssignable(types.getDeclaredType(typeElement), types.getDeclaredType(element))
                && !types.isAssignable(typeElement.getSuperclass(), element.asType())) {
            env.getMessager().printMessage(Diagnostic.Kind.ERROR,
                    "Bind's annotation value class must implement " + element.getSimpleName() + " interface",
                    element, bindMirror, value.get());

            return null;
        }

        return typeElement;
    }

    return null;
}

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

@NotNull
public static Credential getCredential(@NotNull final String principal,
        @NotNull final Optional<String> secret) {
    if (secret.isPresent()) {
        return Credential.newBuilder().setPrincipal(principal)
                .setSecret(ByteString.copyFrom(secret.get().getBytes())).build();
    } else {/*from   w  w  w.  j  a  va  2 s  .co  m*/
        return Credential.newBuilder().setPrincipal(principal).build();
    }
}

From source file:org.opendaylight.netconf.console.utils.NetconfConsoleUtils.java

/**
 * Blocking read transaction//from   w w w .  j av  a 2s . co  m
 * @param store :DatastoreType
 * @param path :InstanceIdentifier
 * @param db :An instance of the {@link DataBroker}
 * @return :data read from path
 */
public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> D read(
        final LogicalDatastoreType store, final InstanceIdentifier<D> path, final DataBroker db) {
    D result = null;
    final ReadOnlyTransaction transaction = db.newReadOnlyTransaction();
    Optional<D> optionalData;
    try {
        optionalData = transaction.read(store, path).checkedGet();
        if (optionalData.isPresent()) {
            result = optionalData.get();
        } else {
            LOG.debug("{}: Failed to read {}", Thread.currentThread().getStackTrace()[1], path);
        }
    } catch (ReadFailedException e) {
        LOG.warn("Failed to read {} ", path, e);
    }
    transaction.close();
    return result;
}