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:com.palantir.atlasdb.keyvalue.api.TableReference.java

public static TableReference createFromFullyQualifiedName(String fullTableName) {
    int index = fullTableName.indexOf('.');
    Preconditions.checkArgument(index > 0, "Table name %s is not a fully qualified table name.");
    return create(Namespace.create(fullTableName.substring(0, index), Namespace.UNCHECKED_NAME),
            fullTableName.substring(index + 1));
}

From source file:com.facebook.stats.cardinality.HyperLogLogUtil.java

public static long estimateCardinality(int[] bucketValues) {
    Preconditions.checkArgument(Numbers.isPowerOf2(bucketValues.length),
            "number of buckets must be a power of 2");

    int zeroBuckets = 0;
    double sum = 0;
    for (Integer value : bucketValues) {
        sum += 1.0 / (1L << value);
        if (value == 0) {
            ++zeroBuckets;/*from  w w  w.ja  v  a2  s.co m*/
        }
    }

    double alpha = computeAlpha(bucketValues.length);
    double result = alpha * bucketValues.length * bucketValues.length / sum;

    if (result <= 2.5 * bucketValues.length) {
        // adjust for small cardinalities
        if (zeroBuckets > 0) {
            // baselineCount is the number of buckets with value 0
            result = bucketValues.length * Math.log(bucketValues.length * 1.0 / zeroBuckets);
        }
    }

    return Math.round(result);
}

From source file:org.bozzo.ipplan.tools.Netmask.java

/**
 * Return the netmask from the number of hosts
 * @param number the number of hosts//  w w  w . j av a 2  s .  co m
 * @return the netmask
 */
public static Integer fromNumberHosts(Long number) {
    Preconditions.checkArgument(number != null, "Hosts number shouldn't be null");
    Preconditions.checkArgument(number > 0, "Hosts number should be a positive integer");
    if (number >= (1L << 32)) {
        return 0;
    } else if (number >= (1L << 31)) {
        return 1;
    }
    return 1 + Integer.numberOfLeadingZeros(number.intValue());
}

From source file:com.spotify.helios.client.ClientCertificatePath.java

private static Path checkExists(Path path) {
    Preconditions.checkNotNull(path);/*from   w w w  . j a va  2s  .com*/
    Preconditions.checkArgument(path.toFile().canRead(), path + " does not exist or cannot be read");
    return path;
}

From source file:org.opendaylight.genius.itm.cli.ItmCliUtils.java

/**
 * Construct dpn id list./*from   w  w w.  ja v  a  2s . c o  m*/
 *
 * @param dpnIds
 *            the dpn ids
 * @return the list
 */
public static List<BigInteger> constructDpnIdList(final String dpnIds) {
    final List<BigInteger> lstDpnIds = new ArrayList<>();
    if (StringUtils.isNotBlank(dpnIds)) {
        final String[] arrDpnIds = StringUtils.split(dpnIds, ',');
        for (String dpn : arrDpnIds) {
            if (StringUtils.isNumeric(StringUtils.trim(dpn))) {
                lstDpnIds.add(new BigInteger(StringUtils.trim(dpn)));
            } else {
                Preconditions.checkArgument(false, String.format("DPN ID [%s] is not a numeric value.", dpn));
            }
        }
    }
    return lstDpnIds;
}

From source file:minium.internal.Paths.java

public static URL toURL(String urlPath) {
    Preconditions.checkArgument(!urlPath.startsWith(CLASSPATH_WILDCARD_PROTOCOL),
            "path starts with classpath*, use toURLs instead");
    return Iterables.getFirst(toURLs(urlPath), null);
}

From source file:org.janusgraph.graphdb.configuration.validator.CompatibilityValidator.java

public static void validateBackwardCompatibilityWithTitan(String version,
        String localConfigurationIdsStoreName) {

    Preconditions.checkArgument(version != null,
            "JanusGraph version nor Titan compatibility have not been initialized");

    if (!JanusGraphConstants.TITAN_COMPATIBLE_VERSIONS.contains(version)) {
        throw new JanusGraphException(
                String.format(INCOMPATIBLE_VERSION_EXCEPTION, version, JanusGraphConstants.VERSION));
    }//ww  w.  j  av a 2s.c om

    // When connecting to a store created by Titan the ID store name will not be in the
    // global configuration as it was not something which was configurable with Titan.
    // So to ensure compatibility override the default to titan_ids.
    boolean localIdStoreIsDefault = JanusGraphConstants.JANUSGRAPH_ID_STORE_NAME
            .equals(localConfigurationIdsStoreName);

    boolean usingTitanIdStore = localIdStoreIsDefault
            || JanusGraphConstants.TITAN_ID_STORE_NAME.equals(localConfigurationIdsStoreName);

    Preconditions.checkArgument(usingTitanIdStore,
            "ID store for Titan compatibility has not been initialized to: "
                    + JanusGraphConstants.TITAN_ID_STORE_NAME);
}

From source file:com.google.cloud.hadoop.gcsio.GoogleCloudStorageExceptions.java

/**
 * Creates FileNotFoundException with suitable message for a GCS bucket or object.
 *///www .j  a  v  a  2s .  c o  m
public static FileNotFoundException getFileNotFoundException(String bucketName, String objectName) {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(bucketName), "bucketName must not be null or empty");
    if (objectName == null) {
        objectName = "";
    }
    return new FileNotFoundException(String.format("Item not found: %s/%s", bucketName, objectName));
}

From source file:org.haiku.haikudepotserver.support.URLHelper.java

public static long payloadLength(URL url) throws IOException {
    Preconditions.checkArgument(null != url, "the url must be supplied");

    long result = -1;
    HttpURLConnection connection = null;

    switch (url.getProtocol()) {

    case "http":
    case "https":

        try {//from www  .j a v  a2  s  . c  o m
            connection = (HttpURLConnection) url.openConnection();

            connection.setConnectTimeout(PAYLOAD_LENGTH_CONNECT_TIMEOUT);
            connection.setReadTimeout(PAYLOAD_LENGTH_READ_TIMEOUT);
            connection.setRequestMethod(HttpMethod.HEAD.name());
            connection.connect();

            String contentLengthHeader = connection.getHeaderField(HttpHeaders.CONTENT_LENGTH);

            if (!Strings.isNullOrEmpty(contentLengthHeader)) {
                long contentLength;

                try {
                    contentLength = Long.parseLong(contentLengthHeader);

                    if (contentLength > 0) {
                        result = contentLength;
                    } else {
                        LOGGER.warn("bad content length; {}", contentLength);
                    }
                } catch (NumberFormatException nfe) {
                    LOGGER.warn("malformed content length; {}", contentLengthHeader);
                }
            } else {
                LOGGER.warn("unable to get the content length header");
            }

        } finally {
            if (null != connection) {
                connection.disconnect();
            }
        }
        break;

    case "file":
        File file = new File(url.getPath());

        if (file.exists() && file.isFile()) {
            result = file.length();
        } else {
            LOGGER.warn("unable to find the local file; {}", url.getPath());
        }
        break;

    }

    LOGGER.info("did obtain length for url; {} - {}", url, result);

    return result;
}

From source file:com.facebook.presto.sql.planner.DomainUtils.java

public static <T> Map<Symbol, T> columnHandleToSymbol(Map<ColumnHandle, T> columnMap,
        Map<Symbol, ColumnHandle> assignments) {
    Map<ColumnHandle, Symbol> inverseAssignments = ImmutableBiMap.copyOf(assignments).inverse();
    Preconditions.checkArgument(inverseAssignments.keySet().containsAll(columnMap.keySet()),
            "assignments does not contain all required column handles");
    ImmutableMap.Builder<Symbol, T> builder = ImmutableMap.builder();
    for (Map.Entry<ColumnHandle, T> entry : columnMap.entrySet()) {
        builder.put(inverseAssignments.get(entry.getKey()), entry.getValue());
    }// www  .  j a  va 2 s  .c  om
    return builder.build();
}