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 String errorMessageTemplate,
        @Nullable Object... errorMessageArgs) 

Source Link

Document

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

Usage

From source file:com.facebook.buck.rules.CellPathResolverSerializer.java

public static ImmutableMap<String, Object> serialize(CellPathResolver resolver) {
    Preconditions.checkArgument(resolver instanceof DefaultCellPathResolver,
            "Unsupported CellPathResolver class: %s", resolver.getClass());

    DefaultCellPathResolver defaultResolver = (DefaultCellPathResolver) resolver;

    ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
    builder.put(TYPE, TYPE_DEFAULT);//w w  w  .j a v  a  2 s  . c  om
    builder.put(ROOT_PATH, defaultResolver.getRoot().toString());

    ImmutableMap.Builder<String, String> cellPathAsStrings = ImmutableMap.builder();
    for (Map.Entry<String, Path> entry : defaultResolver.getCellPaths().entrySet()) {
        cellPathAsStrings.put(entry.getKey(), entry.getValue().toString());
    }
    builder.put(CELL_PATHS, cellPathAsStrings.build());
    return builder.build();
}

From source file:io.airlift.stats.cardinality.Utils.java

public static int indexBitLength(int numberOfBuckets) {
    Preconditions.checkArgument(isPowerOf2(numberOfBuckets), "numberOfBuckets must be a power of 2, actual: %s",
            numberOfBuckets);/*w ww. j a v a  2  s.c  o  m*/
    return (int) (Math.log(numberOfBuckets) / Math.log(2));
}

From source file:org.onos.yangtools.yang.data.impl.codec.BooleanStringCodec.java

private static void validate(final String string) {
    Preconditions.checkArgument("true".equalsIgnoreCase(string) || "false".equalsIgnoreCase(string),
            "Invalid value '%s' for boolean type. Allowed values are true and false", string);
}

From source file:com.goodow.wind.server.model.DeltaSerializer.java

public static JsonObject dataToClientJson(Delta<String> data, long resultingRevision) {
    Preconditions.checkArgument(resultingRevision <= MAX_DOUBLE_INTEGER, "Resulting revision %s is too large",
            resultingRevision);//from  w  ww. j  a  va2 s  .  c o m

    // Assume payload is JSON, and parse it to avoid nested json.
    // TODO: Consider using Delta<JSONObject> instead.
    // The reason I haven't done it yet is because it's not immutable,
    // and also for reasons described in Delta.
    JsonObject payloadJson;
    try {
        payloadJson = new JsonParser().parse(data.getPayload()).getAsJsonObject();
    } catch (JsonParseException e) {
        throw new IllegalArgumentException("Invalid payload for " + data, e);
    }

    JsonObject json = new JsonObject();
    try {
        Preconditions.checkArgument(resultingRevision >= 0, "invalid rev %s", resultingRevision);
        json.addProperty(Constants.Params.VERSION, resultingRevision);
        long sanityCheck = json.get(Constants.Params.VERSION).getAsLong();
        if (sanityCheck != resultingRevision) {
            throw new AssertionError("resultingRevision " + resultingRevision
                    + " not losslessly represented in JSON, got back " + sanityCheck);
        }
        json.addProperty(Constants.Params.SESSION_ID, data.getClientId().getId());
        json.add(Constants.Params.OPERATION, payloadJson);
        return json;
    } catch (JsonParseException e) {
        throw new Error(e);
    }
}

From source file:net.galaxy.weather.MeasurementParser.java

public static MeasurementDto parse(int src, String str) throws IllegalArgumentException {
    Preconditions.checkNotNull(str, "String is null");
    Preconditions.checkArgument(str.length() > 6, "Invalid string: [%s]", str);

    logger.debug("parsing: [{}]", str);
    try {//  ww  w. ja v  a 2 s.  c  om
        String payload = str.substring(0, str.lastIndexOf('^'));
        logger.trace("  payload: `{}`", payload);
        String receivedCrcStr = str.substring(str.lastIndexOf('^') + 1, str.length());
        logger.trace("  CRC16: `{}`", receivedCrcStr);

        int calculatedCrc;
        try {
            calculatedCrc = Digest.crc16(payload.getBytes("ASCII")) & 0xFFFF;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

        int receivedCrc = Integer.valueOf(receivedCrcStr, 16);
        if (calculatedCrc != receivedCrc) {
            throw new IllegalArgumentException("Checksum mismatch");
        }

        String[] parts = payload.split("\\|");
        if (parts.length != 5) {
            throw new IllegalArgumentException("Invalid format -- missing parts");
        }

        long timestamp = Long.parseLong(parts[0]) * 1000 + DT_ADD;

        String[] thParts = parts[1].split(":");
        double temp = 0;
        double humid = 0;
        if (thParts.length == 2) {
            temp = Integer.valueOf(thParts[0], 10) / 10.0;
            humid = Integer.valueOf(thParts[1], 10) / 10.0;
            // temperature sensor error
        }

        MathContext mc = new MathContext(2);
        return new MeasurementDto(src, timestamp, temp, humid, Integer.valueOf(parts[4], 10) / 100.0,
                MeasurementDto.BatteryStatus.values()[Integer.valueOf(parts[2], 10)],
                Integer.valueOf(parts[3], 10) / 100.0);
    } catch (Exception ex) {
        throw new IllegalArgumentException(
                String.format("Error parsing string [%s]: %s", str, ex.getMessage()));
    }
}

From source file:com.goodow.realtime.server.model.DeltaSerializer.java

public static JsonElement dataToClientJson(Delta<String> data, long resultingRevision) {
    Preconditions.checkArgument(resultingRevision <= MAX_DOUBLE_INTEGER, "Resulting revision %s is too large",
            resultingRevision);//from  w  ww  .  ja v a  2s . c o  m

    // Assume payload is JSON, and parse it to avoid nested json.
    // TODO: Consider using Delta<JSONObject> instead.
    // The reason I haven't done it yet is because it's not immutable,
    // and also for reasons described in Delta.
    JsonElement payloadJson;
    try {
        payloadJson = new JsonParser().parse(data.getPayload());
    } catch (JsonParseException e) {
        throw new IllegalArgumentException("Invalid payload for " + data, e);
    }

    JsonArray json = new JsonArray();
    try {
        Preconditions.checkArgument(resultingRevision >= 0, "invalid rev %s", resultingRevision);
        json.add(new JsonPrimitive(resultingRevision));
        long sanityCheck = json.get(0).getAsLong();
        if (sanityCheck != resultingRevision) {
            throw new AssertionError("resultingRevision " + resultingRevision
                    + " not losslessly represented in JSON, got back " + sanityCheck);
        }
        json.add(new JsonPrimitive(data.getSession().userId));
        json.add(new JsonPrimitive(data.getSession().sessionId));
        json.add(payloadJson);
        return json;
    } catch (JsonParseException e) {
        throw new Error(e);
    }
}

From source file:com.facebook.buck.hashing.PathHashing.java

public static ImmutableSet<Path> hashPath(Hasher hasher, FileHashLoader fileHashLoader,
        ProjectFilesystem projectFilesystem, Path root) throws IOException {
    Preconditions.checkArgument(!root.equals(EMPTY_PATH), "Path to hash (%s) must not be empty", root);
    ImmutableSet.Builder<Path> children = ImmutableSet.builder();
    for (Path path : ImmutableSortedSet.copyOf(projectFilesystem.getFilesUnderPath(root))) {
        StringHashing.hashStringAndLength(hasher, MorePaths.pathWithUnixSeparators(path));
        if (!root.equals(path)) {
            children.add(root.relativize(path));
        }/*w w w .  ja v a 2  s  .c o m*/
        hasher.putBytes(fileHashLoader.get(projectFilesystem.resolve(path)).asBytes());
    }
    return children.build();
}

From source file:com.facebook.buck.util.hashing.PathHashing.java

public static ImmutableSet<Path> hashPath(Hasher hasher, ProjectFileHashLoader fileHashLoader,
        ProjectFilesystem projectFilesystem, Path root) throws IOException {
    Preconditions.checkArgument(!root.equals(EMPTY_PATH), "Path to hash (%s) must not be empty", root);
    ImmutableSet.Builder<Path> children = ImmutableSet.builder();
    for (Path path : ImmutableSortedSet.copyOf(projectFilesystem.getFilesUnderPath(root))) {
        StringHashing.hashStringAndLength(hasher, MorePaths.pathWithUnixSeparators(path));
        if (!root.equals(path)) {
            children.add(root.relativize(path));
        }//from   w  w  w .j  ava2 s  . com
        hasher.putBytes(fileHashLoader.get(path).asBytes());
    }
    return children.build();
}

From source file:io.crate.analyze.BlobTableAnalyzer.java

static TableIdent tableToIdent(Table table) {
    List<String> tableNameParts = table.getName().getParts();
    Preconditions.checkArgument(tableNameParts.size() < 3, "Invalid tableName \"%s\"", table.getName());

    if (tableNameParts.size() == 2) {
        Preconditions.checkArgument(tableNameParts.get(0).equalsIgnoreCase(BlobSchemaInfo.NAME),
                "The Schema \"%s\" isn't valid in a [CREATE | ALTER] BLOB TABLE clause", tableNameParts.get(0));

        return new TableIdent(tableNameParts.get(0), tableNameParts.get(1));
    }//from  w w w . ja v  a  2 s  . c  o m
    assert tableNameParts.size() == 1;
    return new TableIdent(BlobSchemaInfo.NAME, tableNameParts.get(0));
}

From source file:org.janusgraph.graphdb.database.idhandling.VariableLong.java

public static byte unsignedByte(int value) {
    Preconditions.checkArgument(value >= 0 && value < 256, "Value overflow: %s", value);
    return (byte) (value & 0xFF);
}