use of java.util.Optional.ofNullable in project alf.io by alfio-event.
the class ReservationForm method validate.
public Optional<Pair<List<TicketReservationWithOptionalCodeModification>, List<ASReservationWithOptionalCodeModification>>> validate(Errors bindingResult, TicketReservationManager tickReservationManager, AdditionalServiceRepository additionalServiceRepository, EventManager eventManager, Event event) {
int selectionCount = ticketSelectionCount();
if (selectionCount <= 0) {
bindingResult.reject(ErrorsCode.STEP_1_SELECT_AT_LEAST_ONE);
return Optional.empty();
}
List<Pair<TicketReservationModification, Integer>> maxTicketsByTicketReservation = selected().stream().map(r -> Pair.of(r, tickReservationManager.maxAmountOfTicketsForCategory(event.getOrganizationId(), event.getId(), r.getTicketCategoryId()))).collect(toList());
Optional<Pair<TicketReservationModification, Integer>> error = maxTicketsByTicketReservation.stream().filter(p -> p.getKey().getAmount() > p.getValue()).findAny();
if (error.isPresent()) {
bindingResult.reject(ErrorsCode.STEP_1_OVER_MAXIMUM, new Object[] { error.get().getValue() }, null);
return Optional.empty();
}
final List<TicketReservationModification> categories = selected();
final List<AdditionalServiceReservationModification> additionalServices = selectedAdditionalServices();
final boolean validCategorySelection = categories.stream().allMatch(c -> {
TicketCategory tc = eventManager.getTicketCategoryById(c.getTicketCategoryId(), event.getId());
return OptionalWrapper.optionally(() -> eventManager.findEventByTicketCategory(tc)).isPresent();
});
final boolean validAdditionalServiceSelected = additionalServices.stream().allMatch(asm -> {
AdditionalService as = eventManager.getAdditionalServiceById(asm.getAdditionalServiceId(), event.getId());
ZonedDateTime now = ZonedDateTime.now(event.getZoneId());
return as.getInception(event.getZoneId()).isBefore(now) && as.getExpiration(event.getZoneId()).isAfter(now) && asm.getQuantity() >= 0 && ((as.isFixPrice() && asm.isQuantityValid(as, selectionCount)) || (!as.isFixPrice() && asm.getAmount() != null && asm.getAmount().compareTo(BigDecimal.ZERO) >= 0)) && OptionalWrapper.optionally(() -> eventManager.findEventByAdditionalService(as)).isPresent();
});
if (!validCategorySelection || !validAdditionalServiceSelected) {
bindingResult.reject(ErrorsCode.STEP_1_TICKET_CATEGORY_MUST_BE_SALEABLE);
return Optional.empty();
}
List<TicketReservationWithOptionalCodeModification> res = new ArrayList<>();
//
Optional<SpecialPrice> specialCode = Optional.ofNullable(StringUtils.trimToNull(promoCode)).flatMap((trimmedCode) -> tickReservationManager.getSpecialPriceByCode(trimmedCode));
//
final ZonedDateTime now = ZonedDateTime.now(event.getZoneId());
maxTicketsByTicketReservation.forEach((pair) -> validateCategory(bindingResult, tickReservationManager, eventManager, event, pair.getRight(), res, specialCode, now, pair.getLeft()));
return bindingResult.hasErrors() ? Optional.empty() : Optional.of(Pair.of(res, additionalServices.stream().map(as -> new ASReservationWithOptionalCodeModification(as, specialCode)).collect(Collectors.toList())));
}
use of java.util.Optional.ofNullable in project component-runtime by Talend.
the class BaseSpark method submit.
/**
* Submits a main to spark cluster.
*
* @param main
* the main to submit to spark.
* @param args
* the spark submit arguments, some values have defaults like memory,
* cores number and deploy mode.
*/
public void submit(final Class<?> main, final String... args) {
final String bundle = of(main).map(c -> c.getName().replace('.', '/') + ".class").flatMap(resource -> config.get().jarCache.entrySet().stream().filter(jar -> new File(jar.getKey(), resource).exists()).findAny().map(Map.Entry::getValue)).orElseGet(() -> // shade case in IT
of(jarLocation(main)).flatMap(f -> f.getName().endsWith(".jar") ? Optional.of(f) : Optional.ofNullable(f.getParentFile().listFiles()).map(Stream::of).orElseGet(Stream::empty).filter(file -> file.getName().endsWith(".jar") && !file.getName().startsWith("original-")).findFirst()).orElseThrow(() -> new IllegalStateException("No bundle jar found from " + main + ", run tests after packaging (IT with failsafe for instance)"))).getAbsolutePath();
final String[] submitArgs = Stream.concat(Stream.concat(Stream.concat(Stream.of("org.apache.spark.deploy.SparkSubmit", "--verbose"), new HashMap<String, String>() {
{
// overridable by args, it is just defaults
// 256m fails so don't reduce it too much if you try
put("--executor-memory", "512m");
// to go that way
put("--driver-memory", "512m");
put("--total-executor-cores", "1");
put("--deploy-mode", "cluster");
}
}.entrySet().stream().filter(e -> Stream.of(args).noneMatch(p -> p.equals(e.getKey()))).flatMap(e -> Stream.of(e.getKey(), e.getValue()))), Stream.of("--master", getSparkMaster(), "--class", main.getName(), bundle)), args == null ? Stream.empty() : Stream.of(args)).toArray(String[]::new);
LOGGER.info("Submitting: " + asList(submitArgs));
final SparkProcessMonitor monitor = new SparkProcessMonitor(config.get(), "spark-submit-" + main.getSimpleName() + "-monitor", () -> true, submitArgs);
final Thread hook = new Thread(monitor::close);
final Runnable shutdownHookCleanup = () -> Runtime.getRuntime().removeShutdownHook(hook);
config.get().cleanupTasks.add(shutdownHookCleanup);
monitor.start();
assertTrue("monitor is not started", monitor.isStarted());
int retries = 500;
while (monitor.process != null && retries-- > 0) {
try {
LOGGER.info("Submit result: " + monitor.process.exitValue());
monitor.close();
config.get().cleanupTasks.remove(shutdownHookCleanup);
Runtime.getRuntime().removeShutdownHook(hook);
} catch (final IllegalThreadStateException itse) {
try {
sleep(750);
} catch (final InterruptedException e) {
fail(e.getMessage());
break;
}
}
}
}
use of java.util.Optional.ofNullable in project alf.io by alfio-event.
the class ReservationUtil method validateCreateRequest.
public static Optional<Pair<List<TicketReservationWithOptionalCodeModification>, List<ASReservationWithOptionalCodeModification>>> validateCreateRequest(ReservationCreate request, Errors bindingResult, TicketReservationManager tickReservationManager, EventManager eventManager, String validatedPromoCodeDiscount, Event event) {
int selectionCount = ticketSelectionCount(request.getTickets());
if (selectionCount <= 0) {
bindingResult.reject(ErrorsCode.STEP_1_SELECT_AT_LEAST_ONE);
return Optional.empty();
}
List<Pair<TicketReservationModification, Integer>> maxTicketsByTicketReservation = selected(request.getTickets()).stream().map(r -> Pair.of(r, tickReservationManager.maxAmountOfTicketsForCategory(event, r.getTicketCategoryId(), validatedPromoCodeDiscount))).collect(toList());
Optional<Pair<TicketReservationModification, Integer>> error = maxTicketsByTicketReservation.stream().filter(p -> p.getKey().getQuantity() > p.getValue()).findAny();
if (error.isPresent()) {
bindingResult.reject(ErrorsCode.STEP_1_OVER_MAXIMUM, new Object[] { error.get().getValue() }, null);
return Optional.empty();
}
final List<TicketReservationModification> categories = selected(request.getTickets());
final List<AdditionalServiceReservationModification> additionalServices = selectedAdditionalServices(request.getAdditionalServices());
final boolean validCategorySelection = categories.stream().allMatch(c -> {
TicketCategory tc = eventManager.getTicketCategoryById(c.getTicketCategoryId(), event.getId());
return eventManager.eventExistsById(tc.getEventId());
});
final boolean validAdditionalServiceSelected = additionalServices.stream().allMatch(asm -> {
AdditionalService as = eventManager.getAdditionalServiceById(asm.getAdditionalServiceId(), event.getId());
ZonedDateTime now = event.now(ClockProvider.clock());
return as.getInception(event.getZoneId()).isBefore(now) && as.getExpiration(event.getZoneId()).isAfter(now) && asm.getQuantity() >= 0 && ((as.isFixPrice() && asm.isQuantityValid(as, selectionCount)) || (!as.isFixPrice() && asm.getAmount() != null && asm.getAmount().compareTo(BigDecimal.ZERO) >= 0)) && eventManager.eventExistsById(as.getEventId());
});
if (!validCategorySelection || !validAdditionalServiceSelected) {
bindingResult.reject(ErrorsCode.STEP_1_TICKET_CATEGORY_MUST_BE_SALEABLE);
return Optional.empty();
}
List<TicketReservationWithOptionalCodeModification> res = new ArrayList<>();
//
Optional<SpecialPrice> specialCode = Optional.ofNullable(StringUtils.trimToNull(request.getPromoCode())).flatMap(tickReservationManager::getSpecialPriceByCode);
//
final ZonedDateTime now = event.now(ClockProvider.clock());
maxTicketsByTicketReservation.forEach(pair -> validateCategory(bindingResult, tickReservationManager, eventManager, event, pair.getRight(), res, specialCode, now, pair.getLeft()));
return bindingResult.hasErrors() ? Optional.empty() : Optional.of(Pair.of(res, additionalServices.stream().map(as -> new ASReservationWithOptionalCodeModification(as, specialCode)).collect(Collectors.toList())));
}
Aggregations