List of usage examples for java.util.function Supplier get
T get();
From source file:de.fosd.jdime.matcher.cost_model.CostModelMatcher.java
/** * Logs the given <code>msg</code> using the {@link #LOG} and prepends the {@link #id(Object)} of the given * matchings.//from w ww . j a v a2s. c o m * * @param level * the level to log at * @param matchings * the matchings the message concerns * @param msg * the message to log */ private void log(Level level, CMMatchings<T> matchings, Supplier<String> msg) { LOG.log(level, () -> String.format("%-10s%s", id(matchings), msg.get())); }
From source file:com.example.app.profile.model.ProfileDAO.java
/** * Get a ProfileType with the given programmatic identifier, or create one * * @param programmaticId the programmatic identifier * @param nameSupplier a Supplier for a LocalizedObjectKey -- only used if the ProfileType is created * @param kindSupplier a Supplier for a Profile Type Kind. This may return null. * * @return the persisted ProfileType//from w w w.j a v a2 s . c o m */ @Nonnull public ProfileType getProfileTypeOrNew(@Nonnull String programmaticId, @Nonnull Supplier<LocalizedObjectKey> nameSupplier, @Nonnull Supplier<Label> kindSupplier) { return getProfileType(programmaticId).orElseGet(() -> { ProfileType pt = new ProfileType(); pt.setProgrammaticIdentifier(programmaticId); pt.setName(nameSupplier.get()); pt.setKind(kindSupplier.get()); return mergeProfileType(pt); }); }
From source file:de.acosix.alfresco.site.hierarchy.repo.service.SiteHierarchyServiceImpl.java
protected void withAspectInheritedPropertyRemovalGuard(final NodeRef node, final QName baseAspect, final Supplier<?> fn) { // there is a bug when aspects that inherit from another are removed but the base aspect remains // all properties of the base aspect are deleted as well final AspectDefinition aspect = this.dictionaryService.getAspect(baseAspect); final Set<QName> propertiesToPreserve = aspect.getProperties().keySet(); final Map<QName, Serializable> properties = this.nodeService.getProperties(node); final Map<QName, Serializable> propertiesBackup = new HashMap<>(); propertiesToPreserve.forEach(propertyQName -> { if (properties.containsKey(propertyQName)) { propertiesBackup.put(propertyQName, properties.get(propertyQName)); }/* w w w . ja v a 2 s. c o m*/ }); fn.get(); if (!propertiesBackup.isEmpty()) { this.nodeService.addProperties(node, propertiesBackup); } }
From source file:com.vmware.xenon.swagger.SwaggerAssembler.java
private Map<String, Path> pathByRoutes(Collection<List<Route>> serviceRoutes, Supplier<Path> pathProto) { Map<String, Path> res = new HashMap<>(); for (List<Route> routes : serviceRoutes) { for (Route route : routes) { String key = route.path; if (key == null) { key = ""; }/*from w w w.ja v a 2s .c o m*/ Path path = res.get(key); if (path == null) { path = pathProto.get(); res.put(key, path); } if (route.supportLevel != null && route.supportLevel.compareTo(this.supportLevel) < 0) { // skip this route, it's below the documentation threshold for supported levels continue; } // Although Xenon allows us to route same action (POST, PATCH, etc.) to different // implementation based on request type Swagger doesn't handle same operation with // different data types. For example: PATCH /user with UserProfile PODO and // PATCH /user with MemberProfile. // Reference: https://github.com/OAI/OpenAPI-Specification/issues/146 io.swagger.models.Operation op = new io.swagger.models.Operation(); op.addTag(this.currentTag.getName()); op.setDescription(route.description); if (route.supportLevel != null && route.supportLevel == SupportLevel.DEPRECATED) { op.setDeprecated(true); } List<Parameter> swaggerParams = new ArrayList<>(); Map<String, Response> swaggerResponses = new LinkedHashMap<>(); List<String> consumesList = new ArrayList<>(); List<String> producesList = new ArrayList<>(); if (route.parameters != null && !route.parameters.isEmpty()) { // From the parameters list split body / query parameters List<RequestRouter.Parameter> bodyParams = new ArrayList<>(); route.parameters.forEach((p) -> { switch (p.paramDef) { case BODY: bodyParams.add(p); break; case PATH: swaggerParams.add(paramPath(p)); break; case QUERY: swaggerParams.add(paramQuery(p, route)); break; case RESPONSE: swaggerResponses.put(p.name, paramResponse(p, route)); break; case CONSUMES: consumesList.add(p.name); break; case PRODUCES: producesList.add(p.name); break; default: break; } }); if (bodyParams.isEmpty() && route.requestType != null) { swaggerParams.add(paramBody(route.requestType)); } // This is to handle the use case of having multiple values in the body for a // given operation. if (!bodyParams.isEmpty()) { swaggerParams.add(paramBody(bodyParams, route)); } } else if (route.requestType != null) { swaggerParams.add(paramBody(route.requestType)); } if (!swaggerParams.isEmpty()) { op.setParameters(swaggerParams); } if (swaggerResponses.isEmpty()) { // Add default response codes op.setResponses(responseMap(Operation.STATUS_CODE_OK, responseOk(route.responseType), Operation.STATUS_CODE_NOT_FOUND, responseGenericError())); } else { op.setResponses(swaggerResponses); } if (!consumesList.isEmpty()) { op.setConsumes(consumesList); } if (!producesList.isEmpty()) { op.setProduces(producesList); } switch (route.action) { case POST: path.post(getSwaggerOperation(op, path.getPost())); break; case PUT: path.put(getSwaggerOperation(op, path.getPut())); break; case PATCH: path.patch(getSwaggerOperation(op, path.getPatch())); break; case GET: path.get(getSwaggerOperation(op, path.getGet())); break; case DELETE: path.delete(getSwaggerOperation(op, path.getDelete())); break; case OPTIONS: path.options(getSwaggerOperation(op, path.getOptions())); break; default: throw new IllegalStateException("Unknown route action encounter: " + route.action); } } } return res; }
From source file:com.yahoo.elide.Elide.java
/** * Handle PATCH.//from www . jav a2 s .co m * * @param contentType the content type * @param accept the accept * @param path the path * @param jsonApiDocument the json api document * @param opaqueUser the opaque user * @param securityMode only for test mode * @return Elide response object */ public ElideResponse patch(String contentType, String accept, String path, String jsonApiDocument, Object opaqueUser, SecurityMode securityMode) { try (DataStoreTransaction transaction = dataStore.beginTransaction()) { User user = transaction.accessUser(opaqueUser); RequestScope requestScope; Supplier<Pair<Integer, JsonNode>> responder; if (JsonApiPatch.isPatchExtension(contentType) && JsonApiPatch.isPatchExtension(accept)) { // build Outer RequestScope to be used for each action PatchRequestScope patchRequestScope = new PatchRequestScope(transaction, user, dictionary, mapper, auditLogger); requestScope = patchRequestScope; responder = JsonApiPatch.processJsonPatch(dataStore, path, jsonApiDocument, patchRequestScope); } else { JsonApiDocument doc = mapper.readJsonApiDocument(jsonApiDocument); requestScope = new RequestScope(doc, transaction, user, dictionary, mapper, auditLogger, securityMode); PatchVisitor visitor = new PatchVisitor(requestScope); responder = visitor.visit(parse(path)); } requestScope.runDeferredPermissionChecks(); transaction.flush(); ElideResponse response = buildResponse(responder.get()); auditLogger.commit(); transaction.commit(); requestScope.runCommitTriggers(); return response; } catch (HttpStatusException e) { return buildErrorResponse(e, securityMode); } catch (ParseCancellationException e) { return buildErrorResponse(new InvalidURLException(e), securityMode); } catch (IOException e) { return buildErrorResponse(new TransactionException(e), securityMode); } }
From source file:com.example.app.profile.model.ProfileDAO.java
/** * Get a MembershipOperation from the database based on the programmatic identifier, or if one does not exist, create it. * * @param programmaticIdentifier the programmatic identifier to search for * @param displayNameSupplier a supplier of the display name of the MembershipOperation -- only used in the case of creation * * @return a matching MembershipOperation based on programmatic identifier, * or a new MembershipOperation that has been persisted. *//* w w w . j a v a 2 s .c o m*/ public MembershipOperation getMembershipOperationOrNew(@Nonnull String programmaticIdentifier, @Nonnull Supplier<LocalizedObjectKey> displayNameSupplier) { return getMembershipOperation(programmaticIdentifier).orElseGet(() -> { MembershipOperation newOperation = new MembershipOperation(); newOperation.setProgrammaticIdentifier(programmaticIdentifier); newOperation.setName(displayNameSupplier.get()); return saveMembershipOperation(newOperation); }); }
From source file:com.redhat.red.build.koji.KojiClient.java
protected Map<String, KojiClientException> uploadForImport(KojiImport buildInfo, Supplier<Iterable<ImportFile>> outputSupplier, String dirname, KojiSessionInfo session) throws KojiClientException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {/*from w ww. j av a 2s . co m*/ objectMapper.writeValue(baos, buildInfo); } catch (IOException e) { throw new KojiClientException("Failed to serialize import info to JSON. Reason: %s", e, e.getMessage()); } AtomicInteger count = new AtomicInteger(0); uploadService.submit( newUploader(new ImportFile(METADATA_JSON_FILE, new ByteArrayInputStream(baos.toByteArray())), dirname, session)); count.incrementAndGet(); outputSupplier.get().forEach((importFile) -> { uploadService.submit(newUploader(importFile, dirname, session)); count.incrementAndGet(); }); Logger logger = LoggerFactory.getLogger(getClass()); Map<String, KojiClientException> uploadErrors = new HashMap<>(); Set<UploadResponse> responses = new HashSet<>(); int total = count.get(); do { logger.debug("Waiting for %d uploads.", count.get()); try { Future<KojiUploaderResult> future = uploadService.take(); KojiUploaderResult result = future.get(); KojiClientException error = result.getError(); if (error != null) { uploadErrors.put(result.getImportFile().getFilePath(), error); } else { responses.add(result.getResponse()); } } catch (InterruptedException e) { logger.debug("Interrupted while uploading. Aborting upload."); break; } catch (ExecutionException e) { throw new KojiClientException("Failed to execute %d uploads for: %s. Reason: %s", e, total, buildInfo, e.getMessage()); } } while (count.decrementAndGet() > 0); return uploadErrors; }
From source file:org.elasticsearch.client.RequestConvertersTests.java
private static void setRandomIndicesOptions(Consumer<IndicesOptions> setter, Supplier<IndicesOptions> getter, Map<String, String> expectedParams) { if (randomBoolean()) { setter.accept(//from w ww .j av a 2s.c o m IndicesOptions.fromOptions(randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean())); } expectedParams.put("ignore_unavailable", Boolean.toString(getter.get().ignoreUnavailable())); expectedParams.put("allow_no_indices", Boolean.toString(getter.get().allowNoIndices())); if (getter.get().expandWildcardsOpen() && getter.get().expandWildcardsClosed()) { expectedParams.put("expand_wildcards", "open,closed"); } else if (getter.get().expandWildcardsOpen()) { expectedParams.put("expand_wildcards", "open"); } else if (getter.get().expandWildcardsClosed()) { expectedParams.put("expand_wildcards", "closed"); } else { expectedParams.put("expand_wildcards", "none"); } }
From source file:org.eclipse.hono.client.impl.HonoClientImpl.java
Future<MessageConsumer> createConsumer(final String tenantId, final Supplier<Future<MessageConsumer>> newConsumerSupplier) { final Future<MessageConsumer> result = Future.future(); context.runOnContext(get -> {/*w w w . ja va 2 s. c om*/ // register a handler to be notified if the underlying connection to the server fails // so that we can fail the result handler passed in final Handler<Void> connectionFailureHandler = connectionLost -> { result.tryFail( new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "connection to server lost")); }; creationRequests.add(connectionFailureHandler); newConsumerSupplier.get().setHandler(attempt -> { creationRequests.remove(connectionFailureHandler); if (attempt.succeeded()) { result.tryComplete(attempt.result()); } else { result.tryFail(attempt.cause()); } }); }); return result; }
From source file:alfio.manager.PaypalManager.java
Optional<PaymentInformation> getInfo(String paymentId, String transactionId, Event event, Supplier<String> platformFeeSupplier) { try {/*from ww w . java 2 s. co m*/ String refund = null; APIContext apiContext = getApiContext(event); //check for backward compatibility reason... if (paymentId != null) { //navigate in all refund objects and sum their amount refund = Payment.get(apiContext, paymentId).getTransactions().stream() .map(Transaction::getRelatedResources).flatMap(List::stream) .filter(f -> f.getRefund() != null).map(RelatedResources::getRefund).map(Refund::getAmount) .map(Amount::getTotal).map(BigDecimal::new).reduce(BigDecimal.ZERO, BigDecimal::add) .toPlainString(); // } Capture c = Capture.get(apiContext, transactionId); String gatewayFee = Optional.ofNullable(c.getTransactionFee()).map(Currency::getValue) .map(BigDecimal::new).map(MonetaryUtil::unitToCents).map(String::valueOf).orElse(null); return Optional.of(new PaymentInformation(c.getAmount().getTotal(), refund, gatewayFee, platformFeeSupplier.get())); } catch (PayPalRESTException ex) { log.warn("Paypal: error while fetching information for payment id " + transactionId, ex); return Optional.empty(); } }