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

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

Introduction

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

Prototype

public abstract boolean isPresent();

Source Link

Document

Returns true if this holder contains a (non-null) instance.

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./*from ww  w  . ja  v  a2 s  .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.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:com.facebook.presto.sql.analyzer.Optionals.java

public static Predicate<Optional<?>> isPresentPredicate() {
    return new Predicate<Optional<?>>() {
        @Override/*from   w w w  . j  av  a 2  s .c o m*/
        public boolean apply(Optional<?> input) {
            return input.isPresent();
        }
    };
}

From source file:org.apache.gobblin.util.JvmUtils.java

/**
 * Formats the specified jvm arguments such that any tokens are replaced with concrete values;
 * @param jvmArguments/*from  w  ww  .  j a v a 2s  .  c o m*/
 * @return The formatted jvm arguments.
 */
public static String formatJvmArguments(Optional<String> jvmArguments) {
    if (jvmArguments.isPresent()) {
        return PORT_UTILS.replacePortTokens(jvmArguments.get());
    }
    return StringUtils.EMPTY;
}

From source file:se.sics.ktoolbox.util.config.KConfig.java

public static <T> T readValue(Config config, String key, Class<T> type) {
    Optional<T> val = config.readValue(key, type);
    if (!val.isPresent()) {
        LOG.error("missing:{}", key);
        throw new RuntimeException("missing:" + key);
    }//from  w w w.  java 2s  .  co  m
    return val.get();
}

From source file:se.sics.ktoolbox.util.config.KConfigHelper.java

public static <O extends Object> O read(Config config, Base<O> opt) {
    Logger LOG = LoggerFactory.getLogger("KConfig");
    Optional<O> optValue = opt.readValue(config);
    if (!optValue.isPresent()) {
        LOG.error("missing:{}", opt.name);
        throw new RuntimeException("missing " + opt.name);
    }/*  ww  w.j  ava2 s . c  o  m*/
    return optValue.get();
}

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());
    }/*  w ww . java  2  s  .c  o m*/
}

From source file:org.sonar.server.permission.PermissionPrivilegeChecker.java

public static void checkProjectAdminUserByComponentDto(UserSession userSession,
        Optional<ComponentDto> project) {
    if (project.isPresent()) {
        checkProjectAdminUserByComponentUuid(userSession, project.get().uuid());
    } else {/*  w  w  w. ja  va  2s  .c o  m*/
        checkGlobalAdminUser(userSession);
    }
}

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:org.igov.service.business.object.ObjectPlaceService.java

/**
 * This method allows to swap two entities by Primary Key (PK).
 *
 * @param entity          - entity with new parameters
 * @param persistedEntity - persisted entity with registered PK in DB
 * @param dao             - type-specific dao implementation
 **//*from w  w w.j a  v  a2 s  .co m*/
@SuppressWarnings("unchecked")
public static <T extends AbstractEntity> boolean swap(T entity, Optional<T> persistedEntity, EntityDao dao) {
    if (persistedEntity.isPresent()) {
        entity.setId(persistedEntity.get().getId());
        dao.saveOrUpdate(entity);
        return true;
    }
    return false;
}