Example usage for com.google.common.base Preconditions checkArgument

List of usage examples for com.google.common.base Preconditions checkArgument

Introduction

In this page you can find the example usage for com.google.common.base Preconditions checkArgument.

Prototype

public static void checkArgument(boolean expression, @Nullable Object errorMessage) 

Source Link

Document

Ensures the truth of an expression involving one or more parameters to the calling method.

Usage

From source file:org.apache.hadoop.hdfs.server.blockmanagement.ContiguousBlockStorageOp.java

/**
 * Ensure that there is enough  space to include num more triplets.
 * @return first free triplet index.//from w  w w . j  a  v a  2  s  .c  o m
 */
private static int ensureCapacity(BlockInfo b, int num) {
    Preconditions.checkArgument(b.triplets != null, "BlockInfo is not initialized");
    int last = b.numNodes();
    if (b.triplets.length >= (last + num) * 3) {
        return last;
    }
    /* Not enough space left. Create a new array. Should normally
     * happen only when replication is manually increased by the user. */
    Object[] old = b.triplets;
    b.triplets = new Object[(last + num) * 3];
    System.arraycopy(old, 0, b.triplets, 0, last * 3);
    return last;
}

From source file:com.facebook.buck.cxx.platform.DebugPathSanitizer.java

/**
 * @return the given path as a string, expanded using {@code separator} to fulfill the required
 *     {@code pathSize}./*from  w  w w.j  ava2  s. c o  m*/
 */
public static String getPaddedDir(String path, int size, char pad) {
    Preconditions.checkArgument(path.length() <= size,
            String.format("Path is too long to sanitize:\n'%s' is %d characters long, limit is %d.", path,
                    path.length(), size));
    return Strings.padEnd(path, size, pad);
}

From source file:com.github.jeluard.guayaba.base.Preconditions2.java

/**
 * Ensure specified {@link Collection} is not {@link Collection#isEmpty()}.
 *
 * @param collection a collection//w  w w .j  a  v a2s  . c  o  m
 * @param name a representation of {@code collection} used to build the error message
 * @throws IllegalArgumentException if {@code collection} is {@link Collection#isEmpty()}
 */
public static <T extends Collection<?>> T checkNotEmpty(final T collection, final String name) {
    Preconditions.checkNotNull(name, "null name");
    Preconditions.checkArgument(!Preconditions.checkNotNull(collection, "null " + name).isEmpty(),
            name + " is empty");
    return collection;
}

From source file:org.kitesdk.data.spi.DatasetRepositories.java

/**
 * Load a {@link DatasetRepository} for the given dataset, view or repository URI.
 * <p>// w  w w  . j ava2 s  .c  om
 * URI formats are defined by {@code Dataset} implementations, but must begin
 * with "dataset:" or "view:".
 *
 * @param uri a {@code Dataset} or {@code View} URI.
 * @param <R> The type of {@code DatasetRepository} expected.
 * @return a {@code DatasetRepository} responsible for the given URI.
 */
@SuppressWarnings("unchecked")
public static <R extends DatasetRepository> R repositoryFor(URI uri) {
    boolean isRepoUri = URIBuilder.REPO_SCHEME.equals(uri.getScheme());
    Preconditions.checkArgument(
            isRepoUri || URIBuilder.DATASET_SCHEME.equals(uri.getScheme())
                    || URIBuilder.VIEW_SCHEME.equals(uri.getScheme()),
            "Not a repository, dataset, or view URI: " + uri);

    Pair<DatasetRepository, Map<String, String>> pair;
    if (URIBuilder.REPO_SCHEME.equals(uri.getScheme())) {
        pair = Registration.lookupRepoUri(URI.create(uri.getRawSchemeSpecificPart()));
    } else {
        pair = Registration.lookupDatasetUri(URI.create(uri.getRawSchemeSpecificPart()));
    }

    return (R) pair.first();
}

From source file:org.opendaylight.yangtools.util.Immutables.java

/**
 * Determines if object is known to be immutable
 *
 * <p>Note: This method may return false to immutable objects which
 * immutability is not known, was defined not using concepts term.
 *
 * @param o//from  w w  w .ja  v a  2s .com
 *            Reference to check
 * @return true if object is known to be immutable false otherwise.
 */
public static boolean isImmutable(final Object o) {
    Preconditions.checkArgument(o != null, "Object should not be null");
    if (o instanceof Mutable) {
        return false;
    } else if (o instanceof Immutable) {
        return true;
    } else if (o instanceof String) {
        return true;
    } else if (KNOWN_IMMUTABLES.contains(o.getClass())) {
        return true;
    }
    return false;
}

From source file:com.android.utils.AsmUtils.java

/**
 * Gets the class name from a class member internal name, like {@code com/foo/Bar.baz:(I)V}.
 *///from   ww  w  .ja  v a2 s .c o  m
@NonNull
public static String getClassName(@NonNull String memberName) {
    Preconditions.checkArgument(memberName.contains("."), "Class name passed as argument.");
    return memberName.substring(0, memberName.indexOf('.'));
}

From source file:org.apache.rocketmq.jms.util.URISpecParser.java

/**
 * ConnectionUrl spec is broker://ip:port?key1=value1&key2=value2
 *
 * @param uri Just like broker://ip:port?key1=value1&key2=value2
 * @return The parameters' map//w w w.  j  av  a2s.  co  m
 */
public static Map<String, String> parseURI(String uri) {
    Preconditions.checkArgument(null != uri && !uri.trim().isEmpty(), "Uri can not be empty!");

    Map<String, String> results = Maps.newHashMap();
    String broker = uri.substring(0, uri.indexOf(":"));
    results.put(CommonConstant.PROVIDER, broker);

    if (broker.equals(DEFAULT_BROKER)) {
        //Special handle for alibaba inner mq broker
        String queryStr = uri.substring(uri.indexOf("?") + 1, uri.length());
        if (StringUtils.isNotEmpty(queryStr)) {
            String[] params = queryStr.split("&");
            for (String param : params) {
                if (param.contains("=")) {
                    String[] values = param.split("=", 2);
                    results.put(values[0], values[1]);
                }
            }
        }
    } else {
        throw new IllegalArgumentException("Broker must be rocketmq");
    }
    return results;
}

From source file:org.apache.james.jmap.api.vacation.AccountId.java

public static AccountId fromString(String identifier) {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(identifier),
            "AccountId identifier should not be null or empty");
    return new AccountId(identifier);
}

From source file:org.haiku.haikudepotserver.dataobjects.MediaType.java

/**
 * <p>Files can have extensions that help to signify what sort of files they are.  For example, a PNG file would
 * have the extension "png".  This method will be able to return a media type for a given file extension.</p>
 *///from w  w  w  .  ja v  a  2  s  . c o  m

public static Optional<MediaType> getByExtension(ObjectContext context, String extension) {
    Preconditions.checkArgument(null != context, "the context must be provided");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(extension), "the extension must be provided");

    if (extension.equals(EXTENSION_HAIKUVECTORICONFILE)) {
        return tryGetByCode(context, MEDIATYPE_HAIKUVECTORICONFILE);
    }

    if (extension.equals(EXTENSION_PNG)) {
        return tryGetByCode(context, com.google.common.net.MediaType.PNG.toString());
    }

    return Optional.empty();
}

From source file:com.salesforce.jprotoc.ProtocPlugin.java

/**
 * Apply multiple generators to the parsed proto descriptor, aggregating their results.
 * @param generators The list of generators to run.
 *//*from  w w w.j  a va 2 s . c  o m*/
public static void generate(@Nonnull List<Generator> generators) {
    Preconditions.checkNotNull(generators, "generators");
    Preconditions.checkArgument(!generators.isEmpty(), "generators.isEmpty()");

    try {
        // Parse the input stream to extract the generator request
        byte[] generatorRequestBytes = ByteStreams.toByteArray(System.in);
        PluginProtos.CodeGeneratorRequest request = PluginProtos.CodeGeneratorRequest
                .parseFrom(generatorRequestBytes);

        // Run each file generator, collecting the output
        List<PluginProtos.CodeGeneratorResponse.File> outputFiles = generators.stream()
                .flatMap(gen -> gen.generate(request)).collect(Collectors.toList());

        // Send the files back to protoc
        PluginProtos.CodeGeneratorResponse response = PluginProtos.CodeGeneratorResponse.newBuilder()
                .addAllFile(outputFiles).build();
        response.writeTo(System.out);

    } catch (GeneratorException ex) {
        try {
            PluginProtos.CodeGeneratorResponse.newBuilder().setError(ex.getMessage()).build()
                    .writeTo(System.out);
        } catch (IOException ex2) {
            abort(ex2);
        }
    } catch (Throwable ex) { // Catch all the things!
        abort(ex);
    }
}