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.cloudbees.api.Main.java

public static void main(String[] args) throws Exception {

    File beesCredentialsFile = new File(System.getProperty("user.home"), ".bees/bees.config");
    Preconditions.checkArgument(beesCredentialsFile.exists(), "File %s not found", beesCredentialsFile);
    Properties beesCredentials = new Properties();
    beesCredentials.load(new FileInputStream(beesCredentialsFile));
    String apiUrl = "https://api.cloudbees.com/api";
    String apiKey = beesCredentials.getProperty("bees.api.key");
    String secret = beesCredentials.getProperty("bees.api.secret");
    BeesClient client = new BeesClient(apiUrl, apiKey, secret, "xml", "1.0");
    client.setVerbose(false);/*from   w ww .ja  va2  s . co  m*/

    URL databasesUrl = Thread.currentThread().getContextClassLoader().getResource("databases.txt");
    Preconditions.checkNotNull(databasesUrl, "File 'databases.txt' NOT found in the classpath");

    Collection<String> databaseNames;
    try {
        databaseNames = Sets.newTreeSet(Resources.readLines(databasesUrl, Charsets.ISO_8859_1));
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }

    databaseNames = Collections2.transform(databaseNames, new Function<String, String>() {
        @Nullable
        @Override
        public String apply(@Nullable String input) {
            // {host_db_create,<<"tco_q5rm">>,<<"TCO_q5rm">>,

            if (input == null)
                return null;

            if (input.startsWith("#"))
                return null;

            if (input.indexOf('"') == -1) {
                logger.warn("Skip invalid line {}", input);
                return null;
            }
            input = input.substring(input.indexOf('"') + 1);
            if (input.indexOf('"') == -1) {
                logger.warn("Skip invalid line {}", input);
                return null;
            }
            return input.substring(0, input.indexOf('"'));

        }
    });
    databaseNames = Collections2.filter(databaseNames, new Predicate<String>() {
        @Override
        public boolean apply(@Nullable String s) {
            return !Strings.isNullOrEmpty(s);
        }
    });

    Multimap<String, String> databasesByAccount = ArrayListMultimap.create();

    Class.forName("com.mysql.jdbc.Driver");

    for (String databaseName : databaseNames) {
        try {
            DatabaseInfo databaseInfo = client.databaseInfo(databaseName, true);
            databasesByAccount.put(databaseInfo.getOwner(), databaseInfo.getName());
            logger.debug("Evaluate " + databaseInfo.getName());

            if (true == false) {
                // Hibernate
                logger.info("Hibernate {}", databaseName);
                Map<String, String> params = new HashMap<String, String>();
                params.put("database_id", databaseName);
                String url = client.getRequestURL("database.hibernate", params);
                String response = client.executeRequest(url);
                DatabaseInfoResponse apiResponse = (DatabaseInfoResponse) client.readResponse(response);
                logger.info("DB {} status: {}", apiResponse.getDatabaseInfo().getName(),
                        apiResponse.getDatabaseInfo().getStatus());

            }
            if (true == false) {
                // Hibernate
                logger.info("Activate {}", databaseName);
                Map<String, String> params = new HashMap<String, String>();
                params.put("database_id", databaseName);
                String url = client.getRequestURL("database.activate", params);
                String response = client.executeRequest(url);
                DatabaseInfoResponse apiResponse = (DatabaseInfoResponse) client.readResponse(response);
                logger.info("DB {} status: {}", apiResponse.getDatabaseInfo().getName(),
                        apiResponse.getDatabaseInfo().getStatus());
            }

            String dbUrl = "jdbc:mysql://" + databaseInfo.getMaster() + "/" + databaseInfo.getName();
            logger.info("Connect to {} user={}", dbUrl, databaseInfo.getUsername());
            Connection cnn = DriverManager.getConnection(dbUrl, databaseInfo.getUsername(),
                    databaseInfo.getPassword());
            cnn.setAutoCommit(false);
            cnn.close();

        } catch (Exception e) {
            logger.warn("Exception for {}", databaseName, e);
        }
    }

    System.out.println("OWNERS");
    for (String account : databasesByAccount.keySet()) {
        System.out.println(account + ": " + Joiner.on(", ").join(databasesByAccount.get(account)));
    }

}

From source file:org.apache.mahout.cf.taste.example.netflix.TransposeToByUser.java

public static void main(String[] args) throws IOException, OptionException {

    File dataDirectory = TasteOptionParser.getRatings(args);
    File byItemDirectory = new File(dataDirectory, "training_set");
    File byUserDirectory = new File(dataDirectory, "training_set_by_user");

    Preconditions.checkArgument(dataDirectory.exists() && dataDirectory.isDirectory(), "%s is not a directory",
            dataDirectory);//w  ww  .jav a2s. com
    Preconditions.checkArgument(byItemDirectory.exists() && byItemDirectory.isDirectory(),
            "%s is not a directory", byItemDirectory);
    Preconditions.checkArgument(!byUserDirectory.exists(), "%s already exists", byUserDirectory);

    byUserDirectory.mkdirs();

    Map<String, List<String>> byUserEntryCache = new FastMap<String, List<String>>(100000);

    for (File byItemFile : byItemDirectory.listFiles()) {
        log.info("Processing {}", byItemFile);
        Iterator<String> lineIterator = new FileLineIterable(byItemFile, false).iterator();
        String line = lineIterator.next();
        String movieIDString = line.substring(0, line.length() - 1);
        while (lineIterator.hasNext()) {
            line = lineIterator.next();
            int firstComma = line.indexOf(',');
            String userIDString = line.substring(0, firstComma);
            int secondComma = line.indexOf(',', firstComma + 1);
            String ratingString = line.substring(firstComma, secondComma); // keep comma
            List<String> cachedLines = byUserEntryCache.get(userIDString);
            if (cachedLines == null) {
                cachedLines = Lists.newArrayList();
                byUserEntryCache.put(userIDString, cachedLines);
            }
            cachedLines.add(movieIDString + ratingString);
            maybeFlushCache(byUserDirectory, byUserEntryCache);
        }

    }

}

From source file:org.apache.mahout.classifier.mlp.TrainMultilayerPerceptron.java

public static void main(String[] args) throws Exception {
    Parameters parameters = new Parameters();

    if (parseArgs(args, parameters)) {
        log.info("Validate model...");
        // check whether the model already exists
        Path modelPath = new Path(parameters.modelFilePath);
        FileSystem modelFs = modelPath.getFileSystem(new Configuration());
        MultilayerPerceptron mlp;//from w  ww.  j a v a  2 s  . c om

        if (modelFs.exists(modelPath) && parameters.updateModel) {
            // incrementally update existing model
            log.info("Build model from existing model...");
            mlp = new MultilayerPerceptron(parameters.modelFilePath);
        } else {
            if (modelFs.exists(modelPath)) {
                modelFs.delete(modelPath, true); // delete the existing file
            }
            log.info("Build model from scratch...");
            mlp = new MultilayerPerceptron();
            for (int i = 0; i < parameters.layerSizeList.size(); ++i) {
                if (i != parameters.layerSizeList.size() - 1) {
                    mlp.addLayer(parameters.layerSizeList.get(i), false, parameters.squashingFunctionName);
                } else {
                    mlp.addLayer(parameters.layerSizeList.get(i), true, parameters.squashingFunctionName);
                }
                mlp.setCostFunction("Minus_Squared");
                mlp.setLearningRate(parameters.learningRate).setMomentumWeight(parameters.momemtumWeight)
                        .setRegularizationWeight(parameters.regularizationWeight);
            }
            mlp.setModelPath(parameters.modelFilePath);
        }

        // set the parameters
        mlp.setLearningRate(parameters.learningRate).setMomentumWeight(parameters.momemtumWeight)
                .setRegularizationWeight(parameters.regularizationWeight);

        // train by the training data
        Path trainingDataPath = new Path(parameters.inputFilePath);
        FileSystem dataFs = trainingDataPath.getFileSystem(new Configuration());

        Preconditions.checkArgument(dataFs.exists(trainingDataPath), "Training dataset %s cannot be found!",
                parameters.inputFilePath);

        log.info("Read data and train model...");
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new InputStreamReader(dataFs.open(trainingDataPath)));
            String line;

            // read training data line by line
            if (parameters.skipHeader) {
                reader.readLine();
            }

            int labelDimension = parameters.labelsIndex.size();
            while ((line = reader.readLine()) != null) {
                String[] token = line.split(",");
                String label = token[token.length - 1];
                int labelIndex = parameters.labelsIndex.get(label);

                double[] instances = new double[token.length - 1 + labelDimension];
                for (int i = 0; i < token.length - 1; ++i) {
                    instances[i] = Double.parseDouble(token[i]);
                }
                for (int i = 0; i < labelDimension; ++i) {
                    instances[token.length - 1 + i] = 0;
                }
                // set the corresponding dimension
                instances[token.length - 1 + labelIndex] = 1;

                Vector instance = new DenseVector(instances).viewPart(0, instances.length);
                mlp.trainOnline(instance);
            }

            // write model back
            log.info("Write trained model to {}", parameters.modelFilePath);
            mlp.writeModelToFile();
            mlp.close();
        } finally {
            Closeables.close(reader, true);
        }
    }
}

From source file:com.github.valentin.fedoskin.fb2me.desktop.drive.DriveSample.java

public static void main(String[] args) {
    Preconditions.checkArgument(
            !UPLOAD_FILE_PATH.startsWith("Enter ") && !DIR_FOR_DOWNLOADS.startsWith("Enter "),
            "Please enter the upload file path and download directory in %s", DriveSample.class);
    try {//from w w w .  j a v  a2  s . c o m
        try {
            // authorization
            Credential credential = authorize();
            // set up the global Drive instance
            drive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                    .setApplicationName(APPLICATION_NAME).build();
            // run commands
            DriveView.header1("Starting Resumable Media Upload");
            File uploadedFile = uploadFile(false);
            DriveView.header1("Updating Uploaded File Name");
            File updatedFile = updateFileWithTestSuffix(uploadedFile.getId());
            DriveView.header1("Starting Resumable Media Download");
            downloadFile(false, updatedFile);
            DriveView.header1("Starting Simple Media Upload");
            uploadedFile = uploadFile(true);
            DriveView.header1("Starting Simple Media Download");
            downloadFile(true, uploadedFile);
            DriveView.header1("Success!");
            return;
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
    System.exit(1);
}

From source file:net.myrrix.online.eval.ParameterOptimizer.java

public static void main(String[] args) throws Exception {
    if (args.length < 4) {
        System.err.println(/*w  w  w  .  j  a v a  2s. c  o m*/
                "Usage: dataDirectory numSteps evaluationPercentage property=min:max [property2=min2:max2 ...]");
        return;
    }

    final File dataDir = new File(args[0]);
    Preconditions.checkArgument(dataDir.exists() && dataDir.isDirectory(), "Not a directory: %s", dataDir);
    Preconditions.checkArgument(dataDir.listFiles().length > 0, "No files in: %s", dataDir);
    int numSteps = Integer.parseInt(args[1]);
    Preconditions.checkArgument(numSteps >= 2, "# steps must be at least 2: %s", numSteps);
    final double evaluationPercentage = Double.parseDouble(args[2]);
    Preconditions.checkArgument(evaluationPercentage > 0.0 && evaluationPercentage <= 1.0,
            "evaluationPercentage must be in (0,1]: %s", evaluationPercentage);

    Map<String, ParameterRange> parameterRanges = Maps.newHashMapWithExpectedSize(args.length);
    for (int i = 3; i < args.length; i++) {
        String[] propValue = EQUALS.split(args[i]);
        String systemProperty = propValue[0];
        String[] minMax = COLON.split(propValue[1]);
        ParameterRange range;
        try {
            int min = Integer.parseInt(minMax[0]);
            int max = Integer.parseInt(minMax.length == 1 ? minMax[0] : minMax[1]);
            range = new ParameterRange(min, max);
        } catch (NumberFormatException ignored) {
            double min = Double.parseDouble(minMax[0]);
            double max = Double.parseDouble(minMax.length == 1 ? minMax[0] : minMax[1]);
            range = new ParameterRange(min, max);
        }
        parameterRanges.put(systemProperty, range);
    }

    Callable<Number> evaluator = new Callable<Number>() {
        @Override
        public Number call() throws IOException, TasteException, InterruptedException {
            MyrrixIRStatistics stats = (MyrrixIRStatistics) new PrecisionRecallEvaluator().evaluate(dataDir,
                    0.9, evaluationPercentage, null);
            return stats == null ? null : stats.getMeanAveragePrecision();
        }
    };

    ParameterOptimizer optimizer = new ParameterOptimizer(parameterRanges, numSteps, evaluator, false);
    Map<String, Number> optimalValues = optimizer.findGoodParameterValues();
    System.out.println(optimalValues);
}

From source file:com.pradeep.blackjack.card.CardFactory.java

/**
 *
 * @param suit//ww  w  . j  a v a  2s.  com
 * @param rank
 * @return
 * @throws IllegalArgumentException
 */
public static ICard newCard(Suit suit, int rank) {
    Preconditions.checkArgument(rank < 14 && rank > 0, "Rank must be between 1 and 13. Given {}", rank);
    if (rank == 1) {
        return new AceCard(suit);
    } else if (rank > 10) {
        return new FaceCard(suit, rank);
    } else {
        return new Card(suit, rank);
    }
}

From source file:org.locationtech.geogig.plumbing.diff.AttributeDiffFactory.java

public static AttributeDiff attributeDiffFromText(Class<?> clazz, String s) {

    String[] tokens = s.split("\t");
    AttributeDiff ad;/*  w ww  .jav  a  2 s  .  com*/
    if (Geometry.class.isAssignableFrom(clazz)) {
        ad = new GeometryAttributeDiff(s);
    } else {
        if (AttributeDiff.TYPE.REMOVED.name().startsWith(tokens[0])) {
            Preconditions.checkArgument(tokens.length == 2, "Wrong difference definition:", s);
            Object oldValue = TextValueSerializer.fromString(FieldType.forBinding(clazz), tokens[1]);
            ad = new GenericAttributeDiffImpl(oldValue, null);
        } else if (AttributeDiff.TYPE.ADDED.name().startsWith(tokens[0])) {
            Preconditions.checkArgument(tokens.length == 2, "Wrong difference definition:", s);
            Object newValue = TextValueSerializer.fromString(FieldType.forBinding(clazz), tokens[1]);
            ad = new GenericAttributeDiffImpl(null, newValue);
        } else if (AttributeDiff.TYPE.MODIFIED.name().startsWith(tokens[0])) {
            Preconditions.checkArgument(tokens.length == 3, "Wrong difference definition:", s);
            Object oldValue = TextValueSerializer.fromString(FieldType.forBinding(clazz), tokens[1]);
            Object newValue = TextValueSerializer.fromString(FieldType.forBinding(clazz), tokens[2]);
            ad = new GenericAttributeDiffImpl(oldValue, newValue);
        } else {
            throw new IllegalArgumentException("Wrong difference definition:" + s);
        }
    }
    return ad;

}

From source file:com.google.uzaygezen.core.BigIntegerMath.java

public static byte[] nonnegativeBigIntegerToBigEndianByteArrayForBitSize(BigInteger s, int size) {
    // It will have at least one sign bit.
    byte[] b = s.toByteArray();
    Preconditions.checkArgument(b[0] >= 0, "%s is negative", s);
    int n = MathUtils.bitCountToByteCount(size);
    Preconditions.checkArgument(b.length <= n + 1, "%s has bits that are two high", s);
    int start;//from  w  w  w .jav a 2  s . c  o  m
    if (b.length == n + 1) {
        Preconditions.checkArgument(size == n << 3,
                "A BigInteger's big endian length of %s cannot be copied into size=%s.", b.length, size);
        Preconditions.checkArgument(b[0] == 0, "The first byte is a sign bit, and it must be zero.");
        start = 1;
    } else {
        start = 0;
    }
    final byte[] array;
    if (b.length != n) {
        array = new byte[n];
        int len = b.length - start;
        System.arraycopy(b, start, array, n - len, len);
    } else {
        // Optimisation, but this branch is not otherwise necessary. 
        array = b;
    }
    return array;
}

From source file:org.locationtech.geogig.api.plumbing.diff.AttributeDiffFactory.java

public static AttributeDiff attributeDiffFromText(Class<?> clazz, String s) {

    String[] tokens = s.split("\t");
    AttributeDiff ad;// ww w.j  a va 2 s .c o m
    if (Geometry.class.isAssignableFrom(clazz)) {
        ad = new GeometryAttributeDiff(s);
    } else {
        if (AttributeDiff.TYPE.REMOVED.name().startsWith(tokens[0])) {
            Preconditions.checkArgument(tokens.length == 2, "Wrong difference definition:", s);
            Object oldValue = TextValueSerializer.fromString(FieldType.forBinding(clazz), tokens[1]);
            ad = new GenericAttributeDiffImpl(Optional.fromNullable(oldValue), null);
        } else if (AttributeDiff.TYPE.ADDED.name().startsWith(tokens[0])) {
            Preconditions.checkArgument(tokens.length == 2, "Wrong difference definition:", s);
            Object newValue = TextValueSerializer.fromString(FieldType.forBinding(clazz), tokens[1]);
            ad = new GenericAttributeDiffImpl(null, Optional.fromNullable(newValue));
        } else if (AttributeDiff.TYPE.MODIFIED.name().startsWith(tokens[0])) {
            Preconditions.checkArgument(tokens.length == 3, "Wrong difference definition:", s);
            Object oldValue = TextValueSerializer.fromString(FieldType.forBinding(clazz), tokens[1]);
            Object newValue = TextValueSerializer.fromString(FieldType.forBinding(clazz), tokens[2]);
            ad = new GenericAttributeDiffImpl(Optional.fromNullable(oldValue), Optional.fromNullable(newValue));
        } else {
            throw new IllegalArgumentException("Wrong difference definition:" + s);
        }
    }
    return ad;

}

From source file:com.cloudera.oryx.kmeans.computation.covariance.CovarianceData.java

public static CovarianceData parse(String line) {
    String[] pieces = DelimitedDataUtils.decode(line);
    Preconditions.checkArgument(pieces.length == 6, "Invalid covariance data: %s", line);
    return new CovarianceData(Integer.valueOf(pieces[0]), Integer.valueOf(pieces[1]),
            Integer.valueOf(pieces[2]), Integer.valueOf(pieces[3]), Double.valueOf(pieces[4]),
            Double.valueOf(pieces[5]));
}