List of usage examples for java.util Optional get
public T get()
From source file:br.com.blackhubos.eventozero.updater.assets.Asset.java
@SuppressWarnings("unchecked") public static Optional<Asset> parseJsonObject(JSONObject jsonObject, MultiTypeFormatter formatter) { String url = null;/*w w w. j a v a2 s. c o m*/ String name = null; String downloadUrl = null; Date createdDate = null; Date updatedDate = null; long id = Long.MIN_VALUE; long size = Long.MIN_VALUE; long downloads = Long.MIN_VALUE; AssetState state = null; Optional<String> label = Optional.empty(); Optional<Uploader> uploader = Optional.empty(); // Obtem todos valores do JSON for (Map.Entry entries : (Set<Map.Entry>) jsonObject.entrySet()) { Object key = entries.getKey(); Object value = entries.getValue(); String valueString = String.valueOf(value); switch (AssetInput.parseObject(key)) { case URL: { // URL do Asset url = valueString; break; } case ID: { // Id do Asset id = Long.parseLong(valueString); break; } case BROWSER_DOWNLOAD_URL: { // Link de download downloadUrl = valueString; break; } case CREATED_AT: { // Data de criao if (formatter.canFormat(Date.class)) { Optional<Date> dateResult = formatter.format(valueString, Date.class); if (dateResult.isPresent()) { createdDate = dateResult.get(); } } break; } case UPDATED_AT: { // Data de atualizao if (formatter.canFormat(Date.class)) { Optional<Date> dateResult = formatter.format(valueString, Date.class); if (dateResult.isPresent()) { updatedDate = dateResult.get(); } } break; } case NAME: { // Nome name = valueString; break; } case DOWNLOAD_COUNT: { // Quantidade de downloads downloads = Long.parseLong(valueString); break; } case LABEL: { /** Rtulo (se houver, caso contrrio, {@link Optional#absent()} **/ if (value == null) { label = Optional.empty(); } else { label = Optional.of(valueString); } break; } case STATE: { // Estado state = AssetState.parseString(valueString); break; } case SIZE: { // Tamanho do arquivo (em bytes) size = Long.parseLong(valueString); break; } case UPLOADER: { // Quem envou (traduzido externalmente) uploader = Uploader.parseJsonObject((JSONObject) value, formatter); break; } default: { } } } if (id == Long.MIN_VALUE) { // Retorna um optional de valor ausente se no for encontrado o Asset. return Optional.empty(); } // Cria um novo Asset return Optional.of(new Asset(url, name, downloadUrl, createdDate, updatedDate, id, size, downloads, state, label, uploader)); }
From source file:com.ikanow.aleph2.data_model.utils.JsonUtils.java
/** Takes a tuple expressed as LinkedHashMap<String, Object> (by convention the Objects are primitives, JsonNode, or POJO), and where one of the objects * is a JSON representation of the original object and creates an object by folding them all together * Note the other fields of the tuple take precedence over the JSON * @param in - the tuple/*from w w w . j a v a 2 s. c o m*/ * @param mapper - the Jackson object mapper * @param json_field - optional fieldname of the string representation of the JSON - if not present then the last field is used (set to eg "" if there is no base object) * @return */ public static JsonNode foldTuple(final LinkedHashMap<String, Object> in, final ObjectMapper mapper, final Optional<String> json_field) { try { // (do this imperatively to handle the "last element can be the base object case" final Iterator<Map.Entry<String, Object>> it = in.entrySet().iterator(); ObjectNode acc = mapper.createObjectNode(); while (it.hasNext()) { final Map.Entry<String, Object> kv = it.next(); if ((json_field.isPresent() && kv.getKey().equals(json_field.get())) || !json_field.isPresent() && !it.hasNext()) { acc = (ObjectNode) ((ObjectNode) mapper.readTree(kv.getValue().toString())).setAll(acc); } else { final ObjectNode acc_tmp = acc; Patterns.match(kv.getValue()).andAct().when(String.class, s -> acc_tmp.put(kv.getKey(), s)) .when(Long.class, l -> acc_tmp.put(kv.getKey(), l)) .when(Integer.class, l -> acc_tmp.put(kv.getKey(), l)) .when(Boolean.class, b -> acc_tmp.put(kv.getKey(), b)) .when(Double.class, d -> acc_tmp.put(kv.getKey(), d)) .when(JsonNode.class, j -> acc_tmp.set(kv.getKey(), j)) .when(Float.class, f -> acc_tmp.put(kv.getKey(), f)) .when(BigDecimal.class, f -> acc_tmp.put(kv.getKey(), f)) .otherwise(x -> acc_tmp.set(kv.getKey(), BeanTemplateUtils.toJson(x))); } } return acc; } catch (Exception e) { throw new RuntimeException(e); } // (convert to unchecked exception) }
From source file:com.helion3.prism.api.query.QueryBuilder.java
/** * Parses a parameter argument.//ww w .ja 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<?>> * @throws ParameterException */ private static Optional<ListenableFuture<?>> parseParameterFromArgument(QuerySession session, Query query, Pair<String, String> parameter) throws ParameterException { // Simple validation if (parameter.getKey().length() <= 0 || parameter.getValue().length() <= 0) { throw new ParameterException("Invalid empty value for parameter \"" + parameter.getKey() + "\"."); } // Find a handler Optional<ParameterHandler> optionalHandler = Prism.getParameterHandler(parameter.getKey()); if (!optionalHandler.isPresent()) { throw new ParameterException( "\"" + parameter.getKey() + "\" is not a valid parameter. No handler found."); } ParameterHandler handler = optionalHandler.get(); // Allows this command source? if (!handler.acceptsSource(session.getCommandSource().get())) { throw new ParameterException( "This command source may not use the \"" + parameter.getKey() + "\" parameter."); } // Validate value if (!handler.acceptsValue(parameter.getValue())) { throw new ParameterException( "Invalid value \"" + parameter.getValue() + "\" for parameter \"" + parameter.getKey() + "\"."); } return handler.process(session, parameter.getKey(), parameter.getValue(), query); }
From source file:com.formkiq.core.form.bean.ObjectBuilder.java
/** * Populate {@link FormJSON} from {@link Map}. * @param form {@link FormJSON}/*from ww w . j a v a2 s .c om*/ * @param values {@link Map} */ public static void populate(final FormJSON form, final Map<String, String> values) { if (values != null) { for (Map.Entry<String, String> e : values.entrySet()) { Optional<FormJSONField> op = findValueByKey(form, e.getKey()); if (op.isPresent()) { if (e.getValue() != null) { op.get().setValue(e.getValue()); } else { op.get().setValue(""); } } } } }
From source file:org.openmhealth.shim.jawbone.mapper.JawboneDataPointMapper.java
/** * @param listEntryNode an individual entry node from the "items" array of a Jawbone endpoint response * @param unixEpochTimestamp unix epoch seconds timestamp from a time property in the list entry node * @return the appropriate {@link ZoneId} for the timestamp parameter based on the timezones contained within the * list entry node// w w w .ja v a 2 s.c o m */ static ZoneId getTimeZoneForTimestamp(JsonNode listEntryNode, Long unixEpochTimestamp) { Optional<JsonNode> optionalTimeZonesNode = asOptionalNode(listEntryNode, "details.tzs"); Optional<JsonNode> optionalTimeZoneNode = asOptionalNode(listEntryNode, "details.tz"); ZoneId zoneIdForTimestamp = ZoneOffset.UTC; // set default to Z in case problems with getting timezone if (optionalTimeZonesNode.isPresent() && optionalTimeZonesNode.get().size() > 0) { JsonNode timeZonesNode = optionalTimeZonesNode.get(); if (timeZonesNode.size() == 1) { zoneIdForTimestamp = parseZone(timeZonesNode.get(0).get(TIMEZONE_ENUM_INDEX_TZ)); } else { long currentLatestTimeZoneStart = 0; for (JsonNode timeZoneNodesEntry : timeZonesNode) { long timeZoneStartTime = timeZoneNodesEntry.get(TIMEZONE_ENUM_INDEX_START).asLong(); if (unixEpochTimestamp >= timeZoneStartTime) { if (timeZoneStartTime > currentLatestTimeZoneStart) { // we cannot guarantee the order of the // "tzs" array and we need to find the latest timezone that started before our time zoneIdForTimestamp = parseZone(timeZoneNodesEntry.get(TIMEZONE_ENUM_INDEX_TZ)); currentLatestTimeZoneStart = timeZoneStartTime; } } } } } else if (optionalTimeZoneNode.isPresent() && !optionalTimeZoneNode.get().isNull()) { zoneIdForTimestamp = parseZone(optionalTimeZoneNode.get()); } return zoneIdForTimestamp; }
From source file:io.github.retz.web.AppRequestHandler.java
static String loadApp(Request req, Response res) throws JsonProcessingException, IOException { LOG.debug(LoadAppRequest.resourcePattern()); Optional<AuthHeader> authHeaderValue = getAuthInfo(req); res.type("application/json"); // TODO: check key from Authorization header matches a key in Application object LoadAppRequest loadAppRequest = MAPPER.readValue(req.bodyAsBytes(), LoadAppRequest.class); LOG.debug("app (id={}, owner={}), requested by {}", loadAppRequest.application().getAppid(), loadAppRequest.application().getOwner(), authHeaderValue.get().key()); // Compare application owner and requester validateOwner(req, loadAppRequest.application()); Optional<Application> tmp = Applications.get(loadAppRequest.application().getAppid()); if (tmp.isPresent()) { if (!tmp.get().getOwner().equals(loadAppRequest.application().getOwner())) { res.status(403);//from w w w . j a v a 2s . c o m LOG.error("Application {} is already owned by ", loadAppRequest.application().getAppid(), tmp.get().getOwner()); return MAPPER.writeValueAsString( new ErrorResponse("The application name is already used by other user")); } } if (!(loadAppRequest.application().container() instanceof DockerContainer)) { if (loadAppRequest.application().getUser().isPresent() && loadAppRequest.application().getUser().get().equals("root")) { res.status(400); return MAPPER .writeValueAsString(new ErrorResponse("root user is only allowed with Docker container")); } } Application app = loadAppRequest.application(); LOG.info("Registering application name={} owner={}", app.getAppid(), app.getOwner()); boolean result = Applications.load(app); if (result) { res.status(200); LoadAppResponse response = new LoadAppResponse(); response.ok(); return MAPPER.writeValueAsString(response); } else { res.status(400); return MAPPER.writeValueAsString(new ErrorResponse("cannot load application")); } }
From source file:io.github.retz.web.JobRequestRouter.java
public static String getDir(spark.Request req, spark.Response res) throws IOException { int id = Integer.parseInt(req.params(":id")); String path = req.queryParams("path"); Optional<Job> job = JobQueue.getJob(id); LOG.debug("get-path: id={}, path={}", id, path); res.type("application/json"); // Translating default as SparkJava's router doesn't route '.' or empty string if (ListFilesRequest.DEFAULT_SANDBOX_PATH.equals(path)) { path = ""; }/* w w w . jav a2 s .c o m*/ List ret; if (job.isPresent() && job.get().url() != null) { try { String json = fetchHTTPDir(job.get().url(), path); ret = MAPPER.readValue(json, new TypeReference<List<DirEntry>>() { }); } catch (FileNotFoundException e) { res.status(404); LOG.warn("path {} not found", path); return MAPPER.writeValueAsString(new ErrorResponse(path + " not found")); } } else { ret = Arrays.asList(); } ListFilesResponse listFilesResponse = new ListFilesResponse(job, ret); listFilesResponse.status("ok"); return MAPPER.writeValueAsString(listFilesResponse); }
From source file:io.github.retz.web.JobRequestHandler.java
private static Optional<Job> getJobAndVerify(Request req) throws IOException { int id = Integer.parseInt(req.params(":id")); Optional<AuthHeader> authHeaderValue = WebConsole.getAuthInfo(req); if (!authHeaderValue.isPresent()) { LOG.debug("Authorization header lacking?"); return Optional.empty(); }/*from w w w . j a va2 s . c om*/ LOG.debug("get-xxx id={}, user={}", id, authHeaderValue.get().key()); Optional<AppJobPair> maybePair = Database.getInstance().getAppJob(id); if (maybePair.isPresent()) { AppJobPair pair = maybePair.get(); if (pair.application().getOwner().equals(authHeaderValue.get().key())) { return Optional.of(pair.job()); } } return Optional.empty(); }
From source file:com.freiheit.fuava.sftp.util.FilenameUtil.java
/** * Returns the lastest date/time from a list of filenames. *///from w w w . j a v a2s . c o m @CheckForNull public static String extractLatestDateFromFilenames(final List<String> entryList, final FileType fileType, @Nullable final RemoteFileStatus status) throws ParseException { final Optional<String> maxDate = entryList.stream().filter(p -> p != null) .filter(f -> FilenameUtil.matchesSearchedFile(f, fileType, null, status)) .max((a, b) -> Long.compare(getDateFromFilename(a), getDateFromFilename(b))); if (!maxDate.isPresent()) { return null; // no timestamp found } final String max = maxDate.get(); return String.valueOf(getDateFromFilenameWithDelimiter(max)); }
From source file:net.minecraftforge.fml.relauncher.libraries.LibraryManager.java
public static List<Artifact> flattenLists(File mcDir) { List<Artifact> merged = new ArrayList<>(); for (ModList list : ModList.getBasicLists(mcDir)) { for (Artifact art : list.flatten()) { Optional<Artifact> old = merged.stream().filter(art::matchesID).findFirst(); if (!old.isPresent()) { merged.add(art);//ww w . j a v a 2s .com } else if (old.get().getVersion().compareTo(art.getVersion()) < 0) { merged.add(merged.indexOf(old.get()), art); merged.remove(old.get()); } } } return merged; }