List of usage examples for java.util Optional get
public T get()
From source file:com.ikanow.aleph2.aleph2_rest_utils.RestCrudFunctions.java
private static <T> Response handleQueryRequest(final Optional<String> query_json, final Optional<String> query_id, final ICrudService<T> crud_service, final Class<T> clazz, Optional<Long> limit) { //get id or a query object that was posted //TODO switch to query_id.map().orElse() ... just making a quick swap for the moment if (query_id.isPresent()) { //ID query try {// www .j a v a 2 s . c o m final String id = query_id.get(); _logger.debug("id: " + id); return Response.ok(RestUtils.convertObjectToJson(crud_service.getObjectById(id).get()).toString()) .build(); } catch (JsonProcessingException | InterruptedException | ExecutionException e) { return Response.status(Status.BAD_REQUEST) .entity(ErrorUtils.getLongForm("Error converting input stream to string: {0}", e)).build(); } } else if (query_json.isPresent()) { //Body Query try { final String json = query_json.get(); _logger.debug("query: " + json); final QueryComponent<T> query = RestUtils.convertStringToQueryComponent(json, clazz, limit); return Response .ok(RestUtils.convertCursorToJson(crud_service.getObjectsBySpec(query).get()).toString()) .build(); } catch (Exception e) { return Response.status(Status.BAD_REQUEST) .entity(ErrorUtils.getLongForm("Error converting input stream to string: {0}", e)).build(); } } else { //empty query, does a getall using limit (or 10) try { _logger.debug("empty query, get all"); final SingleQueryComponent<T> query = JsonNode.class.isAssignableFrom(clazz) ? (SingleQueryComponent<T>) CrudUtils.allOf() : CrudUtils.allOf(clazz); final Cursor<T> cursor = crud_service.getObjectsBySpec(query.limit(limit.orElse(10L))).get(); return Response.ok(RestUtils.convertCursorToJson(cursor).toString()).build(); } catch (JsonProcessingException | InterruptedException | ExecutionException e) { return Response.status(Status.BAD_REQUEST) .entity(ErrorUtils.getLongForm("Error converting input stream to string: {0}", e)).build(); } } }
From source file:net.sf.jabref.model.database.BibDatabase.java
/** * Returns the text stored in the given field of the given bibtex entry * which belongs to the given database./*w w w . jav a 2s. com*/ * <p> * If a database is given, this function will try to resolve any string * references in the field-value. * Also, if a database is given, this function will try to find values for * unset fields in the entry linked by the "crossref" field, if any. * * @param field The field to return the value of. * @param entry maybenull * The bibtex entry which contains the field. * @param database maybenull * The database of the bibtex entry. * @return The resolved field value or null if not found. */ public static String getResolvedField(String field, BibEntry entry, BibDatabase database) { if ("bibtextype".equals(field)) { return EntryUtil.capitalizeFirst(entry.getType()); } // TODO: Changed this to also consider alias fields, which is the expected // behavior for the preview layout and for the check whatever all fields are present. // But there might be unwanted side-effects?! Optional<String> result = entry.getFieldOrAlias(field); // If this field is not set, and the entry has a crossref, try to look up the // field in the referred entry: Do not do this for the bibtex key. if (!result.isPresent() && (database != null) && !field.equals(BibEntry.KEY_FIELD)) { Optional<String> crossrefKey = entry.getFieldOptional(FieldName.CROSSREF); if (crossrefKey.isPresent()) { Optional<BibEntry> referred = database.getEntryByKey(crossrefKey.get()); if (referred.isPresent()) { // Ok, we found the referred entry. Get the field value from that // entry. If it is unset there, too, stop looking: result = referred.get().getFieldOptional(field); } } } return BibDatabase.getText(result.orElse(null), database); }
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 {/*from www .j a v a 2s . 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
/** * 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/* www.jav a2 s .c om*/ * @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:com.android.tools.idea.templates.RepositoryUrlManager.java
private static String findExistingExplicitVersion(@NotNull Collection<GradleCoordinate> dependencies) { Optional<GradleCoordinate> highest = dependencies.stream() .filter(coordinate -> ImportModule.SUPPORT_GROUP_ID.equals(coordinate.getGroupId())) .max(COMPARE_PLUS_LOWER);// w w w.jav a 2s.co m if (!highest.isPresent()) { return null; } String version = highest.get().getRevision(); if (version.endsWith("+")) { return version.length() > 1 ? version.substring(0, version.length() - 1) : null; } return version; }
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/*from ww w . jav a2s .c om*/ */ 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.// ww w . ja v a 2 s. c om * @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
/** * 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./* ww w . ja va 2s. c om*/ * * @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: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 va 2s . c om */ 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.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>//from www.ja va 2s .com * 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)); } }