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.protocol.bgp.flowspec.ipv6.FlowspecIpv6NlriParserHelper.java

private static final List<FlowLabel> createFlowLabels(final UnkeyedListNode flowLabelsData) {
    final List<FlowLabel> flowLabels = new ArrayList<>();

    for (final UnkeyedListEntryNode node : flowLabelsData.getValue()) {
        final FlowLabelBuilder flowLabelsBuilder = new FlowLabelBuilder();
        final Optional<DataContainerChild<? extends PathArgument, ?>> opValue = node
                .getChild(AbstractFlowspecNlriParser.OP_NID);
        if (opValue.isPresent()) {
            flowLabelsBuilder//from  ww  w  .  j  a  v a2s.  c o  m
                    .setOp(NumericOneByteOperandParser.INSTANCE.create((Set<String>) opValue.get().getValue()));
        }
        final Optional<DataContainerChild<? extends PathArgument, ?>> valueNode = node
                .getChild(AbstractFlowspecNlriParser.VALUE_NID);
        if (valueNode.isPresent()) {
            flowLabelsBuilder.setValue((Long) valueNode.get().getValue());
        }
        flowLabels.add(flowLabelsBuilder.build());
    }

    return flowLabels;
}

From source file:org.xacml4j.v30.policy.function.RegularExpressionFunctions.java

private static BooleanExp matches(EvaluationContext context, StringExp regexp, AttributeExp value) {
    if (log.isDebugEnabled()) {
        log.debug("Matching input=\"{}\" via regexp=\"{}\"", value, regexp);
    }//from w  w  w  .jav a 2  s.co  m
    TypeCapability.Index<TypeToString> idx = TypeToString.Types.getIndex();
    Optional<TypeToString> toString = idx.get(value.getType());
    Preconditions.checkState(toString.isPresent());
    return BooleanExp.valueOf(
            Pattern.matches(covertXacmlToJavaSyntax(regexp.getValue()), toString.get().toString(value)));
}

From source file:net.awairo.mcmod.spawnchecker.presetmode.spawncheck.SlimeSpawnChecker.java

private static Optional<Long> findSeed(final Optional<InetSocketAddress> address) {
    if (!address.isPresent())
        return Optional.absent();

    final InetAddress inetAddress = address.get().getAddress();

    final String host = inetAddress.getHostName();
    final String ip = inetAddress.getHostAddress();
    final Integer port = address.get().getPort();

    LOGGER.info("multiplayer server: host={}, ip={}, port={}", host, ip, port);

    return seedConfig().get(host, port).or(seedConfig().get(ip, port));
}

From source file:com.groupon.utility.OvalBuilder.java

/**
 * Static factory initializes the specified builder with state from the
 * source instance.//from   www .j a  va  2s  .  com
 *
 * @param <T>    The type of object created by the builder.
 * @param <B>    The type of builder to return.
 * @param source The source of initial state.
 * @param target The target builder instance.
 * @return Target populated from source.
 */
public static <T, B extends Builder<? super T>> B clone(final T source, final B target) {
    for (final Method targetMethod : target.getClass().getMethods()) {
        if (isSetterMethod(targetMethod)) {
            final Optional<Method> getterMethod = getGetterForSetter(targetMethod, source.getClass());
            if (getterMethod.isPresent()) {
                try {
                    if (!getterMethod.get().isAccessible()) {
                        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                            getterMethod.get().setAccessible(true);
                            return null;
                        });
                    }
                    Object value = getterMethod.get().invoke(source);
                    if (value instanceof Optional) {
                        value = ((Optional) value).orNull();
                    }
                    targetMethod.invoke(target, value);
                } catch (final IllegalAccessException | InvocationTargetException e) {
                    throw Throwables.propagate(e);
                }
            }
        }
    }
    return target;
}

From source file:com.arpnetworking.utility.OvalBuilder.java

/**
 * Static factory initializes the specified builder with state from the
 * source instance.// w w  w.j a v  a  2s .c  om
 *
 * @param <T> The type of object created by the builder.
 * @param <B> The type of builder to return.
 * @param source The source of initial state.
 * @param target The target builder instance.
 * @return Target populated from source.
 */
public static <T, B extends Builder<? super T>> B clone(final T source, final B target) {
    for (final Method targetMethod : target.getClass().getMethods()) {
        if (isSetterMethod(targetMethod)) {
            final Optional<Method> getterMethod = getGetterForSetter(targetMethod, source.getClass());
            if (getterMethod.isPresent()) {
                try {
                    if (!getterMethod.get().isAccessible()) {
                        getterMethod.get().setAccessible(true);
                    }
                    Object value = getterMethod.get().invoke(source);
                    if (value instanceof Optional) {
                        value = ((Optional) value).orNull();
                    }
                    targetMethod.invoke(target, value);
                } catch (final IllegalAccessException | InvocationTargetException e) {
                    Throwables.propagate(e);
                }
            }
        }
    }
    return target;
}

From source file:org.trimou.handlebars.HelperValidator.java

/**
 *
 * @param definition//w  ww .  j a v a2s .c o m
 * @param hashSize
 * @see #checkHash(Class, HelperDefinition, int)
 */
public static void checkHash(HelperDefinition definition, BasicHelper helper) {
    // Number of required hash entries
    checkHash(helper.getClass(), definition, helper.numberOfRequiredHashEntries());
    // Log a warning message if an unsupported hash key is found
    Optional<Set<String>> supportedHashKeys = helper.getSupportedHashKeys();
    if (supportedHashKeys.isPresent()) {
        for (String key : definition.getHash().keySet()) {
            if (!supportedHashKeys.get().contains(key)) {
                logger.info("Unsupported hash key detected [key: {}, helper: {}, template: {}, line: {}]", key,
                        helper.getClass().getName(), definition.getTagInfo().getTemplateName(),
                        definition.getTagInfo().getLine());
            }
        }
    }
}

From source file:google.registry.model.registry.label.PremiumListUtils.java

/**
 * Returns the premium price for the specified label and registry, or absent if the label is not
 * premium.//  w  w w.  ja  v a 2  s  . com
 */
public static Optional<Money> getPremiumPrice(String label, Registry registry) {
    // If the registry has no configured premium list, then no labels are premium.
    if (registry.getPremiumList() == null) {
        return Optional.<Money>absent();
    }
    String listName = registry.getPremiumList().getName();
    Optional<PremiumList> optionalPremiumList = PremiumList.get(listName);
    checkState(optionalPremiumList.isPresent(), "Could not load premium list '%s'", listName);
    PremiumList premiumList = optionalPremiumList.get();
    PremiumListRevision revision;
    try {
        revision = cachePremiumListRevisions.get(premiumList.getRevisionKey());
    } catch (InvalidCacheLoadException | ExecutionException e) {
        throw new RuntimeException("Could not load premium list revision " + premiumList.getRevisionKey(), e);
    }
    checkState(revision.probablePremiumLabels != null,
            "Probable premium labels bloom filter is null on revision '%s'", premiumList.getRevisionKey());

    if (revision.probablePremiumLabels.mightContain(label)) {
        Key<PremiumListEntry> entryKey = Key.create(premiumList.getRevisionKey(), PremiumListEntry.class,
                label);
        try {
            Optional<PremiumListEntry> entry = cachePremiumListEntries.get(entryKey);
            return (entry.isPresent()) ? Optional.of(entry.get().getValue()) : Optional.<Money>absent();
        } catch (InvalidCacheLoadException | ExecutionException e) {
            throw new RuntimeException("Could not load premium list entry " + entryKey, e);
        }
    } else {
        return Optional.<Money>absent();
    }
}

From source file:org.pau.assetmanager.business.ClientsBusiness.java

/**
 * This method removes a client from the database 
 * //  w  w w  .  j a v a2  s . co m
 * @param selectedClient client to remove
 * 
 * @return the client removed
 */
public static Client removeClient(Client selectedClient) {
    String queryBooks = "select book from Book book where book.client=:client";
    List<Book> books = DaoFunction.<Book>querySimpleListFunction("client", selectedClient).apply(queryBooks);
    for (Book book : books) {
        BooksBusiness.removeBook(book);
    }
    String queryClients = "select client from Client client where client=:client";
    Optional<Client> optionalClient = DaoFunction.<Client>querySimpleUniqueFunction("client", selectedClient)
            .apply(queryClients);
    if (optionalClient.isPresent()) {
        Client client = optionalClient.get();
        DaoFunction.deleteDetachedFunction().apply(client);
        return client;
    } else {
        String message = "Client '" + selectedClient.toString() + "' not found in the database";
        logger.error(message);
        throw new AssetManagerRuntimeException(message);
    }
}

From source file:org.apache.rya.api.instance.RyaDetailsToConfiguration.java

/**
 * Ensures a Rya Client will not try to use a secondary index that is not not supported by the Rya Instance
 * it is connecting to./*from w w w  .  j a  v a 2 s .c om*/
 * </p>
 * If the configuration...
 * <ul>
 *   <li>provides an 'on' value for an index that is supported, then nothing changes.</li>
 *   <li>provides an 'off' value for an index that is or is not supported, then nothing changes.</li>
 *   <li>provides an 'on' value for an index that is not supported, then the index is turned
 *       off and a warning is logged.</li>
 *   <li>does not provide any value for an index, then it will be turned on if supported.</li>
 * </ul>
 *
 * @param conf - The {@link Configuration} to potentially change. (not null)
 * @param useIndexField - The field within {@code conf} that indicates if the client will utilize the index. (not null)
 * @param indexSupported - {@code true} if the Rya Instance supports the index; otherwise {@code false}.
 */
private static void checkAndSet(final Configuration conf, final String useIndexField,
        final boolean indexSupported) {
    requireNonNull(conf);
    requireNonNull(useIndexField);

    final Optional<String> useIndexStr = Optional.fromNullable(conf.get(useIndexField));

    // If no value was provided, default to using the index if it is supported.
    if (!useIndexStr.isPresent()) {
        log.info("No Rya Client configuration was provided for the " + useIndexField
                + " index, so it is being defaulted to " + indexSupported);
        conf.setBoolean(useIndexField, indexSupported);
        return;
    }

    // If configured to use the index, but the Rya Instance does not support it, then turn it off.
    final boolean useIndex = Boolean.parseBoolean(useIndexStr.get());
    if (useIndex && !indexSupported) {
        log.warn(
                "The Rya Client indicates it wants to use a secondary index that the Rya Instance does not support. "
                        + "This is not allowed, so the index will be turned off. Index Configuration Field: "
                        + useIndexField);
        conf.setBoolean(useIndexField, false);
    }

    // Otherwise use whatever the Client wants to use.
}

From source file:org.gradle.model.internal.core.ModelTypeInitializationException.java

private static String toMessage(NodeInitializerContext context, ModelSchemaStore schemaStore,
        Iterable<ModelType<?>> scalarTypes, Iterable<ModelType<?>> constructableTypes) {
    Optional<ModelProperty<?>> modelPropertyOptional = context.getModelProperty();
    StringBuilder s = new StringBuilder();
    if (modelPropertyOptional.isPresent()) {
        s.append(String.format("A model element of type: '%s' can not be constructed.%n",
                context.getDeclaringType().get().getName()));
        ModelProperty<?> modelProperty = modelPropertyOptional.get();
        if (isManagedCollection(modelProperty.getType())) {
            s.append(String.format("Its property '%s %s' is not a valid managed collection%n",
                    modelProperty.getType().getName(), modelProperty.getName()));
            ModelCollectionSchema<?, ?> schema = (ModelCollectionSchema) schemaStore
                    .getSchema(modelProperty.getType());
            s.append(String.format("A managed collection can not contain '%s's%n", schema.getElementType()));
            appendManagedCollections(s, 1, constructableTypes);
        } else if (isAnUnmanagedCollection(modelProperty)) {
            ModelType<?> innerType = modelProperty.getType().getTypeVariables().get(0);
            s.append(String.format("Its property '%s %s' is not a valid scalar collection%n",
                    modelProperty.getType().getName(), modelProperty.getName()));
            s.append(String.format("A scalar collection can not contain '%s's%n", innerType));
            s.append(explainScalarCollections(scalarTypes));
        } else {//from  www.j a v  a 2  s  . com
            s.append(String.format("Its property '%s %s' can not be constructed%n",
                    modelProperty.getType().getName(), modelProperty.getName()));
            s.append(String.format("It must be one of:%n"));
            s.append(String.format("    - %s%n", MANAGED_TYPE_DESCRIPTION));
            s.append("    - A managed collection. ");
            appendManagedCollections(s, 1, constructableTypes);
            s.append(String.format("%n    - A scalar collection. %s%n    - %s",
                    explainScalarCollections(scalarTypes), UNMANAGED_PROPERTY_DESCRIPTION));
            maybeAppendConstructables(s, constructableTypes, 1);
        }
    } else {
        s.append(String.format("A model element of type: '%s' can not be constructed.%n",
                context.getModelType().getName()));
        s.append(String.format("It must be one of:%n"));
        s.append(String.format("    - %s", MANAGED_TYPE_DESCRIPTION));
        maybeAppendConstructables(s, constructableTypes, 1);
    }
    return s.toString();
}