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:springfox.bean.validators.plugins.BeanValidators.java

public static <T extends Annotation> Optional<T> validatorFromBean(ModelPropertyContext context,
        Class<T> annotationType) {

    Optional<BeanPropertyDefinition> propertyDefinition = context.getBeanPropertyDefinition();
    Optional<T> notNull = Optional.absent();
    if (propertyDefinition.isPresent()) {
        notNull = annotationFrom(propertyDefinition.get().getGetter(), annotationType)
                .or(annotationFrom(propertyDefinition.get().getField(), annotationType));
    }//from   w w  w.ja v  a2  s.c o m
    return notNull;
}

From source file:com.facebook.buck.apple.FrameworkPath.java

public static FrameworkPath fromString(BuildTarget target, String string) {
    Path path = Paths.get(string);

    String firstElement = Preconditions.checkNotNull(Iterables.getFirst(path, Paths.get(""))).toString();

    if (firstElement.startsWith("$")) { // NOPMD - length() > 0 && charAt(0) == '$' is ridiculous
        Optional<PBXReference.SourceTree> sourceTree = PBXReference.SourceTree.fromBuildSetting(firstElement);
        if (sourceTree.isPresent()) {
            return ImmutableFrameworkPath.builder().setSourceTreePath(
                    new SourceTreePath(sourceTree.get(), path.subpath(1, path.getNameCount()))).build();
        } else {//from   w w w. j  a  va 2s .  c  o m
            throw new HumanReadableException(String.format(
                    "Unknown SourceTree: %s in target: %s. Should be one of: %s", firstElement, target,
                    Joiner.on(',')
                            .join(Iterables.transform(ImmutableList.copyOf(PBXReference.SourceTree.values()),
                                    new Function<PBXReference.SourceTree, String>() {
                                        @Override
                                        public String apply(PBXReference.SourceTree input) {
                                            return "$" + input.toString();
                                        }
                                    }))));
        }
    } else {
        return ImmutableFrameworkPath.builder()
                .setSourcePath(new BuildTargetSourcePath(target, Paths.get(string))).build();
    }
}

From source file:com.facebook.buck.apple.xcode.FrameworkPath.java

public static FrameworkPath fromString(BuildTarget target, String string) {
    Path path = Paths.get(string);

    String firstElement = Preconditions.checkNotNull(Iterables.getFirst(path, Paths.get(""))).toString();

    if (firstElement.startsWith("$")) { // NOPMD - length() > 0 && charAt(0) == '$' is ridiculous
        Optional<PBXReference.SourceTree> sourceTree = PBXReference.SourceTree.fromBuildSetting(firstElement);
        if (sourceTree.isPresent()) {
            return ImmutableFrameworkPath.builder()
                    .sourceTreePath(new SourceTreePath(sourceTree.get(), path.subpath(1, path.getNameCount())))
                    .build();/* www  . ja  va2 s . c  o  m*/
        } else {
            throw new HumanReadableException(String.format(
                    "Unknown SourceTree: %s in target: %s. Should be one of: %s", firstElement, target,
                    Joiner.on(',')
                            .join(Iterables.transform(ImmutableList.copyOf(PBXReference.SourceTree.values()),
                                    new Function<PBXReference.SourceTree, String>() {
                                        @Override
                                        public String apply(PBXReference.SourceTree input) {
                                            return "$" + input.toString();
                                        }
                                    }))));
        }
    } else {
        return ImmutableFrameworkPath.builder().sourcePath(new BuildTargetSourcePath(target, Paths.get(string)))
                .build();
    }
}

From source file:org.semanticweb.owlapi.util.OWLAPIPreconditions.java

/**
 * check for absent and throw IllegalArgumentException if null or absent
 * //from   w ww . j a v a  2  s .c  o  m
 * @param object
 *        reference to check
 * @param message
 *        message for the illegal argument exception
 * @param <T>
 *        reference type
 * @return the input reference if not null
 * @throws IllegalArgumentException
 *         if object is null
 */
@Nonnull
public static <T> T checkNotNull(Optional<T> object, @Nonnull String message) {
    if (object == null || !object.isPresent()) {
        throw new IllegalArgumentException(message);
    }
    return verifyNotNull(object.get());
}

From source file:com.complexible.common.base.Optionals.java

public static <T, E extends Exception> T require(final Optional<T> theOptional, final Class<E> theExceptionType,
        final String theMsg) throws E {
    if (theOptional.isPresent()) {
        return theOptional.get();
    }//from   ww w  . j  ava2 s  . co m

    try {
        throw theExceptionType.getConstructor(String.class).newInstance(theMsg);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException("Invalid exception type provided");
    } catch (InvocationTargetException e) {
        throw new RuntimeException("Invalid exception type provided");
    } catch (InstantiationException e) {
        throw new RuntimeException("Invalid exception type provided");
    } catch (IllegalAccessException e) {
        throw new RuntimeException("Invalid exception type provided");
    }
}

From source file:io.crate.testing.SQLPrinter.java

public static String print(QuerySpec spec) {
    StringBuilder sb = new StringBuilder();

    sb.append("SELECT ");
    TESTING_SYMBOL_PRINTER.process(spec.outputs(), sb);

    if (spec.where().hasQuery()) {
        sb.append(" WHERE ");
        TESTING_SYMBOL_PRINTER.process(spec.where().query(), sb);
    }/*from w  w w  .  j  av a  2s .c om*/
    if (spec.groupBy().isPresent()) {
        sb.append(" GROUP BY ");
        TESTING_SYMBOL_PRINTER.process(spec.groupBy().get(), sb);
    }
    if (spec.having().isPresent()) {
        sb.append(" HAVING ");
        TESTING_SYMBOL_PRINTER.process(spec.having().get().query(), sb);
    }
    if (spec.orderBy().isPresent()) {
        sb.append(" ORDER BY ");
        TESTING_SYMBOL_PRINTER.process(spec.orderBy().get(), sb);
    }
    Optional<Symbol> limit = spec.limit();
    if (limit.isPresent()) {
        sb.append(" LIMIT ");
        sb.append(print(limit.get()));
    }
    Optional<Symbol> offset = spec.offset();
    if (offset.isPresent()) {
        sb.append(" OFFSET ");
        sb.append(print(offset.get()));
    }
    return sb.toString();
}

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

public static <T extends StoreTreeNode<T>> T findNodeChecked(final T tree, final InstanceIdentifier path) {
    T current = tree;/*w  w w . java  2 s  .  c  o  m*/
    List<PathArgument> nested = new ArrayList<>(path.getPath().size());
    for (PathArgument pathArg : path.getPath()) {
        Optional<T> potential = current.getChild(pathArg);
        nested.add(pathArg);
        Preconditions.checkArgument(potential.isPresent(), "Child %s is not present in tree.", nested);
        current = potential.get();
    }
    return current;
}

From source file:org.sonar.server.computation.issue.commonrule.CommentDensityRule.java

private static CommonRuleIssue generateIssue(Optional<Measure> commentDensityMeasure,
        Optional<Measure> commentLinesMeasure, Optional<Measure> nclocMeasure, double minCommentDensity) {
    int commentLines = commentLinesMeasure.isPresent() ? commentLinesMeasure.get().getIntValue() : 0;
    int ncloc = nclocMeasure.get().getIntValue();
    int minExpectedCommentLines = (int) Math.ceil(minCommentDensity * ncloc / (100 - minCommentDensity));
    int missingCommentLines = minExpectedCommentLines - commentLines;
    if (missingCommentLines <= 0) {
        throw new IllegalStateException(format(
                "Bug in measures of comment lines - density=%s, comment_lines= %d, ncloc=%d, threshold=%s%%",
                commentDensityMeasure.get().getDoubleValue(), commentLines, nclocMeasure.get().getIntValue(),
                minCommentDensity));/* www.j a  va  2s  .c o m*/
    }

    // TODO declare min threshold as int but not float ?
    String message = format(
            "%d more comment lines need to be written to reach the minimum threshold of %s%% comment density.",
            missingCommentLines, minCommentDensity);
    return new CommonRuleIssue(missingCommentLines, message);
}

From source file:org.opendaylight.vpnservice.interfacemgr.globals.InterfaceServiceUtil.java

public static short getVlanId(String interfaceName, DataBroker broker) {
    InstanceIdentifier<Interface> id = InstanceIdentifier.builder(Interfaces.class)
            .child(Interface.class, new InterfaceKey(interfaceName)).build();
    Optional<Interface> ifInstance = MDSALUtil.read(LogicalDatastoreType.CONFIGURATION, id, broker);
    if (ifInstance.isPresent()) {
        IfL2vlan vlanIface = ifInstance.get().getAugmentation(IfL2vlan.class);
        short vlanId = vlanIface.getVlanId() == null ? 0 : vlanIface.getVlanId().getValue().shortValue();
        return vlanId;
    }//from  w  ww.  j  a  v a  2  s  . c o m
    return -1;
}

From source file:net.caseif.ttt.util.helper.gamemode.BanHelper.java

/**
 * Bans the player by the specified UUID from using TTT for a set amount of time.
 *
 * @param player  the UUID of the player to ban
 * @param minutes the length of time to ban the player for
 *///from   ww w .jav a2s  .c  om
public static void ban(UUID player, int minutes) throws InvalidConfigurationException, IOException {
    File f = new File(TTTCore.getPlugin().getDataFolder(), "bans.yml");
    YamlConfiguration y = new YamlConfiguration();
    Player p = Bukkit.getPlayer(player);
    y.load(f);
    long unbanTime = minutes < 0 ? -1 : System.currentTimeMillis() / 1000L + (minutes * 60);
    y.set(player.toString(), unbanTime);
    y.save(f);
    if (p != null) {
        Optional<Challenger> ch = TTTCore.mg.getChallenger(p.getUniqueId());
        if (ch.isPresent()) {
            ch.get().removeFromRound();
        }
    }
}