List of usage examples for java.util Optional get
public T get()
From source file:io.github.retz.web.JobRequestHandler.java
static String kill(Request req, spark.Response res) throws JsonProcessingException { LOG.debug("kill", req.params(":id")); res.type("application/json"); int id = Integer.parseInt(req.params(":id")); Optional<Job> maybeJob; try {/* w w w . j a v a 2s .c om*/ maybeJob = getJobAndVerify(req); } catch (IOException e) { return MAPPER.writeValueAsString(new ErrorResponse(e.toString())); } if (!maybeJob.isPresent()) { res.status(404); Response response = new ErrorResponse("No such job: " + id); response.status("No such job: " + id); return MAPPER.writeValueAsString(response); } Optional<Boolean> result = Stanchion.call(() -> { Optional<Job> maybeJob2 = JobQueue.cancel(id, "Canceled by user"); if (maybeJob2.isPresent()) { Job job = maybeJob2.get(); // There's a slight pitfall between cancel above and kill below where // no kill may be sent, RetzScheduler is exactly in resourceOffers and being scheduled. // Then this protocol returns false for sure. if (job.taskId() != null && !job.taskId().isEmpty() && driver.isPresent()) { Protos.TaskID taskId = Protos.TaskID.newBuilder().setValue(job.taskId()).build(); Protos.Status status = driver.get().killTask(taskId); LOG.info("Job id={} was running and killed. status={}, taskId={}", job.id(), status, job.taskId()); } return job.state() == Job.JobState.KILLED; } // Job is already finished or killed, no more running nor runnable, or something is wrong return false; }); Response response; if (result.isPresent() && result.get()) { response = new KillResponse(); res.status(200); response.ok(); } else { res.status(500); response = new ErrorResponse(); response.status("Can't kill job - due to unknown reason"); } return MAPPER.writeValueAsString(response); }
From source file:io.github.retz.web.WebConsole.java
static void validateOwner(Request req, Application app) { Optional<AuthHeader> authHeaderValue = getAuthInfo(req); if (!app.getOwner().equals(authHeaderValue.get().key())) { LOG.debug("Invalid request: requester and owner does not match"); halt(400, "Invalid request: requester and owner does not match"); }//www .j a v a 2s . c o m }
From source file:io.github.retz.scheduler.Launcher.java
public static int run(String... argv) { Configuration conf;/* w w w . j a va 2s. c o m*/ try { conf = parseConfiguration(argv); if (conf.fileConfig.isTLS()) { LOG.warn("Make sure a valid certificate is being used or RetzExecutor may not work."); } Database.getInstance().init(conf.getServerConfig()); if (conf.getServerConfig().getGc()) { GarbageJobCollector.start(conf.getServerConfig().getGcLeeway(), conf.getServerConfig().getGcInterval()); } else { LOG.info("Automatic garbage collection is turned off; use retz-admin gc to collect old jobs"); } } catch (ParseException e) { LOG.error(e.toString()); return -1; } catch (URISyntaxException e) { LOG.error(e.toString()); return -1; } catch (SQLException e) { LOG.error(e.toString()); return -1; } catch (IOException e) { LOG.error(e.toString()); return -1; } Optional<JmxServer> maybeJmxServer = AdminConsole.startJmxServer(conf.getServerConfig()); if (!maybeJmxServer.isPresent()) { LOG.error("Failed to start JMX Server"); return -1; } JmxServer jmxServer = maybeJmxServer.get(); Protos.FrameworkInfo fw = buildFrameworkInfo(conf); // Retz must do all recovery process before launching scheduler; // This is because running scheduler changes state of any jobs if it // has successfully connected to Mesos master. // By hitting HTTP endpoints and comparing with database job states, // Retz can decide whether to re-run it or just finish it. // BTW after connecting to Mesos it looks like re-sending unacked messages. maybeRequeueRunningJobs(conf.getMesosMaster(), fw.getId().getValue(), Database.getInstance().getRunning()); RetzScheduler scheduler; try { scheduler = new RetzScheduler(conf, fw); } catch (Throwable t) { LOG.error("Cannot initialize scheduler", t); return -1; } SchedulerDriver driver = SchedulerDriverFactory.create(scheduler, conf, fw); Protos.Status status = driver.start(); if (status != Protos.Status.DRIVER_RUNNING) { LOG.error("Cannot start Mesos scheduler: {}", status.name()); System.exit(-1); //} else if (status == Protos.Status.DRIVER_ABORTED) { //} else if (status == Protos.Status.DRIVER_NOT_STARTED) { //} else if (status == Protos.Status.DRIVER_STOPPED) { } LOG.info("Mesos scheduler started: {}", status.name()); // Start web server WebConsole.start(conf.fileConfig); WebConsole.set(scheduler, driver); LOG.info("Web console has started with port {}", conf.getPort()); java.lang.Runtime.getRuntime().addShutdownHook(new ShutdownThread(driver)); // Stop them all, usually don't come here // Wait for Mesos framework stop status = driver.join(); LOG.info("{} has been stopped: {}", RetzScheduler.FRAMEWORK_NAME, status.name()); WebConsole.stop(); // Stop web server GarbageJobCollector.stop(); Database.getInstance().stop(); jmxServer.stop(); return (status == Protos.Status.DRIVER_STOPPED ? 0 : 255); }
From source file:net.fabricmc.loom.task.DownloadTask.java
public static void downloadMcJson(LoomGradleExtension extension, Logger logger) throws IOException { if (!Constants.MINECRAFT_JSON.get(extension).exists()) { logger.lifecycle(":downloading minecraft json"); FileUtils.copyURLToFile(new URL("https://launchermeta.mojang.com/mc/game/version_manifest.json"), Constants.VERSION_MANIFEST.get(extension)); ManifestVersion mcManifest = new GsonBuilder().create().fromJson( FileUtils.readFileToString(Constants.VERSION_MANIFEST.get(extension), "UTF-8"), ManifestVersion.class); Optional<ManifestVersion.Versions> optionalVersion = mcManifest.versions.stream() .filter(versions -> versions.id.equalsIgnoreCase(extension.version)).findFirst(); if (optionalVersion.isPresent()) { FileUtils.copyURLToFile(new URL(optionalVersion.get().url), Constants.MINECRAFT_JSON.get(extension)); } else {/* ww w .j a v a2s . c o m*/ logger.info(":failed downloading minecraft json"); throw new RuntimeException("Failed downloading Minecraft json"); } } }
From source file:net.sf.jabref.gui.desktop.JabRefDesktop.java
private static void openExternalFilePlatformIndependent(Optional<ExternalFileType> fileType, String filePath) throws IOException { if (fileType.isPresent()) { String application = fileType.get().getOpenWithApplication(); if (application.isEmpty()) { NATIVE_DESKTOP.openFile(filePath, fileType.get().getExtension()); } else {/*from w ww . ja v a2s . co m*/ NATIVE_DESKTOP.openFileWithApplication(filePath, application); } } }
From source file:io.github.retz.scheduler.MesosHTTPFetcher.java
public static Optional<String> sandboxDownloadUri(String master, String slaveId, String frameworkId, String executorId, String path) { Optional<String> base = sandboxUri("download", master, slaveId, frameworkId, executorId); if (base.isPresent()) { try {/*w w w .j a v a 2s . c o m*/ String encodedPath = java.net.URLEncoder.encode(path, java.nio.charset.StandardCharsets.UTF_8.toString()); return Optional.of(base.get() + encodedPath); } catch (UnsupportedEncodingException e) { return Optional.empty(); } } return Optional.empty(); }
From source file:io.github.retz.web.JobRequestHandler.java
static String downloadFile(spark.Request req, spark.Response res) throws Exception { Optional<Job> job = getJobAndVerify(req); String file = req.queryParams("path"); LOG.debug("download: path={}", file); if (job.isPresent() && job.get().url() != null) { // If url() is null, the job hasn't yet been started at Mesos MesosHTTPFetcher.downloadHTTPFile(job.get().url(), file, (Triad<Integer, String, Pair<Long, InputStream>> triad) -> { Integer statusCode = triad.left(); res.status(statusCode); if (statusCode == 200) { Long length = triad.right().left(); InputStream io = triad.right().right(); Long maxFileSize = scheduler.get().maxFileSize(); if (length < 0) { throw new IOException("content length is negative: " + length); } else if (0 <= maxFileSize && maxFileSize < length) { // negative maxFileSize indicates no limit throw new DownloadFileSizeExceeded(length, maxFileSize); }/* ww w . ja v a 2s .co m*/ res.raw().setHeader("Content-Length", length.toString()); LOG.debug("start streaming of {} bytes for {}", length, file); IOUtils.copyLarge(io, res.raw().getOutputStream(), 0, length); LOG.debug("end streaming for {}", file); } else { res.body(triad.center()); } }); return ""; } else { res.status(404); return ""; } }
From source file:com.skelril.skree.content.registry.item.zone.ZoneItemUtil.java
public static boolean hasSameZoneID(ItemStack stackA, ItemStack stackB) { if (isZoneItem(stackA) && isZoneItem(stackB)) { Optional<UUID> zoneIDA = getZoneID(stackA); Optional<UUID> zoneIDB = getZoneID(stackB); return zoneIDA.isPresent() && zoneIDB.isPresent() && zoneIDA.get().equals(zoneIDB.get()); }/* ww w . j a v a 2s .co m*/ return false; }
From source file:com.helion3.prism.api.query.QueryBuilder.java
/** * Parses a flag argument.//w w w .j a v a 2 s . c o m * * @param session QuerySession current session. * @param query Query query being built. * @param parameter String argument which should be a parameter * @return Optional<ListenableFuture<?>> */ private static Optional<ListenableFuture<?>> parseFlagFromArgument(QuerySession session, Query query, String flag) throws ParameterException { flag = flag.substring(1); // Determine the true alias and value Optional<String> optionalValue = Optional.empty(); if (flag.contains("=")) { // Split the parameter: values String[] split = flag.split("="); flag = split[0]; if (!split[1].trim().isEmpty()) { optionalValue = Optional.of(split[1]); } } // Find a handler Optional<FlagHandler> optionalHandler = Prism.getFlagHandler(flag); if (!optionalHandler.isPresent()) { throw new ParameterException("\"" + flag + "\" is not a valid flag. No handler found."); } FlagHandler handler = optionalHandler.get(); // Allows this command source? if (!handler.acceptsSource(session.getCommandSource().get())) { throw new ParameterException("This command source may not use the \"" + flag + "\" flag."); } // Validate value if (optionalValue.isPresent() && !handler.acceptsValue(optionalValue.get())) { throw new ParameterException( "Invalid value \"" + optionalValue.get() + "\" for parameter \"" + flag + "\"."); } return handler.process(session, flag, optionalValue, query); }
From source file:io.github.retz.scheduler.MesosHTTPFetcher.java
public static Optional<String> sandboxUri(String t, String master, String slaveId, String frameworkId, String executorId) {/* w w w .ja v a2 s . c o m*/ Optional<String> slaveAddr = fetchSlaveAddr(master, slaveId); // get master:5050/slaves with slaves/pid, cut with '@' LOG.debug("Agent address of executor {}: {}", executorId, slaveAddr); if (!slaveAddr.isPresent()) { return Optional.empty(); } Optional<String> dir = fetchDirectory(slaveAddr.get(), frameworkId, executorId); if (!dir.isPresent()) { return Optional.empty(); } try { return Optional.of(String.format("http://%s/files/%s?path=%s", slaveAddr.get(), t, java.net.URLEncoder.encode(dir.get(), //builder.toString(), java.nio.charset.StandardCharsets.UTF_8.toString()))); } catch (UnsupportedEncodingException e) { return Optional.empty(); } }