List of usage examples for java.util Optional isPresent
public boolean isPresent()
From source file:io.github.benas.randombeans.util.ReflectionUtils.java
@SuppressWarnings("unchecked") public static <T> Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments) { try {/*from w w w . ja v a 2 s. co m*/ if (notEmpty(randomizerArguments)) { Optional<Constructor<?>> matchingConstructor = asList(type.getConstructors()).stream() .filter(constructor -> hasSameArgumentNumber(constructor, randomizerArguments) && hasSameArgumentTypes(constructor, randomizerArguments)) .findFirst(); if (matchingConstructor.isPresent()) { return (Randomizer<T>) matchingConstructor.get() .newInstance(convertArguments(randomizerArguments)); } } return (Randomizer<T>) type.newInstance(); } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { throw new ObjectGenerationException( format("Could not create Randomizer of type: %s with constructor arguments: %s", type, Arrays.toString(randomizerArguments)), e); } }
From source file:io.pravega.controller.store.stream.tables.TableHelper.java
/** * Get active segments at given timestamp. * Perform binary search on index table to find the record corresponding to timestamp. * Note: index table may be stale or not reflect lastest state of history table. * So we may need to fall through in the history table from the record being pointed to by index * until we find the correct record.//from w w w.jav a 2 s . c o m * * @param timestamp timestamp * @param indexTable indextable * @param historyTable history table * @return */ public static List<Integer> getActiveSegments(final long timestamp, final byte[] indexTable, final byte[] historyTable) { Optional<HistoryRecord> record = HistoryRecord.readRecord(historyTable, 0, true); if (record.isPresent() && timestamp > record.get().getScaleTime()) { final Optional<IndexRecord> recordOpt = IndexRecord.search(timestamp, indexTable).getValue(); final int startingOffset = recordOpt.isPresent() ? recordOpt.get().getHistoryOffset() : 0; record = findRecordInHistoryTable(startingOffset, timestamp, historyTable, true); } return record.map(HistoryRecord::getSegments).orElse(new ArrayList<>()); }
From source file:org.kontalk.crypto.Coder.java
private static KeysResult getKeys(User user) { KeysResult result = new KeysResult(); Optional<PersonalKey> optMyKey = AccountLoader.getInstance().getPersonalKey(); if (!optMyKey.isPresent()) { LOGGER.log(Level.WARNING, "can't get personal key"); result.errors.add(Error.MY_KEY_UNAVAILABLE); return result; }/* w w w. j av a2 s. c o m*/ result.myKey = optMyKey.get(); if (!user.hasKey()) { LOGGER.warning("key not found for user, id: " + user.getID()); result.errors.add(Error.KEY_UNAVAILABLE); return result; } Optional<PGPCoderKey> optKey = PGPUtils.readPublicKey(user.getKey()); if (!optKey.isPresent()) { LOGGER.warning("can't get sender key"); result.errors.add(Error.INVALID_KEY); return result; } result.otherKey = optKey.get(); return result; }
From source file:io.pravega.controller.store.stream.tables.TableHelper.java
/** * Segment Table records are of fixed size. * So O(constant) operation to get segment given segmentTable Chunk. * <p>// ww w . jav a 2 s . c o m * Note: this method assumes you have supplied the correct chunk * * @param number segment number * @param segmentTable segment table * @return */ public static Segment getSegment(final int number, final byte[] segmentTable) { Optional<SegmentRecord> recordOpt = SegmentRecord.readRecord(segmentTable, number); if (recordOpt.isPresent()) { SegmentRecord record = recordOpt.get(); return new Segment(record.getSegmentNumber(), record.getStartTime(), record.getRoutingKeyStart(), record.getRoutingKeyEnd()); } else { throw StoreException.create(StoreException.Type.DATA_NOT_FOUND, "Segment number: " + String.valueOf(number)); } }
From source file:io.pravega.controller.store.stream.tables.TableHelper.java
/** * Current active segments correspond to last entry in the history table. * Until segment number is written to the history table it is not exposed to outside world * (e.g. callers - producers and consumers) * * @param historyTable history table/*from w w w. j a va2 s .com*/ * @return */ public static List<Integer> getActiveSegments(final byte[] historyTable) { final Optional<HistoryRecord> record = HistoryRecord.readLatestRecord(historyTable, true); return record.isPresent() ? record.get().getSegments() : new ArrayList<>(); }
From source file:io.github.retz.web.JobRequestHandler.java
static String getFile(spark.Request req, spark.Response res) throws IOException { Optional<Job> job = getJobAndVerify(req); String file = req.queryParams("path"); long offset = Long.parseLong(req.queryParams("offset")); long length = Long.parseLong(req.queryParams("length")); LOG.debug("get-file: path={}, offset={}, length={}", file, offset, length); res.type("application/json"); Optional<FileContent> fileContent; if (job.isPresent() && job.get().url() != null // If url() is null, the job hasn't yet been started at Mesos && MesosHTTPFetcher.statHTTPFile(job.get().url(), file)) { Pair<Integer, String> payload = MesosHTTPFetcher.fetchHTTPFile(job.get().url(), file, offset, length); LOG.debug("Payload length={}, offset={}", payload.right().length(), offset); // TODO: what the heck happens when a file is not UTF-8 encodable???? How Mesos works? if (payload.left() == 200) { fileContent = Optional.ofNullable(MAPPER.readValue(payload.right(), FileContent.class)); } else {/* w w w. j a va 2 s . c o m*/ return MAPPER.writeValueAsString(new ErrorResponse(payload.right())); } } else { fileContent = Optional.empty(); } GetFileResponse getFileResponse = new GetFileResponse(job, fileContent); getFileResponse.ok(); res.status(200); return MAPPER.writeValueAsString(getFileResponse); }
From source file:io.pravega.controller.store.stream.tables.TableHelper.java
/** * Add a new row to the history table. This row is only partial as it only contains list of segments. * Timestamp is added using completeHistoryRecord method. * * @param historyTable history table * @param newActiveSegments new active segments * @return/*w w w. j a va2 s . c o m*/ */ public static byte[] addPartialRecordToHistoryTable(final byte[] historyTable, final List<Integer> newActiveSegments) { final ByteArrayOutputStream historyStream = new ByteArrayOutputStream(); Optional<HistoryRecord> last = HistoryRecord.readLatestRecord(historyTable, false); assert last.isPresent() && !(last.get().isPartial()); try { historyStream.write(historyTable); historyStream.write(new HistoryRecord(last.get().getEpoch() + 1, newActiveSegments, historyTable.length) .toBytePartial()); } catch (Exception e) { throw new RuntimeException(e); } return historyStream.toByteArray(); }
From source file:io.pravega.controller.store.stream.tables.TableHelper.java
/** * Return segments in the epoch./*from ww w . ja va2s . co m*/ * @param historyTableData history table * @param epoch epoch * * @return segments in the epoch */ public static List<Integer> getSegmentsInEpoch(byte[] historyTableData, int epoch) { Optional<HistoryRecord> record = HistoryRecord.readLatestRecord(historyTableData, false); while (record.isPresent() && record.get().getEpoch() > epoch) { record = HistoryRecord.fetchPrevious(record.get(), historyTableData); } return record.orElseThrow(() -> StoreException.create(StoreException.Type.DATA_NOT_FOUND, "Epoch: " + epoch + " not found in history table")).getSegments(); }
From source file:io.pravega.controller.store.stream.tables.TableHelper.java
/** * Adds timestamp to the last record in the history table. * * @param historyTable history table * @param partialHistoryRecord partial history record * @param timestamp scale timestamp * @return/* ww w . j a v a2s . c o m*/ */ public static byte[] completePartialRecordInHistoryTable(final byte[] historyTable, final HistoryRecord partialHistoryRecord, final long timestamp) { Optional<HistoryRecord> record = HistoryRecord.readLatestRecord(historyTable, false); assert record.isPresent() && record.get().isPartial() && record.get().getEpoch() == partialHistoryRecord.getEpoch(); final ByteArrayOutputStream historyStream = new ByteArrayOutputStream(); try { historyStream.write(historyTable); historyStream .write(new HistoryRecord(partialHistoryRecord.getSegments(), partialHistoryRecord.getEpoch(), timestamp, partialHistoryRecord.getOffset()).remainingByteArray()); } catch (Exception e) { throw new RuntimeException(e); } return historyStream.toByteArray(); }
From source file:io.github.retz.web.WebConsole.java
public static boolean kill(int id) throws Exception { if (!driver.isPresent()) { LOG.error("Driver is not present; this setup should be wrong"); return false; }/*from w w w.j a v a2 s .c o m*/ Optional<Boolean> result = Stanchion.call(() -> { // TODO: non-application owner is even possible to kill job Optional<String> maybeTaskId = JobQueue.cancel(id, "Canceled by user"); // 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 (maybeTaskId.isPresent()) { Protos.TaskID taskId = Protos.TaskID.newBuilder().setValue(maybeTaskId.get()).build(); Protos.Status status = driver.get().killTask(taskId); LOG.info("Job id={} was running and killed."); return status == Protos.Status.DRIVER_RUNNING; } return false; }); if (result.isPresent()) { return result.get(); } else { return false; } }