Search in sources :

Example 1 with Optional.ofNullable

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())));
}
Also used : Errors(org.springframework.validation.Errors) TicketReservationModification(alfio.model.modification.TicketReservationModification) ZonedDateTime(java.time.ZonedDateTime) SaleableTicketCategory(alfio.controller.decorator.SaleableTicketCategory) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) BigDecimal(java.math.BigDecimal) Pair(org.apache.commons.lang3.tuple.Pair) ASReservationWithOptionalCodeModification(alfio.model.modification.ASReservationWithOptionalCodeModification) AdditionalServiceRepository(alfio.repository.AdditionalServiceRepository) TicketReservationWithOptionalCodeModification(alfio.model.modification.TicketReservationWithOptionalCodeModification) Collections.emptyList(java.util.Collections.emptyList) Optional.ofNullable(java.util.Optional.ofNullable) ErrorsCode(alfio.util.ErrorsCode) OptionalWrapper(alfio.util.OptionalWrapper) Collectors(java.util.stream.Collectors) Serializable(java.io.Serializable) TicketReservationManager(alfio.manager.TicketReservationManager) TicketCategory(alfio.model.TicketCategory) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) EventManager(alfio.manager.EventManager) AdditionalService(alfio.model.AdditionalService) SpecialPrice(alfio.model.SpecialPrice) Data(lombok.Data) Optional(java.util.Optional) Event(alfio.model.Event) AdditionalServiceReservationModification(alfio.model.modification.AdditionalServiceReservationModification) SpecialPrice(alfio.model.SpecialPrice) AdditionalService(alfio.model.AdditionalService) ArrayList(java.util.ArrayList) SaleableTicketCategory(alfio.controller.decorator.SaleableTicketCategory) TicketCategory(alfio.model.TicketCategory) ASReservationWithOptionalCodeModification(alfio.model.modification.ASReservationWithOptionalCodeModification) AdditionalServiceReservationModification(alfio.model.modification.AdditionalServiceReservationModification) TicketReservationWithOptionalCodeModification(alfio.model.modification.TicketReservationWithOptionalCodeModification) ZonedDateTime(java.time.ZonedDateTime) TicketReservationModification(alfio.model.modification.TicketReservationModification) Pair(org.apache.commons.lang3.tuple.Pair)

Example 2 with Optional.ofNullable

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;
            }
        }
    }
}
Also used : AcceptScopesStrategy(org.jboss.shrinkwrap.resolver.api.maven.strategy.AcceptScopesStrategy) URL(java.net.URL) MavenResolutionStrategy(org.jboss.shrinkwrap.resolver.api.maven.strategy.MavenResolutionStrategy) Optional.of(java.util.Optional.of) LoggerFactory(org.slf4j.LoggerFactory) SparkClusterRule(org.talend.sdk.component.runtime.testing.spark.SparkClusterRule) BooleanSupplier(java.util.function.BooleanSupplier) InetAddress(java.net.InetAddress) ServerSocket(java.net.ServerSocket) Maven(org.jboss.shrinkwrap.resolver.api.maven.Maven) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) Thread.sleep(java.lang.Thread.sleep) ENGLISH(java.util.Locale.ENGLISH) Path(java.nio.file.Path) ZipEntry(java.util.zip.ZipEntry) Collectors.toSet(java.util.stream.Collectors.toSet) ScopeType(org.jboss.shrinkwrap.resolver.api.maven.ScopeType) Predicate(java.util.function.Predicate) Collection(java.util.Collection) StandardOpenOption(java.nio.file.StandardOpenOption) Set(java.util.Set) Collectors.joining(java.util.stream.Collectors.joining) StandardCharsets(java.nio.charset.StandardCharsets) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) ClassLoaders(org.apache.ziplock.ClassLoaders) Stream(java.util.stream.Stream) ConfigurableMavenResolverSystem(org.jboss.shrinkwrap.resolver.api.maven.ConfigurableMavenResolverSystem) Optional(java.util.Optional) IntStream(java.util.stream.IntStream) Socket(java.net.Socket) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Getter(lombok.Getter) HashMap(java.util.HashMap) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) UrlSet(org.apache.xbean.finder.UrlSet) JarEntry(java.util.jar.JarEntry) JarOutputStream(java.util.jar.JarOutputStream) OutputStream(java.io.OutputStream) Logger(org.slf4j.Logger) MalformedURLException(java.net.MalformedURLException) Files(java.nio.file.Files) Optional.ofNullable(java.util.Optional.ofNullable) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Collectors.toList(java.util.stream.Collectors.toList) JarLocation.jarLocation(org.apache.ziplock.JarLocation.jarLocation) AllArgsConstructor(lombok.AllArgsConstructor) InputStream(java.io.InputStream) HashMap(java.util.HashMap) Stream(java.util.stream.Stream) IntStream(java.util.stream.IntStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JarOutputStream(java.util.jar.JarOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) InputStream(java.io.InputStream) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap)

Example 3 with Optional.ofNullable

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())));
}
Also used : Errors(org.springframework.validation.Errors) TicketReservationModification(alfio.model.modification.TicketReservationModification) TicketReservationWithOptionalCodeModification(alfio.model.modification.TicketReservationWithOptionalCodeModification) PromoCodeRequestManager(alfio.manager.PromoCodeRequestManager) Collections.emptyList(java.util.Collections.emptyList) Optional.ofNullable(java.util.Optional.ofNullable) ZonedDateTime(java.time.ZonedDateTime) BindingResult(org.springframework.validation.BindingResult) SaleableTicketCategory(alfio.controller.decorator.SaleableTicketCategory) StringUtils(org.apache.commons.lang3.StringUtils) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) BigDecimal(java.math.BigDecimal) TicketReservationManager(alfio.manager.TicketReservationManager) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) EventManager(alfio.manager.EventManager) Pair(org.apache.commons.lang3.tuple.Pair) alfio.model(alfio.model) ValidatedResponse(alfio.manager.support.response.ValidatedResponse) ASReservationWithOptionalCodeModification(alfio.model.modification.ASReservationWithOptionalCodeModification) Optional(java.util.Optional) AdditionalServiceReservationModification(alfio.model.modification.AdditionalServiceReservationModification) ReservationCreate(alfio.controller.form.ReservationCreate) ArrayList(java.util.ArrayList) SaleableTicketCategory(alfio.controller.decorator.SaleableTicketCategory) ASReservationWithOptionalCodeModification(alfio.model.modification.ASReservationWithOptionalCodeModification) AdditionalServiceReservationModification(alfio.model.modification.AdditionalServiceReservationModification) TicketReservationWithOptionalCodeModification(alfio.model.modification.TicketReservationWithOptionalCodeModification) ZonedDateTime(java.time.ZonedDateTime) TicketReservationModification(alfio.model.modification.TicketReservationModification) Pair(org.apache.commons.lang3.tuple.Pair)

Aggregations

ArrayList (java.util.ArrayList)3 List (java.util.List)3 Optional (java.util.Optional)3 Optional.ofNullable (java.util.Optional.ofNullable)3 Collectors.toList (java.util.stream.Collectors.toList)3 SaleableTicketCategory (alfio.controller.decorator.SaleableTicketCategory)2 EventManager (alfio.manager.EventManager)2 TicketReservationManager (alfio.manager.TicketReservationManager)2 ASReservationWithOptionalCodeModification (alfio.model.modification.ASReservationWithOptionalCodeModification)2 AdditionalServiceReservationModification (alfio.model.modification.AdditionalServiceReservationModification)2 TicketReservationModification (alfio.model.modification.TicketReservationModification)2 TicketReservationWithOptionalCodeModification (alfio.model.modification.TicketReservationWithOptionalCodeModification)2 BigDecimal (java.math.BigDecimal)2 ZonedDateTime (java.time.ZonedDateTime)2 Collections.emptyList (java.util.Collections.emptyList)2 Collectors (java.util.stream.Collectors)2 StringUtils (org.apache.commons.lang3.StringUtils)2 Pair (org.apache.commons.lang3.tuple.Pair)2 Errors (org.springframework.validation.Errors)2 ReservationCreate (alfio.controller.form.ReservationCreate)1