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

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

Introduction

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

Prototype

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

Source Link

Document

Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method.

Usage

From source file:kn.uni.gis.dataimport.GenerateCSV.java

public static void main(String[] args) throws IOException, InterruptedException {
    for (File file : new File(PATH).listFiles(new FilenameFilter() {
        @Override/*from w w w. j a  va 2 s  .c om*/
        public boolean accept(File dir, String name) {
            return name.endsWith(".shp");
        }
    })) {
        ProcessBuilder builder = new ProcessBuilder("lib/shp2text", "--spreadsheet", file.getAbsolutePath());

        System.out.println("executing: " + builder.command());

        final Process start = builder.start();

        new StreamConsumer(new InputSupplier<Reader>() {
            public Reader getInput() throws IOException {
                return new InputStreamReader(start.getInputStream());
            }
        }, Files.newWriterSupplier(new File(OUTPUT + file.getName() + ".csv"), Charsets.UTF_8)).start();
        new StreamConsumer(new InputSupplier<Reader>() {
            public Reader getInput() throws IOException {
                return new InputStreamReader(start.getErrorStream());
            }
        }, Files.newWriterSupplier(new File(OUTPUT + file.getName() + ".csv"), Charsets.UTF_8)).start();
        Preconditions.checkState(start.waitFor() == 0, "error ");
    }
}

From source file:ezbake.thriftrunner.ThriftRunner.java

public static void main(String[] args) throws Exception {
    ThriftStarter thriftStarter = null;//from   w  ww  .  j av a  2  s.  c o m
    if (OpenShiftUtil.inOpenShiftContainer()) {
        thriftStarter = new OpenShiftStarter();
    } else {
        thriftStarter = new SimpleStarter();
    }

    final CommonOptions commonOptions = parseArgs(args, thriftStarter);

    final File jarFile = Preconditions.checkNotNull(commonOptions.jarFile, "A jar file must be specified!");
    Preconditions.checkState(jarFile.exists() && jarFile.isFile(),
            jarFile + " does not exist or is not a file!");

    final Properties configuration = getMergedConfig(commonOptions);

    setupLogging(configuration, commonOptions.loggingConfig);

    thriftStarter.initialize();

    /* args4j for boolean  will set to true if we enable an option, in this case we want to disable something, hence
     the '!' */
    final EzBakeBaseThriftService service = getServiceFromJar(jarFile, thriftStarter, configuration);

    System.out.println("Thrift server starting on " + thriftStarter.getPrivateHostInfo());

    boolean serviceDiscoveryEnabled = !commonOptions.serviceDiscoveryDisabled;
    // Will start the server and block until the JVM is shut down, thus stopping the service, unregistering, etc.
    new EZBakeBaseThriftServiceRunner(service, thriftStarter, serviceDiscoveryEnabled).run();
}

From source file:com.mapr.PurchaseLog.java

public static void main(String[] args) throws IOException {
    Options opts = new Options();
    CmdLineParser parser = new CmdLineParser(opts);
    try {/*w w w .j  a v a 2 s .c o  m*/
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println("Usage: -count <number>G|M|K [ -users number ]  log-file user-profiles");
        return;
    }

    Joiner withTab = Joiner.on("\t");

    // first generate lots of user definitions
    SchemaSampler users = new SchemaSampler(
            Resources.asCharSource(Resources.getResource("user-schema.txt"), Charsets.UTF_8).read());
    File userFile = File.createTempFile("user", "tsv");
    BufferedWriter out = Files.newBufferedWriter(userFile.toPath(), Charsets.UTF_8);
    for (int i = 0; i < opts.users; i++) {
        out.write(withTab.join(users.sample()));
        out.newLine();
    }
    out.close();

    // now generate a session for each user
    Splitter onTabs = Splitter.on("\t");
    Splitter onComma = Splitter.on(",");

    Random gen = new Random();
    SchemaSampler intermediate = new SchemaSampler(
            Resources.asCharSource(Resources.getResource("hit_step.txt"), Charsets.UTF_8).read());

    final int COUNTRY = users.getFieldNames().indexOf("country");
    final int CAMPAIGN = intermediate.getFieldNames().indexOf("campaign_list");
    final int SEARCH_TERMS = intermediate.getFieldNames().indexOf("search_keywords");
    Preconditions.checkState(COUNTRY >= 0, "Need country field in user schema");
    Preconditions.checkState(CAMPAIGN >= 0, "Need campaign_list field in step schema");
    Preconditions.checkState(SEARCH_TERMS >= 0, "Need search_keywords field in step schema");

    out = Files.newBufferedWriter(new File(opts.out).toPath(), Charsets.UTF_8);

    for (String line : Files.readAllLines(userFile.toPath(), Charsets.UTF_8)) {
        long t = (long) (TimeUnit.MILLISECONDS.convert(30, TimeUnit.DAYS) * gen.nextDouble());
        List<String> user = Lists.newArrayList(onTabs.split(line));

        // pick session length
        int n = (int) Math.floor(-30 * Math.log(gen.nextDouble()));

        for (int i = 0; i < n; i++) {
            // time on page
            int dt = (int) Math.floor(-20000 * Math.log(gen.nextDouble()));
            t += dt;

            // hit specific values
            JsonNode step = intermediate.sample();

            // check for purchase
            double p = 0.01;
            List<String> campaigns = Lists.newArrayList(onComma.split(step.get("campaign_list").asText()));
            List<String> keywords = Lists.newArrayList(onComma.split(step.get("search_keywords").asText()));
            if ((user.get(COUNTRY).equals("us") && campaigns.contains("5"))
                    || (user.get(COUNTRY).equals("jp") && campaigns.contains("7")) || keywords.contains("homer")
                    || keywords.contains("simpson")) {
                p = 0.5;
            }

            String events = gen.nextDouble() < p ? "1" : "-";

            out.write(Long.toString(t));
            out.write("\t");
            out.write(line);
            out.write("\t");
            out.write(withTab.join(step));
            out.write("\t");
            out.write(events);
            out.write("\n");
        }
    }
    out.close();
}

From source file:com.mapr.synth.Synth.java

public static void main(String[] args)
        throws IOException, CmdLineException, InterruptedException, ExecutionException {
    final Options opts = new Options();
    CmdLineParser parser = new CmdLineParser(opts);
    try {//  w  w w . java2 s . co m
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println("Usage: " + "[ -count <number>G|M|K ] " + "-schema schema-file "
                + "[-quote DOUBLE_QUOTE|BACK_SLASH|OPTIMISTIC] " + "[-format JSON|TSV|CSV|XML ] "
                + "[-threads n] " + "[-output output-directory-name] ");
        throw e;
    }
    Preconditions.checkArgument(opts.threads > 0 && opts.threads <= 2000,
            "Must have at least one thread and no more than 2000");

    if (opts.threads > 1) {
        Preconditions.checkArgument(!"-".equals(opts.output),
                "If more than on thread is used, you have to use -output to set the output directory");
    }

    File outputDir = new File(opts.output);
    if (!"-".equals(opts.output)) {
        if (!outputDir.exists()) {
            Preconditions.checkState(outputDir.mkdirs(),
                    String.format("Couldn't create output directory %s", opts.output));
        }
        Preconditions.checkArgument(outputDir.exists() && outputDir.isDirectory(),
                String.format("Couldn't create directory %s", opts.output));
    }

    if (opts.schema == null) {
        throw new IllegalArgumentException("Must specify schema file using [-schema filename] option");
    }
    final SchemaSampler sampler = new SchemaSampler(opts.schema);
    final AtomicLong rowCount = new AtomicLong();

    final List<ReportingWorker> tasks = Lists.newArrayList();
    int limit = (opts.count + opts.threads - 1) / opts.threads;
    int remaining = opts.count;
    for (int i = 0; i < opts.threads; i++) {

        final int count = Math.min(limit, remaining);
        remaining -= count;

        tasks.add(new ReportingWorker(opts, sampler, rowCount, count, i));
    }

    final double t0 = System.nanoTime() * 1e-9;
    ExecutorService pool = Executors.newFixedThreadPool(opts.threads);
    ScheduledExecutorService blinker = Executors.newScheduledThreadPool(1);
    final AtomicBoolean finalRun = new AtomicBoolean(false);

    final PrintStream sideLog = new PrintStream(new FileOutputStream("side-log"));
    Runnable blink = new Runnable() {
        public double oldT;
        private long oldN;

        @Override
        public void run() {
            double t = System.nanoTime() * 1e-9;
            long n = rowCount.get();
            System.err.printf("%s\t%d\t%.1f\t%d\t%.1f\t%.3f\n", finalRun.get() ? "F" : "R", opts.threads,
                    t - t0, n, n / (t - t0), (n - oldN) / (t - oldT));
            for (ReportingWorker task : tasks) {
                ReportingWorker.ThreadReport r = task.report();
                sideLog.printf("\t%d\t%.2f\t%.2f\t%.2f\t%.1f\t%.1f\n", r.fileNumber, r.threadTime, r.userTime,
                        r.wallTime, r.rows / r.threadTime, r.rows / r.wallTime);
            }
            oldN = n;
            oldT = t;
        }
    };
    if (!"-".equals(opts.output)) {
        blinker.scheduleAtFixedRate(blink, 0, 10, TimeUnit.SECONDS);
    }
    List<Future<Integer>> results = pool.invokeAll(tasks);

    int total = 0;
    for (Future<Integer> result : results) {
        total += result.get();
    }
    Preconditions.checkState(total == opts.count, String
            .format("Expected to generate %d lines of output, but actually generated %d", opts.count, total));
    pool.shutdownNow();
    blinker.shutdownNow();
    finalRun.set(true);
    sideLog.close();
    blink.run();
}

From source file:pocman.demo.ClosedCPPDemo.java

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

    final Stopwatch stopwatch = new Stopwatch();

    final ClosedCPPDemo that = new ClosedCPPDemo(MATCHING_ALGORITHM_1);

    for (final String level : Mazes.LEVELS) {
        final int pocManPosition = level.indexOf(Tile.POCMAN.toCharacter());
        Preconditions.checkState(pocManPosition > -1, "POCMAN POSITION NOT FOUND !");
        final char[] data = level.toCharArray();
        data[pocManPosition] = Tile.COIN.toCharacter();

        final Maze maze = Maze.from(data);

        stopwatch.start();//from   w  w w.  ja va  2  s  . c o  m
        final ClosedCPPSolution<MazeNode> closedCPPSolution = that.solve(maze);
        stopwatch.stop();

        final EulerianTrailInterface<MazeNode> eulerianTrailInterface = maze.get()
                .fetch(EulerianTrailFeature.class).up();
        final List<MazeNode> closedTrail = eulerianTrailInterface.getEulerianTrail(maze.getNode(pocManPosition),
                closedCPPSolution.getTraversalByEdge()); // TODO ! maze.getEulerianTrail(startingMazeNode)

        that.debug(maze, closedTrail, 160);
        System.out.println(closedCPPSolution);
        Thread.sleep(1000);

        /*
        stopwatch.start();
        final OpenCPPSolution<MazeNode> openCPPSolution = that.solve(closedCPPSolution, maze.getNode(pocManPosition));
        stopwatch.stop();
                
        final List<MazeNode> trail = EulerianTrail.from(
            openCPPSolution.getGraph(),
            openCPPSolution.getTraversalByEdge(),
            openCPPSolution.getEndPoint());
                
        that.debug(maze, trail, 160);
        */

        //break;
    }

    /*
    stopwatch.start();
    final OpenCPPSolution<MazeNode> openCPPSolution = that.solve(closedCPPSolution, maze.getNode(pocManPosition));
    stopwatch.stop();
            
    final List<MazeNode> trail = EulerianTrail.from(
        openCPPSolution.getGraph(),
        openCPPSolution.getTraversalByEdge(),
        openCPPSolution.getEndPoint());
            
    that.debug(maze, trail, 320);
    System.out.println(openCPPSolution);
    Thread.sleep(1000);
    */

    //}

    System.out.println(stopwatch.elapsedTime(TimeUnit.MILLISECONDS) + " " + TimeUnit.MILLISECONDS.toString());
}

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

public static Optional<Prominence> getByOrdering(ObjectContext context, Integer ordering) {
    Preconditions.checkArgument(null != context, "the context must be supplied");
    Preconditions.checkState(null != ordering && ordering >= 0, "bad ordering");
    return getAll(context).stream().filter((p) -> p.getOrdering().equals(ordering)).findFirst();
}

From source file:works.chatterbox.hooks.ircchannels.channels.modes.Mode.java

static Mode fromString(@NotNull final String string) {
    Preconditions.checkNotNull(string);/* www  .  j av  a2s  .co  m*/
    Preconditions.checkArgument(string.length() > 0, "Zero-length (or smaller) string given");
    final char modeChar = string.charAt(0);
    final Mode mode = IRCChannelsAPI.getInstance().getModesAPI().getModes().getMode(modeChar);
    Preconditions.checkState(mode != null, "No mode for " + modeChar);
    if (mode.getArgumentLength() > 0) {
        Preconditions.checkState(string.length() > 2, "No arguments for mode requiring arguments");
        final String[] args = string.substring(2).split(" ");
        Preconditions.checkState(args.length == mode.getArgumentLength(),
                "Invalid number of arguments. Expected " + mode.getArgumentLength() + ", received "
                        + args.length);
        final List<String> arguments = Arrays.stream(args).collect(Collectors.toList());
        //noinspection unchecked
        mode.setArguments(arguments);
    }
    return mode;
}

From source file:org.opendaylight.controller.config.yangjmxgenerator.attribute.SimpleTypeResolver.java

public static SimpleType<?> getSimpleType(Type type) {
    SimpleType<?> expectedSimpleType = JAVA_TYPE_TO_SIMPLE_TYPE.get(type.getFullyQualifiedName());
    Preconditions.checkState(expectedSimpleType != null,
            "Cannot find simple type for " + type.getFullyQualifiedName());
    return expectedSimpleType;
}

From source file:com.turn.griffin.utils.GriffinConfig.java

private static void init() {
    properties = new Properties();
    try (FileInputStream fis = new FileInputStream(configFile)) {
        properties.load(fis);//  w  ww. j av  a  2  s  .  co m
    } catch (IOException e) {
        Preconditions.checkState(false, e.getMessage());
    }
}

From source file:com.facebook.util.Validations.java

public static <T extends Exception> void checkState(boolean expression, Class<T> clazz, String message)
        throws T {
    try {//from   w  w  w. java2  s .  c o  m
        Preconditions.checkState(expression, message);
    } catch (Exception e) {
        throw ExceptionUtils.wrap(e, clazz);
    }
}