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.yangtools.yang.data.api.schema.tree.StoreTreeNodes.java

/**
 * Finds a node in tree//from  w ww. jav  a  2  s.  c o  m
 * @param <T>
 *          Store tree node type.
 * @param tree Data Tree
 * @param path Path to the node
 * @return Optional with node if the node is present in tree, {@link Optional#absent()} otherwise.
 */
public static <T extends StoreTreeNode<T>> Optional<T> findNode(final T tree,
        final YangInstanceIdentifier path) {
    Optional<T> current = Optional.of(tree);
    Iterator<PathArgument> pathIter = path.getPathArguments().iterator();
    while (current.isPresent() && pathIter.hasNext()) {
        current = current.get().getChild(pathIter.next());
    }
    return current;
}

From source file:org.eclipse.buildship.core.workspace.internal.BuildCommandUpdater.java

private static Set<ICommand> toCommands(Optional<List<OmniEclipseBuildCommand>> buildCommands,
        IProjectDescription description) {
    Set<ICommand> commands = Sets.newLinkedHashSet();
    if (buildCommands.isPresent()) {
        commands.addAll(toCommands(buildCommands.get(), description));
    } else {/*from w  w w  .j av a2  s.co  m*/
        commands.addAll(Arrays.asList(description.getBuildSpec()));
    }
    commands.add(toCommand(description, GradleProjectBuilder.ID, Collections.<String, String>emptyMap()));
    return commands;
}

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

/**
 * Calls submit on submitter if present.
 *//*from  www  .  ja v  a2  s. c  o  m*/
public static void submit(Optional<EventSubmitter> submitter, String name, String... metadataEls) {
    if (submitter.isPresent()) {
        submitter.get().submit(name, metadataEls);
    }
}

From source file:google.registry.monitoring.whitebox.EppMetric.java

/**
 * Helper method to populate an {@link com.google.common.collect.ImmutableMap.Builder} with an
 * {@link Optional} value if the value is {@link Optional#isPresent()}.
 *//*  ww  w  . ja  v  a 2s . c o m*/
private static <T> void addOptional(String key, Optional<T> value, ImmutableMap.Builder<String, String> map) {
    if (value.isPresent()) {
        map.put(key, value.get().toString());
    }
}

From source file:org.anhonesteffort.flock.sync.key.KeySyncUtil.java

public static HidingCalDavCollection getOrCreateKeyCollection(Context context, DavAccount account)
        throws PropertyParseException, DavException, GeneralSecurityException, IOException {
    Log.d(TAG, "getOrCreateKeyCollection()");

    Optional<HidingCalDavCollection> keyCollection = getKeyCollection(context, account);
    if (keyCollection.isPresent())
        return keyCollection.get();

    HidingCalDavStore store = DavAccountHelper.getHidingCalDavStore(context, account, null);
    Optional<String> calendarHomeSet = store.getCalendarHomeSet();

    if (!calendarHomeSet.isPresent())
        throw new PropertyParseException("No calendar-home-set property found for user.", store.getHostHREF(),
                CalDavConstants.PROPERTY_NAME_CALENDAR_HOME_SET);

    Log.d(TAG, "creating key collection");
    store.addCollection(calendarHomeSet.get().concat(KeySyncUtil.PATH_KEY_COLLECTION));
    keyCollection = store.getCollection(calendarHomeSet.get().concat(KeySyncUtil.PATH_KEY_COLLECTION));

    if (!keyCollection.isPresent())
        throw new DavException(500, "WebDAV server did not create our key collection!");

    return keyCollection.get();
}

From source file:com.bitranger.parknshop.common.recommend.collections.CollectionUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static <E> Iterable<E> fast(final Iterable<E> iter) {
    if (iter instanceof FastIterable) {
        return new Iterable<E>() {
            @Override//from   w w w.  j a va  2  s.c om
            public Iterator<E> iterator() {
                return ((FastIterable) iter).fastIterator();
            }
        };
    } else if (iter instanceof Cursor) {
        throw new IllegalArgumentException();
    } else {
        Optional<Method> fastMethod = fastIteratorMethods.getUnchecked(iter.getClass());
        if (fastMethod.isPresent()) {
            final Method method = fastMethod.get();
            return new Iterable<E>() {
                @Override
                public Iterator<E> iterator() {
                    try {
                        return (Iterator<E>) method.invoke(iter);
                    } catch (IllegalAccessException e) {
                        return iter.iterator();
                    } catch (InvocationTargetException e) {
                        throw Throwables.propagate(e.getCause());
                    }
                }
            };
        } else {
            return iter;
        }
    }
}

From source file:google.registry.flows.host.HostFlowUtils.java

/** Return the {@link DomainResource} this host is subordinate to, or null for external hosts. */
static DomainResource lookupSuperordinateDomain(InternetDomainName hostName, DateTime now) throws EppException {
    Optional<InternetDomainName> tld = findTldForName(hostName);
    if (!tld.isPresent()) {
        // This is an host on a TLD we don't run, therefore obviously external, so we are done.
        return null;
    }// w w w .  j a  va2s .c  o m
    // This is a subordinate host
    String domainName = Joiner.on('.')
            .join(Iterables.skip(hostName.parts(), hostName.parts().size() - (tld.get().parts().size() + 1)));
    DomainResource superordinateDomain = loadByForeignKey(DomainResource.class, domainName, now);
    if (superordinateDomain == null || !isActive(superordinateDomain, now)) {
        throw new SuperordinateDomainDoesNotExistException(domainName);
    }
    return superordinateDomain;
}

From source file:net.pterodactylus.sonitus.io.IdentifyingInputStream.java

/**
 * Tries to identify the given input stream.
 *
 * @param inputStream//from  w w  w .  j  av a 2  s.c  o  m
 *       The input stream to identify
 * @return An identifying input stream that delivers the original stream and
 *         the metadata it detected, or {@link Optional#absent()} if no
 *         metadata could be identified
 * @throws IOException
 *       if an I/O error occurs
 */
public static Optional<IdentifyingInputStream> create(InputStream inputStream) throws IOException {

    /* remember everything we read here. */
    RememberingInputStream rememberingInputStream = new RememberingInputStream(inputStream);

    /* first, try formats with unambiguous layouts. */
    try {
        Optional<Metadata> metadata = FlacIdentifier.identify(rememberingInputStream);
        if (metadata.isPresent()) {
            return Optional.of(new IdentifyingInputStream(rememberingInputStream.remembered(), metadata.get()));
        }
    } catch (EOFException eofe1) {
        /* ignore. */
    }

    /* try Ogg Vorbis next. */
    try {
        rememberingInputStream = new RememberingInputStream(rememberingInputStream.remembered());
        Optional<Metadata> metadata = OggVorbisIdentifier.identify(rememberingInputStream);
        if (metadata.isPresent()) {
            return Optional.of(new IdentifyingInputStream(rememberingInputStream.remembered(), metadata.get()));
        }
    } catch (EOFException eofe1) {
        /* ignore. */
    }

    /* finally, try MP3. */
    try {
        rememberingInputStream = new RememberingInputStream(rememberingInputStream.remembered());
        InputStream limitedInputStream = ByteStreams.limit(rememberingInputStream, 1048576);
        Optional<Metadata> metadata = Mp3Identifier.identify(limitedInputStream);
        if (metadata.isPresent()) {
            return Optional.of(new IdentifyingInputStream(rememberingInputStream.remembered(), metadata.get()));
        }
    } catch (EOFException eofe1) {
        /* ignore. */
    }

    return Optional.absent();
}

From source file:com.android.camera.one.OneCameraModule.java

/**
 * Creates a new camera manager that is based on Camera2 API, if available.
 *
 * @throws OneCameraException Thrown if an error occurred while trying to
 *             access the camera./*  w  w w. ja v  a 2s . c  o m*/
 */
public static OneCameraOpener provideOneCameraOpener(OneCameraFeatureConfig featureConfig, Context context,
        ActiveCameraDeviceTracker activeCameraDeviceTracker, DisplayMetrics displayMetrics)
        throws OneCameraException {
    Optional<OneCameraOpener> manager = Camera2OneCameraOpenerImpl.create(featureConfig, context,
            activeCameraDeviceTracker, displayMetrics);
    if (!manager.isPresent()) {
        manager = LegacyOneCameraOpenerImpl.create();
    }
    if (!manager.isPresent()) {
        throw new OneCameraException("No camera manager is available.");
    }
    return manager.get();
}

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

/**
 * Extract a web service error message from the given throwable.
 *
 * @param throwable The possibly web service caused throwable
 * @param defaultMessage The message to use if a service message is not found
 * @return The message or the default message
 *///from  w w  w  .  j a  va  2  s .  c  o m
public static String asWebServiceErrorMessage(final Throwable throwable, final String defaultMessage) {
    String message = defaultMessage;
    final Optional<AsyncWebServiceError> serviceErrorOption = AsyncExceptions.asWebServiceError(throwable);
    if (serviceErrorOption.isPresent()) {
        message = serviceErrorOption.get().getMessage();
    }
    return message;
}