List of usage examples for java.util Optional ofNullable
@SuppressWarnings("unchecked") public static <T> Optional<T> ofNullable(T value)
From source file:at.gridtec.lambda4j.function.bi.BiIntFunction.java
/** * Lifts a partial {@link BiIntFunction} into a total {@link BiIntFunction} that returns an {@link Optional} result. * * @param <R> The type of return value from the function * @param partial A function that is only defined for some values in its domain * @return A partial {@code BiIntFunction} lifted into a total {@code BiIntFunction} that returns an {@code * Optional} result./*from www . j a v a 2 s .c o m*/ * @throws NullPointerException If given argument is {@code null} */ @Nonnull static <R> BiIntFunction<Optional<R>> lift(@Nonnull final BiIntFunction<? extends R> partial) { Objects.requireNonNull(partial); return (value1, value2) -> Optional.ofNullable(partial.apply(value1, value2)); }
From source file:com.temenos.useragent.generic.mediatype.JsonEntityHandler.java
@Override public <T> void setValue(String fqPropertyName, T value) { List<String> pathParts = Arrays.asList(flattenPropertyName(fqPropertyName)); Optional<JSONObject> parent = navigateJsonObjectforPropertyPath(Optional.ofNullable(jsonObject), pathParts.subList(0, pathParts.size() - 1), fqPropertyName, true); if (parent.isPresent()) { parent.get().put(pathParts.get(pathParts.size() - 1), value); }// ww w . ja v a 2 s. c om }
From source file:com.example.app.profile.model.terminology.FallbackProfileTermProvider.java
@Override public TextSource locations() { return isBlank( Optional.ofNullable(getProfileTermProvider()).map(ProfileTermProvider::locations).orElse(null)) ? _defaultProfileTermProvider.locations() : getProfileTermProvider().locations(); }
From source file:com.nike.cerberus.vault.VaultAdminClientFactory.java
/** * Looks up the running instances from the Vault AutoScaling group and attempts to determine who the leader is * by using the health endpoint./*from w w w. j ava 2 s .c om*/ * * @return Client for leader */ public Optional<VaultAdminClient> getClientForLeader() { VaultAdminClient leaderClient = null; final String vaultRootToken = configStore.getVaultRootToken(); final VaultOutputs vaultOutputs = configStore.getVaultStackOutputs(); final List<String> instanceDnsNames = autoScalingService .getPublicDnsForAutoScalingGroup(vaultOutputs.getAutoscalingGroupLogicalId()); for (final String instanceDnsName : instanceDnsNames) { final VaultAdminClient vaultAdminClient = getClient(vaultRootToken, instanceDnsName); final VaultHealthResponse healthResponse = vaultAdminClient.health(); if (healthResponse.isInitialized() && !healthResponse.isSealed() && !healthResponse.isStandby()) { leaderClient = vaultAdminClient; break; } } return Optional.ofNullable(leaderClient); }
From source file:com.liferay.apio.architect.internal.body.MultipartToBodyConverter.java
/** * Reads a {@code "multipart/form"} HTTP request body into a {@link Body} * instance or fails with a {@link BadRequestException} if the input is not * a valid multipart form.//from w w w .j a v a 2 s .co m * * @review */ public static Body multipartToBody(HttpServletRequest request) { if (!isMultipartContent(request)) { throw new BadRequestException("Request body is not a valid multipart form"); } FileItemFactory fileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory); try { List<FileItem> fileItems = servletFileUpload.parseRequest(request); Iterator<FileItem> iterator = fileItems.iterator(); Map<String, String> values = new HashMap<>(); Map<String, BinaryFile> binaryFiles = new HashMap<>(); Map<String, Map<Integer, String>> indexedValueLists = new HashMap<>(); Map<String, Map<Integer, BinaryFile>> indexedFileLists = new HashMap<>(); while (iterator.hasNext()) { FileItem fileItem = iterator.next(); String name = fileItem.getFieldName(); Matcher matcher = _arrayPattern.matcher(name); if (matcher.matches()) { int index = Integer.parseInt(matcher.group(2)); String actualName = matcher.group(1); _storeFileItem(fileItem, value -> { Map<Integer, String> indexedMap = indexedValueLists.computeIfAbsent(actualName, __ -> new HashMap<>()); indexedMap.put(index, value); }, binaryFile -> { Map<Integer, BinaryFile> indexedMap = indexedFileLists.computeIfAbsent(actualName, __ -> new HashMap<>()); indexedMap.put(index, binaryFile); }); } else { _storeFileItem(fileItem, value -> values.put(name, value), binaryFile -> binaryFiles.put(name, binaryFile)); } } Map<String, List<String>> valueLists = _flattenMap(indexedValueLists); Map<String, List<BinaryFile>> fileLists = _flattenMap(indexedFileLists); return Body.create(key -> Optional.ofNullable(values.get(key)), key -> Optional.ofNullable(valueLists.get(key)), key -> Optional.ofNullable(fileLists.get(key)), key -> Optional.ofNullable(binaryFiles.get(key))); } catch (FileUploadException | IndexOutOfBoundsException | NumberFormatException e) { throw new BadRequestException("Request body is not a valid multipart form", e); } }
From source file:org.n52.iceland.config.json.JsonSettingsDao.java
@Override public void saveSettingValue(SettingValue<?> value) { writeLock().lock();/* w ww.j a v a 2 s .c o m*/ try { ObjectNode settings = getConfiguration().with(JsonConstants.SETTINGS); JsonNode node = settings.path(value.getKey()); ObjectNode settingNode = (ObjectNode) Optional.ofNullable(node.isObject() ? node : null) .orElseGet(() -> settings.putObject(value.getKey())); settingNode.put(JsonConstants.TYPE, value.getType().toString()); settingNode.set(JsonConstants.VALUE, this.settingsEncoder.encodeValue(value)); } finally { writeLock().unlock(); } configuration().scheduleWrite(); }
From source file:io.galeb.health.services.HealthCheckerService.java
@SuppressWarnings({ "FutureReturnValueIgnored", "unused" }) @JmsListener(destination = "galeb-health", concurrency = "5-5") public void check(String targetStr) throws ExecutionException, InterruptedException { final Target target = new Gson().fromJson(targetStr, Target.class); final String poolName = target.getParent().getName(); final Map<String, String> properties = target.getParent().getProperties(); final String hcPath = Optional.ofNullable(properties.get(PROP_HEALTHCHECK_PATH.toString())).orElse("/"); final String hcStatusCode = Optional.ofNullable(properties.get(PROP_HEALTHCHECK_CODE.toString())) .orElse(""); final String hcBody = Optional.ofNullable(properties.get(PROP_HEALTHCHECK_RETURN.toString())).orElse(""); final String hcHost = Optional.ofNullable(properties.get(PROP_HEALTHCHECK_HOST.toString())) .orElse(buildHcHostFromTarget(target)); final String lastReason = target.getProperties().get(PROP_STATUS_DETAILED.toString()); long start = System.currentTimeMillis(); RequestBuilder requestBuilder = new RequestBuilder("GET").setUrl(target.getName() + hcPath) .setVirtualHost(hcHost);//from w w w . ja v a 2 s . c o m asyncHttpClient.executeRequest(requestBuilder, new AsyncCompletionHandler<Response>() { @Override public Response onCompleted(Response response) throws Exception { if (checkFailStatusCode(response) || checkFailBody(response)) return response; definePropertiesAndUpdate(OK, OK.toString()); return response; } @Override public void onThrowable(Throwable t) { definePropertiesAndUpdate(UNKNOWN, t.getMessage()); } private boolean checkFailBody(Response response) { if (!"".equals(hcBody)) { String body = response.getResponseBody(); if (body != null && !body.isEmpty() && !body.contains(hcBody)) { definePropertiesAndUpdate(FAIL, "Body check FAIL"); return true; } } return false; } private boolean checkFailStatusCode(Response response) { if (!"".equals(hcStatusCode)) { String statusCodeStr = String.valueOf(response.getStatusCode()); if (!hcStatusCode.equals(statusCodeStr)) { definePropertiesAndUpdate(FAIL, "HTTP Status Code check FAIL"); return true; } } return false; } private void definePropertiesAndUpdate(EnumHealthState state, String reason) { String newHealthyState = state.toString(); target.getProperties().put(PROP_HEALTHY.toString(), newHealthyState); target.getProperties().put(PROP_STATUS_DETAILED.toString(), reason); String logMessage = buildLogMessage(reason); if (state.equals(OK)) { logger.info(logMessage); } else { logger.warn(logMessage); } if (lastReason == null || !reason.equals(lastReason)) { callBackQueue.update(target); } } private String buildLogMessage(String reason) { return "Pool " + poolName + " -> " + "Test Params: { " + "ExpectedBody:\"" + hcBody + "\", " + "ExpectedStatusCode:" + hcStatusCode + ", " + "Host:\"" + hcHost + "\", " + "FullUrl:\"" + target.getName() + hcPath + "\", " + "ConnectionTimeout:" + connectionTimeout + "ms }, " + "Result: [ " + reason + " (request time: " + (System.currentTimeMillis() - start) + " ms) ]"; } }); }
From source file:alfio.controller.form.ReservationForm.java
private int additionalServicesSelectionCount(AdditionalServiceRepository additionalServiceRepository, int eventId) { return (int) selectedAdditionalServices().stream() .filter(as -> as.getAdditionalServiceId() != null && (additionalServiceRepository.getById(as.getAdditionalServiceId(), eventId).isFixPrice() || Optional.ofNullable(as.getAmount()).filter(a -> a.compareTo(BigDecimal.ZERO) > 0) .isPresent())) .count();//from www . j av a2s . c o m }
From source file:io.pivotal.strepsirrhini.chaosloris.destroyer.DestructionScheduler.java
private static Mono<ScheduledFuture<?>> putSchedule(Map<Long, ScheduledFuture<?>> scheduled, Long id, ScheduledFuture<?> future) { return Optional.ofNullable(scheduled.put(id, future)) .map((Function<ScheduledFuture<?>, Mono<ScheduledFuture<?>>>) Mono::just).orElse(Mono.empty()); }