List of usage examples for java.util Optional of
public static <T> Optional<T> of(T value)
From source file:Main.java
public static void main(String[] args) { Optional<String> value = Optional.of("some value"); System.out.println(value.isPresent()); System.out.println(value.get()); }
From source file:Main.java
public static void main(String[] args) { Optional<String> optional = Optional.of("bam"); optional.isPresent(); // true optional.get(); // "bam" optional.orElse("fallback"); // "bam" optional.ifPresent((s) -> System.out.println(s.charAt(0))); // "b" }
From source file:Main.java
public static void main(String[] args) { String str = null; Optional value = Optional.of(str); }
From source file:Main.java
public static void main(String[] args) { Optional<String> optional1 = Optional.empty(); Optional<String> optional2 = Optional.of("DEMO"); System.out.println("optional2.get = " + optional2.get()); System.out.println("optional1.orElse = " + optional1.orElse("Something else")); optional2.ifPresent(System.out::println); System.out.println("optional1.isPresent = " + optional1.isPresent()); }
From source file:Main.java
public static void main(String[] args) { Optional<String> value = Optional.of("some value"); System.out.println(value.isPresent()); System.out.println(value.get()); String str = null;/*from ww w. jav a 2 s .c o m*/ // Optional.of(str); Optional<Integer> o = Optional.empty(); System.out.println(o.isPresent()); System.out.println(o.orElse(42)); List<Integer> results = new ArrayList<>(); Optional<Integer> second = Optional.of(3); second.ifPresent(results::add); // must operate via side-effects, // unfortunately... System.out.println(results); o = Optional.empty(); System.out.println(o.orElse(42)); o = Optional.of(42); System.out.println(o.get()); o = Optional.empty(); o.get(); }
From source file:com.ikanow.aleph2.remote.es_tests.SimpleReadableCrudTest.java
public static void main(final String args[]) throws Exception { if (args.length < 1) { System.out.println("CLI: <host>"); System.exit(-1);//from ww w . j av a 2s. c o m } final String temp_dir = System.getProperty("java.io.tmpdir") + File.separator; Config config = ConfigFactory .parseReader(new InputStreamReader( SimpleReadableCrudTest.class.getResourceAsStream("/test_es_remote.properties"))) .withValue("globals.local_root_dir", ConfigValueFactory.fromAnyRef(temp_dir)) .withValue("globals.local_cached_jar_dir", ConfigValueFactory.fromAnyRef(temp_dir)) .withValue("globals.distributed_root_dir", ConfigValueFactory.fromAnyRef(temp_dir)) .withValue("globals.local_yarn_config_dir", ConfigValueFactory.fromAnyRef(temp_dir)) .withValue("MongoDbManagementDbService.mongodb_connection", ConfigValueFactory.fromAnyRef(args[0] + ":27017")) .withValue("ElasticsearchCrudService.elasticsearch_connection", ConfigValueFactory.fromAnyRef(args[0] + ":9300")); final SimpleReadableCrudTest app = new SimpleReadableCrudTest(); final Injector app_injector = ModuleUtils.createTestInjector(Arrays.asList(), Optional.of(config)); app_injector.injectMembers(app); app.runTest(); System.exit(0); }
From source file:com.ikanow.aleph2.enrichment.utils.services.JsScriptEngineTestService.java
/** Entry point * @param args// w w w . j a va2 s. c o m * @throws IOException */ public static void main(String[] args) throws IOException { if (args.length < 3) { System.out .println("ARGS: <script-file> <input-file> <output-prefix> [{[len: <LEN>], [group: <GROUP>]}]"); } // STEP 1: load script file final String user_script = Files.toString(new File(args[0]), Charsets.UTF_8); // STEP 2: get a stream for the JSON file final InputStream io_stream = new FileInputStream(new File(args[1])); // STEP 3: set up control if applicable Optional<JsonNode> json = Optional.of("").filter(__ -> args.length > 3).map(__ -> args[3]) .map(Lambdas.wrap_u(j -> _mapper.readTree(j))); // STEP 4: set up the various objects final DataBucketBean bucket = Mockito.mock(DataBucketBean.class); final JsScriptEngineService service_under_test = new JsScriptEngineService(); final LinkedList<ObjectNode> emitted = new LinkedList<>(); final LinkedList<JsonNode> grouped = new LinkedList<>(); final LinkedList<JsonNode> externally_emitted = new LinkedList<>(); final IEnrichmentModuleContext context = Mockito.mock(IEnrichmentModuleContext.class, new Answer<Void>() { @SuppressWarnings("unchecked") public Void answer(InvocationOnMock invocation) { try { Object[] args = invocation.getArguments(); if (invocation.getMethod().getName().equals("emitMutableObject")) { final Optional<JsonNode> grouping = (Optional<JsonNode>) args[3]; if (grouping.isPresent()) { grouped.add(grouping.get()); } emitted.add((ObjectNode) args[1]); } else if (invocation.getMethod().getName().equals("externalEmit")) { final DataBucketBean to = (DataBucketBean) args[0]; final Either<JsonNode, Map<String, Object>> out = (Either<JsonNode, Map<String, Object>>) args[1]; externally_emitted .add(((ObjectNode) out.left().value()).put("__a2_bucket", to.full_name())); } } catch (Exception e) { e.printStackTrace(); } return null; } }); final EnrichmentControlMetadataBean control = BeanTemplateUtils.build(EnrichmentControlMetadataBean.class) .with(EnrichmentControlMetadataBean::config, new LinkedHashMap<String, Object>( ImmutableMap.<String, Object>builder().put("script", user_script).build())) .done().get(); service_under_test.onStageInitialize(context, bucket, control, Tuples._2T(ProcessingStage.batch, ProcessingStage.grouping), Optional.empty()); final BeJsonParser json_parser = new BeJsonParser(); // Run the file through final Stream<Tuple2<Long, IBatchRecord>> json_stream = StreamUtils .takeUntil(Stream.generate(() -> json_parser.getNextRecord(io_stream)), i -> null == i) .map(j -> Tuples._2T(0L, new BatchRecord(j))); service_under_test.onObjectBatch(json_stream, json.map(j -> j.get("len")).map(j -> (int) j.asLong(0L)), json.map(j -> j.get("group"))); System.out.println("RESULTS: "); System.out.println("emitted: " + emitted.size()); System.out.println("grouped: " + grouped.size()); System.out.println("externally emitted: " + externally_emitted.size()); Files.write(emitted.stream().map(j -> j.toString()).collect(Collectors.joining(";")), new File(args[2] + "emit.json"), Charsets.UTF_8); Files.write(grouped.stream().map(j -> j.toString()).collect(Collectors.joining(";")), new File(args[2] + "group.json"), Charsets.UTF_8); Files.write(externally_emitted.stream().map(j -> j.toString()).collect(Collectors.joining(";")), new File(args[2] + "external_emit.json"), Charsets.UTF_8); }
From source file:com.arpnetworking.metrics.mad.Main.java
/** * Entry point for Metrics Aggregator Daemon (MAD). * * @param args the command line arguments *//* w ww.jav a 2 s . c om*/ public static void main(final String[] args) { // Global initialization Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> { System.err.println("Unhandled exception! exception: " + throwable.toString()); throwable.printStackTrace(System.err); }); Thread.currentThread().setUncaughtExceptionHandler((thread, throwable) -> LOGGER.error() .setMessage("Unhandled exception!").setThrowable(throwable).log()); LOGGER.info().setMessage("Launching mad").log(); Runtime.getRuntime().addShutdownHook(SHUTDOWN_THREAD); System.setProperty("org.vertx.logger-delegate-factory-class-name", "org.vertx.java.core.logging.impl.SLF4JLogDelegateFactory"); // Run the tsd aggregator if (args.length != 1) { throw new RuntimeException("No configuration file specified"); } LOGGER.debug().setMessage("Loading configuration").addData("file", args[0]).log(); Optional<DynamicConfiguration> configuration = Optional.empty(); Optional<Configurator<Main, AggregatorConfiguration>> configurator = Optional.empty(); try { final File configurationFile = new File(args[0]); configurator = Optional.of(new Configurator<>(Main::new, AggregatorConfiguration.class)); configuration = Optional.of(new DynamicConfiguration.Builder().setObjectMapper(OBJECT_MAPPER) .addSourceBuilder(getFileSourceBuilder(configurationFile)) .addTrigger(new FileTrigger.Builder().setFile(configurationFile).build()) .addListener(configurator.get()).build()); configuration.get().launch(); // Wait for application shutdown SHUTDOWN_SEMAPHORE.acquire(); } catch (final InterruptedException e) { throw Throwables.propagate(e); } finally { if (configurator.isPresent()) { configurator.get().shutdown(); } if (configuration.isPresent()) { configuration.get().shutdown(); } // Notify the shutdown that we're done SHUTDOWN_SEMAPHORE.release(); } }
From source file:com.ikanow.aleph2.data_import_manager.harvest.modules.LocalHarvestTestModule.java
/** Entry point * @param args - config_file source_key harvest_tech_id * @throws Exception //from ww w . java 2 s. c o m */ public static void main(final String[] args) { try { if (args.length < 3) { System.out.println("CLI: config_file source_key harvest_tech_jar_path"); System.exit(-1); } System.out.println("Running with command line: " + Arrays.toString(args)); Config config = ConfigFactory.parseFile(new File(args[0])); LocalHarvestTestModule app = ModuleUtils.initializeApplication(Arrays.asList(), Optional.of(config), Either.left(LocalHarvestTestModule.class)); app.start(args[1], args[2], Arrays.copyOfRange(args, 3, args.length)); } catch (Exception e) { try { System.out.println("Got all the way to main"); e.printStackTrace(); } catch (Exception e2) { // the exception failed! System.out.println(ErrorUtils.getLongForm("Got all the way to main: {0}", e)); } } }
From source file:com.act.biointerpretation.l2expansion.L2ExpansionDriver.java
public static void main(String[] args) throws Exception { // Build command line parser. Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());//from w ww . j av a 2s . c o m } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { LOGGER.error("Argument parsing failed: %s", e.getMessage()); HELP_FORMATTER.printHelp(L2ExpansionDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } // Print help. if (cl.hasOption(OPTION_HELP)) { HELP_FORMATTER.printHelp(L2ExpansionDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } // Get output files. String outputPath = cl.getOptionValue(OPTION_OUTPUT_PATH); File outputFile = new File(outputPath); if (outputFile.isDirectory() || outputFile.exists()) { LOGGER.error("Supplied output file is a directory or already exists."); System.exit(1); } outputFile.createNewFile(); File inchiOutputFile = new File(outputPath + ".inchis"); if (inchiOutputFile.isDirectory() || inchiOutputFile.exists()) { LOGGER.error("Supplied inchi output file is a directory or already exists."); System.exit(1); } inchiOutputFile.createNewFile(); Optional<OutputStream> maybeProgressStream = Optional.empty(); if (cl.hasOption(OPTION_PROGRESS_PATH)) { String progressPath = cl.getOptionValue(OPTION_PROGRESS_PATH); File progressFile = new File(progressPath); LOGGER.info("Writing incremental results to file at %s", progressFile.getAbsolutePath()); if (progressFile.isDirectory() || progressFile.exists()) { LOGGER.error("Supplied progress file is a directory or already exists."); System.exit(1); } maybeProgressStream = Optional.of(new FileOutputStream(progressFile)); } // Get metabolite list L2InchiCorpus inchiCorpus = getInchiCorpus(cl, OPTION_METABOLITES); LOGGER.info("%d substrate inchis.", inchiCorpus.getInchiList().size()); Integer maxMass = NO_MASS_THRESHOLD; if (cl.hasOption(OPTION_MASS_THRESHOLD)) { maxMass = Integer.parseInt(cl.getOptionValue(OPTION_MASS_THRESHOLD)); LOGGER.info("Filtering out substrates with mass more than %d daltons.", maxMass); } inchiCorpus.filterByMass(maxMass); LOGGER.info("%d substrate inchis that are importable as molecules.", inchiCorpus.getInchiList().size()); PredictionGenerator generator = new AllPredictionsGenerator(new ReactionProjector()); L2Expander expander = buildExpander(cl, inchiCorpus, generator); L2PredictionCorpus predictionCorpus = expander.getPredictions(maybeProgressStream); LOGGER.info("Done with L2 expansion. Produced %d predictions.", predictionCorpus.getCorpus().size()); LOGGER.info("Writing corpus to file."); predictionCorpus.writePredictionsToJsonFile(outputFile); L2InchiCorpus productInchis = new L2InchiCorpus(predictionCorpus.getUniqueProductInchis()); productInchis.writeToFile(inchiOutputFile); LOGGER.info("L2ExpansionDriver complete!"); }