List of usage examples for java.util Optional ifPresent
public void ifPresent(Consumer<? super T> action)
From source file:org.fineract.module.stellar.horizonadapter.HorizonServerPaymentObserver.java
private void setupListeningForAccount(@NotNull final StellarAccountId stellarAccountId, @NotNull final Optional<String> cursor) { logger.info("HorizonServerPaymentObserver.setupListeningForAccount {}, cursor {}", stellarAccountId.getPublicKey(), cursor); final EffectsRequestBuilder effectsRequestBuilder = new EffectsRequestBuilder(URI.create(serverAddress)); effectsRequestBuilder.forAccount(KeyPair.fromAccountId(stellarAccountId.getPublicKey())); cursor.ifPresent(effectsRequestBuilder::cursor); effectsRequestBuilder.stream(listener); }
From source file:it.polimi.diceH2020.SPACE4CloudWS.core.CoarseGrainedOptimizer.java
private boolean hillClimbing(SolutionPerJob solPerJob, Technology technology) { boolean success = false; Pair<Optional<Double>, Long> simulatorResult = dataProcessor.simulateClass(solPerJob); Optional<Double> maybeResult = simulatorResult.getLeft(); if (maybeResult.isPresent()) { success = true;// ww w. ja v a 2 s . c o m PerformanceSolver currentSolver = dataProcessor.getPerformanceSolver(); Function<Double, Double> fromResult = currentSolver.transformationFromSolverResult(solPerJob, technology); Predicate<Double> feasibilityCheck = currentSolver.feasibilityCheck(solPerJob, technology); Consumer<Double> metricUpdater = currentSolver.metricUpdater(solPerJob, technology); final double tolerance = settings.getOptimization().getTolerance(); BiPredicate<Double, Double> incrementCheck; Function<Integer, Integer> updateFunction; Predicate<Double> stoppingCondition; Predicate<Integer> vmCheck; double responseTime = fromResult.apply(maybeResult.get()); if (feasibilityCheck.test(responseTime)) { updateFunction = n -> n - 1; stoppingCondition = feasibilityCheck.negate(); vmCheck = n -> n == 1; incrementCheck = (prev, curr) -> false; } else { updateFunction = n -> n + 1; stoppingCondition = feasibilityCheck; vmCheck = n -> false; incrementCheck = (prev, curr) -> Math.abs((prev - curr) / prev) < tolerance; } List<Triple<Integer, Optional<Double>, Boolean>> resultsList = alterUntilBreakPoint(solPerJob, updateFunction, fromResult, feasibilityCheck, stoppingCondition, incrementCheck, vmCheck); Optional<Triple<Integer, Optional<Double>, Boolean>> result = resultsList.parallelStream() .filter(t -> t.getRight() && t.getMiddle().isPresent()) .min(Comparator.comparing(Triple::getLeft)); result.ifPresent(triple -> triple.getMiddle().ifPresent(output -> { int nVM = triple.getLeft(); switch (technology) { case HADOOP: case SPARK: solPerJob.setThroughput(output); break; case STORM: break; default: throw new RuntimeException("Unexpected technology"); } solPerJob.updateNumberVM(nVM); double metric = fromResult.apply(output); metricUpdater.accept(metric); logger.info(String.format( "class%s-> MakeFeasible ended, result = %f, other metric = %f, obtained with: %d VMs", solPerJob.getId(), output, metric, nVM)); })); } else { logger.info("class" + solPerJob.getId() + "-> MakeFeasible ended with ERROR"); solPerJob.setFeasible(false); } return success; }
From source file:alfio.controller.api.support.TicketHelper.java
public Optional<Triple<ValidationResult, Event, Ticket>> assignTicket(String eventName, String ticketIdentifier, UpdateTicketOwnerForm updateTicketOwner, Optional<Errors> bindingResult, HttpServletRequest request, Consumer<Triple<ValidationResult, Event, Ticket>> reservationConsumer, Optional<UserDetails> userDetails) { Optional<Triple<ValidationResult, Event, Ticket>> triple = ticketReservationManager .fetchComplete(eventName, ticketIdentifier) .map(result -> assignTicket(updateTicketOwner, bindingResult, request, userDetails, result)); triple.ifPresent(reservationConsumer); return triple; }
From source file:net.rptools.tokentool.controller.ManageOverlays_Controller.java
@FXML void addFolderButton_onAction(ActionEvent event) { TextInputDialog dialog = new TextInputDialog(); dialog.setTitle(I18N.getString("ManageOverlays.filechooser.folder.title")); dialog.setContentText(I18N.getString("ManageOverlays.filechooser.folder.content_text")); Optional<String> result = dialog.showAndWait(); result.ifPresent(name -> { if (FileSaveUtil.makeDir(name, currentDirectory)) { displayTreeView();//from w w w . j a v a2 s . c o m } ; }); }
From source file:gov.ca.cwds.cals.service.builder.PlacementHomeEntityAwareDTOBuilder.java
public PlacementHomeEntityAwareDTOBuilder appendCountyLicenseCase() { CLCEntityAwareDTO clcEntityAwareDTO = new CLCEntityAwareDTO(); Optional<StaffPerson> staffPerson = Optional .ofNullable(staffPersonService.find(PrincipalUtils.getStaffPersonId())); CountyLicenseCase countyLicenseCase = countyLicenseCaseMapper.toCountyLicenseCase(form); staffPerson.ifPresent(countyLicenseCase::setStaffPerson); clcEntityAwareDTO.setEntity(countyLicenseCase); placementHomeEntityAwareDTO.setCountyLicenseCase(clcEntityAwareDTO); return this; }
From source file:org.obiba.mica.core.upgrade.Mica310Upgrade.java
private void addRecruitmentsIfMissing(Study study, List<JSONObject> history) { try {//ww w.j a v a 2s. c o m if (!containsRecruitments(study)) { Optional<List<String>> optionalRecruitments = history.stream().filter(this::containsRecruitment) .findFirst().map(this::extractRecruitments); optionalRecruitments .ifPresent(recruitments -> (getModelMethods(study)).put("recruitments", recruitments)); } } catch (RuntimeException ignore) { } }
From source file:com.hp.autonomy.hod.client.api.developer.ApplicationServiceImpl.java
@Override public void update(final AuthenticationToken<EntityType.Developer, TokenType.HmacSha1> token, final String domain, final String name, final ApplicationUpdateRequest updateRequest) throws HodErrorException { final Optional<List<String>> optionalAuthModes = updateRequest.getAuthentications() .map(authentications -> authentications.stream().map(this::serializeAuthentication) .collect(Collectors.toList())); final Map<String, List<String>> body = new HashMap<>(); final Map<String, String> bodyMultiMap = new MultiMap<>(); optionalAuthModes.ifPresent(authenticationStrings -> { body.put(AUTH_MODES_PART, authenticationStrings); authenticationStrings.forEach(s -> bodyMultiMap.put(AUTH_MODES_PART, s)); });/*from w w w . java 2 s .com*/ updateRequest.getDescription().ifPresent(description -> { body.put(DESCRIPTION_PART, Collections.singletonList(description)); bodyMultiMap.put(DESCRIPTION_PART, description); }); final Request<Void, String> request = new Request<>(Request.Verb.PATCH, pathForApplication(domain, name) + "/v1", null, body); final String signature = hmac.generateToken(request, token); backend.update(signature, domain, name, bodyMultiMap); }
From source file:nu.yona.server.ThymeleafConfiguration.java
private TemplateEngine templateEngine(Optional<ResourceBundleMessageSource> messageSource, AbstractTemplateResolver... templateResolvers) { final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); int i = 1;// www. ja v a 2s .c om for (AbstractTemplateResolver templateResolver : templateResolvers) { templateResolver.setOrder(i++); templateEngine.addTemplateResolver(templateResolver); } messageSource.ifPresent(templateEngine::setTemplateEngineMessageSource); return templateEngine; }
From source file:nc.noumea.mairie.appock.viewmodel.EditStockViewModel.java
protected void creeMultipleNouvelleSortieStock(List<EntreeSortieStock> listeSortieStock) { listeSortieStock.forEach(sortieStock -> { // On rcupre la dernire version de ArticleStock mis jour par les itrations prcdentes Stock stock = stockService.findOne(sortieStock.getArticleStock().getStock().getId()); Optional<ArticleStock> optionalArticleStock = stock.getListeArticleStock().stream() .filter(a -> a.getId().equals(sortieStock.getArticleStock().getId())).findFirst(); optionalArticleStock.ifPresent(articleStock -> creeNouvelleSortieStock(articleStock, sortieStock.getQuantiteASortir(), sortieStock.getObservation())); });//w w w. j av a2 s. co m }
From source file:nc.noumea.mairie.appock.viewmodel.EditStockViewModel.java
protected void creeEntreeSortieGeneric(List<EntreeSortieStock> listeEntreeStock, TypeMouvementStock typeMouvementStock) { listeEntreeStock.forEach(entreeStock -> { // On rcupre la dernire version de ArticleStock mis jour par les itrations prcdentes Stock stock = stockService.findOne(entreeStock.getArticleStock().getStock().getId()); Optional<ArticleStock> optionalArticleStock = stock.getListeArticleStock().stream() .filter(a -> a.getId().equals(entreeStock.getArticleStock().getId())).findFirst(); optionalArticleStock.ifPresent(articleStock -> creeEntreeSortieGeneric(articleStock, entreeStock.getQuantiteASortir(), entreeStock.getObservation(), typeMouvementStock)); });//from ww w .ja v a2 s. c om }