Example usage for com.google.common.base Optional get

List of usage examples for com.google.common.base Optional get

Introduction

In this page you can find the example usage for com.google.common.base Optional get.

Prototype

public abstract T get();

Source Link

Document

Returns the contained instance, which must be present.

Usage

From source file:com.github.rinde.rinsim.examples.experiment.ExperimentExample.java

/**
 * It is possible to use the application arguments directly for configuring
 * the experiment. The '-h' or '--help' argument will show the list of
 * options./*  w w w  .ja va  2s.  c o m*/
 * @param args The arguments supplied to the application.
 */
public static void main(String[] args) {
    int uiSpeedUp = 1;
    final int index = Arrays.binarySearch(args, "speedup");

    String[] arguments = args;
    if (index >= 0) {
        checkArgument(arguments.length > index + 1,
                "speedup option requires an integer indicating the speedup.");
        uiSpeedUp = Integer.parseInt(arguments[index + 1]);
        checkArgument(uiSpeedUp > 0, "speedup must be a positive integer.");
        final List<String> list = new ArrayList<>(Arrays.asList(arguments));
        list.remove(index + 1);
        list.remove(index);
        arguments = list.toArray(new String[] {});
    }

    final Optional<ExperimentResults> results;

    // Starts the experiment builder.
    results = Experiment.builder()

            // Adds a configuration to the experiment. A configuration configures an
            // algorithm that is supposed to handle or 'solve' a problem specified by
            // a scenario. A configuration can handle a scenario if it contains an
            // event handler for all events that occur in the scenario. The scenario
            // in this example contains four different events and registers an event
            // handler for each of them.
            .addConfiguration(MASConfiguration.builder()
                    .addEventHandler(AddDepotEvent.class, AddDepotEvent.defaultHandler())
                    .addEventHandler(AddParcelEvent.class, AddParcelEvent.defaultHandler())
                    // There is no default handle for vehicle events, here a non functioning
                    // handler is added, it can be changed to add a custom vehicle to the
                    // simulator.
                    .addEventHandler(AddVehicleEvent.class, CustomVehicleHandler.INSTANCE)
                    .addEventHandler(TimeOutEvent.class, TimeOutEvent.ignoreHandler())

                    // Note: if you multi-agent system requires the aid of a model (e.g.
                    // CommModel) it can be added directly in the configuration. Models that
                    // are only used for the solution side should not be added in the
                    // scenario as they are not part of the problem.
                    .build())

            // Adds the newly constructed scenario to the experiment. Every
            // configuration will be run on every scenario.
            .addScenario(createScenario())

            // The number of repetitions for each simulation. Each repetition will
            // have a unique random seed that is given to the simulator.
            .repeat(2)

            // The master random seed from which all random seeds for the
            // simulations will be drawn.
            .withRandomSeed(0)

            // The number of threads the experiment will use, this allows to run
            // several simulations in parallel. Note that when the GUI is used the
            // number of threads must be set to 1.
            .withThreads(1)

            // We add a post processor to the experiment. A post processor can read
            // the state of the simulator after it has finished. It can be used to
            // gather simulation results. The objects created by the post processor
            // end up in the ExperimentResults object that is returned by the
            // perform(..) method of Experiment.
            .usePostProcessor(new ExamplePostProcessor())

            // Adds the GUI just like it is added to a Simulator object.
            .showGui(View.builder().with(PlaneRoadModelRenderer.builder()).with(PDPModelRenderer.builder())
                    .with(TimeLinePanel.builder()).withResolution((int) RESOLUTION.x, (int) RESOLUTION.y)
                    .withAutoPlay().withAutoClose()
                    // For testing we allow to change the speed up via the args.
                    .withSpeedUp(uiSpeedUp).withTitleAppendix("Experiments example"))

            // Starts the experiment, but first reads the command-line arguments
            // that are specified for this application. By supplying the '-h' option
            // you can see an overview of the supported options.
            .perform(System.out, arguments);

    if (results.isPresent()) {

        for (final SimulationResult sr : results.get().getResults()) {
            // The SimulationResult contains all information about a specific
            // simulation, the result object is the object created by the post
            // processor, a String in this case.
            System.out.println(sr.getSimArgs().getRandomSeed() + " " + sr.getResultObject());
        }
    } else {
        throw new IllegalStateException("Experiment did not complete.");
    }
}

From source file:org.metastatic.treediff.Main.java

public static void main(String... argv) throws Exception {
    Optional<Command> command = Optional.absent();
    LongOpt[] longOpts = new LongOpt[] { new LongOpt("checksum", LongOpt.NO_ARGUMENT, null, CHECKSUM),
            new LongOpt("diff", LongOpt.NO_ARGUMENT, null, DIFF),
            new LongOpt("patch", LongOpt.NO_ARGUMENT, null, PATCH),
            new LongOpt("hash", LongOpt.REQUIRED_ARGUMENT, null, 'h'),
            new LongOpt("hash-length", LongOpt.REQUIRED_ARGUMENT, null, 'l'),
            new LongOpt("sums-file", LongOpt.REQUIRED_ARGUMENT, null, 's'),
            new LongOpt("diff-file", LongOpt.REQUIRED_ARGUMENT, null, 'd'),
            new LongOpt("output", LongOpt.REQUIRED_ARGUMENT, null, 'o'),
            new LongOpt("verbose", LongOpt.NO_ARGUMENT, null, 'v'),
            new LongOpt("strict-hash", LongOpt.NO_ARGUMENT, null, 'H'),
            new LongOpt("size-only", LongOpt.NO_ARGUMENT, null, 'S'),
            new LongOpt("help", LongOpt.NO_ARGUMENT, null, HELP),
            new LongOpt("version", LongOpt.NO_ARGUMENT, null, VERSION) };
    Optional<MessageDigest> hash = Optional.absent();
    Optional<Integer> hashLength = Optional.absent();
    Optional<String> inputFile = Optional.absent();
    Optional<String> outputFile = Optional.absent();
    Optional<DiffCheck> diffCheck = Optional.of(DiffCheck.SizeAndTime);
    Getopt getopt = new Getopt(Main.class.getName(), argv, "h:l:s:d:o:vH", longOpts);
    int ch;//  www  . ja  v  a 2  s.c o  m
    while ((ch = getopt.getopt()) != -1) {
        switch (ch) {
        case CHECKSUM:
            if (command.isPresent()) {
                System.err.printf("%s: only specify one command.%n", Main.class.getName());
                System.exit(1);
                return;
            }
            command = Optional.of(Command.Checksum);
            break;

        case DIFF:
            if (command.isPresent()) {
                System.err.printf("%s: only specify one command.%n", Main.class.getName());
                System.exit(1);
                return;
            }
            command = Optional.of(Command.Diff);
            break;

        case PATCH:
            if (command.isPresent()) {
                System.err.printf("%s: only specify one command.%n", Main.class.getName());
                System.exit(1);
                return;
            }
            command = Optional.of(Command.Patch);

        case HELP:
            help();
            System.exit(0);
            break;

        case VERSION:
            version();
            System.exit(0);
            break;

        case 'h':
            checkCommand("--hash", command, EnumSet.of(Command.Checksum));
            try {
                hash = Optional.of(MessageDigest.getInstance(getopt.getOptarg()));
            } catch (NoSuchAlgorithmException nsae) {
                try {
                    hash = Optional.of(MessageDigest.getInstance(getopt.getOptarg(), new JarsyncProvider()));
                } catch (NoSuchAlgorithmException nsae2) {
                    System.err.printf("%s: no such hash: %s%n", Main.class.getName(), getopt.getOptarg());
                    System.exit(1);
                    return;
                }
            }
            break;

        case 'l':
            checkCommand("--hash-length", command, EnumSet.of(Command.Checksum));
            try {
                hashLength = Optional.of(Integer.parseInt(getopt.getOptarg()));
            } catch (NumberFormatException nfe) {
                System.err.printf("%s: --hash-length: invalid number.%n", Main.class.getName());
                System.exit(1);
                return;
            }
            break;

        case 's':
            checkCommand("--sums-file", command, EnumSet.of(Command.Diff));
            inputFile = Optional.of(getopt.getOptarg());
            break;

        case 'd':
            checkCommand("--diff-file", command, EnumSet.of(Command.Patch));
            inputFile = Optional.of(getopt.getOptarg());
            break;

        case 'o':
            checkCommand("--output", command, EnumSet.of(Command.Checksum, Command.Diff));
            outputFile = Optional.of(getopt.getOptarg());
            break;

        case 'v':
            verbosity++;
            break;

        case 'H':
            checkCommand("--strict-hash", command, EnumSet.of(Command.Diff));
            diffCheck = Optional.of(DiffCheck.StrictHash);
            break;

        case 'S':
            checkCommand("--size-only", command, EnumSet.of(Command.Diff));
            diffCheck = Optional.of(DiffCheck.SizeOnly);
            break;

        case '?':
            System.err.printf("Try `%s --help' for more info.%n", Main.class.getName());
            System.exit(1);
            return;
        }
    }

    if (!command.isPresent()) {
        System.err.printf("%s: must supply a command.%n", Main.class.getName());
        System.exit(1);
        return;
    }

    switch (command.get()) {
    case Checksum: {
        if (!hash.isPresent())
            hash = Optional.of(MessageDigest.getInstance("Murmur3", new JarsyncProvider()));
        if (!hashLength.isPresent())
            hashLength = Optional.of(hash.get().getDigestLength());
        else if (hashLength.get() <= 0 || hashLength.get() > hash.get().getDigestLength()) {
            System.err.printf("%s: invalid hash length: %d.%n", Main.class.getName(), hashLength.get());
            System.exit(1);
            return;
        }
        if (!outputFile.isPresent()) {
            System.err.printf("%s: --output argument required.%n", Main.class.getName());
            System.exit(1);
            return;
        }
        if (getopt.getOptind() >= argv.length) {
            System.err.printf("%s: must specify at least one file or directory.%n", Main.class.getName());
            System.exit(1);
            return;
        }
        DataOutputStream output = new DataOutputStream(
                new BufferedOutputStream(new FileOutputStream(outputFile.get())));
        output.write(SUMS_MAGIC);
        String alg = hash.get().getAlgorithm();
        output.writeUTF(alg);
        output.writeInt(hashLength.get());
        checksum(hash.get(), hashLength.get(), output,
                Arrays.asList(argv).subList(getopt.getOptind(), argv.length));
        output.close();
        break;
    }

    case Diff: {
        if (!inputFile.isPresent()) {
            System.err.printf("%s: --diff: option --sums-file required.%n", Main.class.getName());
            System.exit(1);
            return;
        }
        if (!outputFile.isPresent()) {
            System.err.printf("%s: --output argument required.%n", Main.class.getName());
            System.exit(1);
            return;
        }
        DataInputStream input = new DataInputStream(new FileInputStream(inputFile.get()));
        byte[] magic = new byte[8];
        input.readFully(magic);
        if (!Arrays.equals(magic, SUMS_MAGIC)) {
            System.err.printf("%s: %s: invalid file header.%n", Main.class.getName(), inputFile.get());
            System.exit(1);
            return;
        }
        String alg = input.readUTF();
        try {
            hash = Optional.of(MessageDigest.getInstance(alg, new JarsyncProvider()));
        } catch (NoSuchAlgorithmException nsae) {
            hash = Optional.of(MessageDigest.getInstance(alg));
        }
        hashLength = Optional.of(input.readInt());
        if (hashLength.get() <= 0 || hashLength.get() > hash.get().getDigestLength()) {
            System.err.printf("%s: invalid hash length: %d.%n", Main.class.getName(), hashLength.get());
            System.exit(1);
            return;
        }
        DataOutputStream output = new DataOutputStream(
                new BufferedOutputStream(new FileOutputStream(outputFile.get())));
        output.write(DIFF_MAGIC);
        output.writeUTF(alg);
        output.writeInt(hashLength.get());
        diff(hash.get(), hashLength.get(), input, output, diffCheck.or(DiffCheck.SizeAndTime));
        output.close();
        break;
    }

    case Patch:
        throw new Error("not yet implemented");
    }
}

From source file:com.facebook.presto.sql.analyzer.Optionals.java

public static <T> Function<Optional<T>, T> optionalGetter() {
    return new Function<Optional<T>, T>() {
        @Override// w  w  w  . ja v a  2  s  .co  m
        public T apply(Optional<T> input) {
            return input.get();
        }
    };
}

From source file:li.klass.fhem.util.Optionals.java

public static <T> Function<Optional<T>, T> get() {
    return new Function<Optional<T>, T>() {
        @Override/*from w  w w .  j av a  2s  .  c o m*/
        public T apply(Optional<T> input) {
            return input.get();
        }
    };
}

From source file:org.openo.msb.wrapper.consul.option.Options.java

static <T> WebTarget optionallyAdd(WebTarget input, String key, Optional<T> val) {
    return val.isPresent() ? input.queryParam(key, val.get()) : input;
}

From source file:org.ldp4j.tutorial.frontend.util.Mapper.java

public static String toStringOrNull(Optional<URI> individual) {
    return individual.isPresent() ? individual.get().toString() : null;
}

From source file:net.caseif.flint.steel.util.helper.ChatHelper.java

private static boolean checkRoundBarrier(Optional<Challenger> ch) {
    return ch.isPresent() && ch.get().getRound().getConfigValue(ConfigNode.SEPARATE_ROUND_CHATS);
}

From source file:myokun.mods.elex.worldgen.biome.Biomes.java

private static void registerBiome(Optional<? extends BiomeGenBase> biome) {
    if (biome.isPresent()) {
        GameRegistry.addBiome(biome.get());
    }/*from  ww w.j  a  va 2s.c  o m*/
}

From source file:org.dswarm.graph.delta.match.model.util.CSEntityUtil.java

public static Optional<? extends Collection<ValueEntity>> getValueEntities(
        final Optional<? extends Collection<CSEntity>> csEntities) {

    if (!csEntities.isPresent() || csEntities.get().isEmpty()) {

        return Optional.absent();
    }//from  ww w. jav a  2  s.  c  om

    final Set<ValueEntity> valueEntities = new HashSet<>();

    for (final CSEntity csEntity : csEntities.get()) {

        valueEntities.addAll(csEntity.getValueEntities());
    }

    return Optional.of(valueEntities);
}

From source file:org.sonar.server.computation.task.projectanalysis.formula.coverage.CoverageUtils.java

static double getMeasureVariations(CounterInitializationContext counterContext, String metricKey) {
    Optional<Measure> measure = counterContext.getMeasure(metricKey);
    if (!measure.isPresent() || !measure.get().hasVariation()) {
        return 0d;
    }/*from ww w . j a  v a 2 s .  c o m*/
    return measure.get().getVariation();
}