Search in sources :

Example 96 with BeanPropertyBindingResult

use of org.springframework.validation.BeanPropertyBindingResult in project alf.io by alfio-event.

the class BillingDocumentCreationIntegrationTest method createReservation.

private String createReservation(Consumer<ContactAndTicketsForm> formCustomizer) {
    var categories = ticketCategoryRepository.findAllTicketCategories(event.getId());
    assertFalse(categories.isEmpty());
    int categoryId = categories.get(0).getId();
    var form = new ReservationForm();
    var ticketReservation = new TicketReservationModification();
    ticketReservation.setQuantity(1);
    ticketReservation.setTicketCategoryId(categoryId);
    form.setReservation(List.of(ticketReservation));
    var res = eventApiV2Controller.reserveTickets(event.getShortName(), "en", form, new BeanPropertyBindingResult(form, "reservation"), new ServletWebRequest(new MockHttpServletRequest(), new MockHttpServletResponse()), null);
    assertEquals(HttpStatus.OK, res.getStatusCode());
    var resBody = res.getBody();
    assertNotNull(resBody);
    assertTrue(resBody.isSuccess());
    assertEquals(0, resBody.getErrorCount());
    var reservationId = resBody.getValue();
    // reservation is now in PENDING status
    var resInfoRes = reservationApiV2Controller.getReservationInfo(reservationId, null);
    assertEquals(HttpStatus.OK, resInfoRes.getStatusCode());
    assertNotNull(resInfoRes.getBody());
    var ticketsByCat = resInfoRes.getBody().getTicketsByCategory();
    assertEquals(1, ticketsByCat.size());
    assertEquals(1, ticketsByCat.get(0).getTickets().size());
    var ticket = ticketsByCat.get(0).getTickets().get(0);
    var contactForm = new ContactAndTicketsForm();
    contactForm.setAddCompanyBillingDetails(true);
    contactForm.setSkipVatNr(false);
    contactForm.setInvoiceRequested(true);
    contactForm.setEmail("test@test.com");
    contactForm.setFirstName("full");
    contactForm.setLastName("name");
    var ticketForm1 = new UpdateTicketOwnerForm();
    ticketForm1.setFirstName("ticketfull");
    ticketForm1.setLastName("ticketname");
    ticketForm1.setEmail("tickettest@test.com");
    formCustomizer.accept(contactForm);
    contactForm.setTickets(Map.of(ticket.getUuid(), ticketForm1));
    var success = reservationApiV2Controller.validateToOverview(reservationId, "en", false, contactForm, new BeanPropertyBindingResult(contactForm, "paymentForm"), null);
    assertEquals(HttpStatus.OK, success.getStatusCode());
    var paymentForm = new PaymentForm();
    paymentForm.setPrivacyPolicyAccepted(true);
    paymentForm.setTermAndConditionsAccepted(true);
    paymentForm.setPaymentProxy(PaymentProxy.OFFLINE);
    paymentForm.setSelectedPaymentMethod(PaymentMethod.BANK_TRANSFER);
    var handleRes = reservationApiV2Controller.confirmOverview(reservationId, "en", paymentForm, new BeanPropertyBindingResult(paymentForm, "paymentForm"), new MockHttpServletRequest(), null);
    assertEquals(HttpStatus.OK, handleRes.getStatusCode());
    return reservationId;
}
Also used : ContactAndTicketsForm(alfio.controller.form.ContactAndTicketsForm) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) PaymentForm(alfio.controller.form.PaymentForm) ReservationForm(alfio.controller.form.ReservationForm) UpdateTicketOwnerForm(alfio.controller.form.UpdateTicketOwnerForm) TicketReservationModification(alfio.model.modification.TicketReservationModification) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse)

Example 97 with BeanPropertyBindingResult

use of org.springframework.validation.BeanPropertyBindingResult in project alf.io by alfio-event.

the class BaseReservationFlowTest method ensureConfiguration.

private void ensureConfiguration(ReservationFlowContext context) {
    IntegrationTestUtil.ensureMinimalConfiguration(configurationRepository);
    // promo code at event level
    eventManager.addPromoCode(PROMO_CODE, context.event.getId(), null, ZonedDateTime.now(clockProvider.getClock()).minusDays(2), context.event.getEnd().plusDays(2), 10, PromoCodeDiscount.DiscountType.PERCENTAGE, null, 3, "description", "test@test.ch", PromoCodeDiscount.CodeType.DISCOUNT, null);
    hiddenCategoryId = ticketCategoryRepository.findAllTicketCategories(context.event.getId()).stream().filter(TicketCategory::isAccessRestricted).collect(Collectors.toList()).get(0).getId();
    eventManager.addPromoCode(HIDDEN_CODE, context.event.getId(), null, ZonedDateTime.now(clockProvider.getClock()).minusDays(2), context.event.getEnd().plusDays(2), 0, PromoCodeDiscount.DiscountType.NONE, null, null, "hidden", "test@test.ch", PromoCodeDiscount.CodeType.ACCESS, hiddenCategoryId);
    // add additional fields before and after, with one mandatory
    var af = new EventModification.AdditionalField(-1, true, "field1", "text", true, false, null, null, null, Map.of("en", new EventModification.Description("field en", "", null)), null, null);
    eventManager.addAdditionalField(context.event, af);
    var afId = ticketFieldRepository.findAdditionalFieldsForEvent(context.event.getId()).get(0).getId();
    ticketFieldRepository.updateFieldOrder(afId, -1);
    var af2 = new EventModification.AdditionalField(1, true, "field2", "text", false, false, null, null, null, Map.of("en", new EventModification.Description("field2 en", "", null)), null, null);
    eventManager.addAdditionalField(context.event, af2);
    // 
    // add additional service
    var addServ = new EventModification.AdditionalService(null, new BigDecimal("40.00"), true, 0, 1, 1, new DateTimeModification(ZonedDateTime.now(clockProvider.getClock()).minusDays(2).toLocalDate(), ZonedDateTime.now(clockProvider.getClock()).minusDays(2).toLocalTime()), new DateTimeModification(context.event.getEnd().plusDays(2).toLocalDate(), context.event.getEnd().plusDays(2).toLocalTime()), context.event.getVat(), AdditionalService.VatType.INHERITED, null, Collections.singletonList(new EventModification.AdditionalServiceText(null, "en", "additional title", AdditionalServiceText.TextType.TITLE)), Collections.singletonList(new EventModification.AdditionalServiceText(null, "en", "additional desc", AdditionalServiceText.TextType.DESCRIPTION)), AdditionalService.AdditionalServiceType.SUPPLEMENT, AdditionalService.SupplementPolicy.OPTIONAL_MAX_AMOUNT_PER_TICKET);
    var addServRes = additionalServiceApiController.insert(context.event.getId(), addServ, new BeanPropertyBindingResult(addServ, "additionalService"));
    assertNotNull(addServRes.getBody());
    additionalServiceId = addServRes.getBody().getId();
    // 
    var af3 = new EventModification.AdditionalField(2, true, "field3", "text", true, false, null, null, null, Map.of("en", new EventModification.Description("field3 en", "", null)), addServRes.getBody(), null);
    eventManager.addAdditionalField(context.event, af3);
    // enable reservation list and pre sales
    configurationRepository.insertEventLevel(context.event.getOrganizationId(), context.event.getId(), ConfigurationKeys.ENABLE_WAITING_QUEUE.getValue(), "true", "");
    configurationRepository.insertEventLevel(context.event.getOrganizationId(), context.event.getId(), ConfigurationKeys.ENABLE_PRE_REGISTRATION.getValue(), "true", "");
    // 
    specialPriceTokenGenerator.generatePendingCodes();
}
Also used : BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) BigDecimal(java.math.BigDecimal)

Example 98 with BeanPropertyBindingResult

use of org.springframework.validation.BeanPropertyBindingResult in project alf.io by alfio-event.

the class BaseReservationFlowTest method testAddSubscription.

protected void testAddSubscription(ReservationFlowContext context, int numberOfTickets) {
    var form = new ReservationForm();
    var ticketReservation = new TicketReservationModification();
    ticketReservation.setQuantity(numberOfTickets);
    var categoriesResponse = eventApiV2Controller.getTicketCategories(context.event.getShortName(), null);
    assertTrue(categoriesResponse.getStatusCode().is2xxSuccessful());
    assertNotNull(categoriesResponse.getBody());
    ticketReservation.setTicketCategoryId(categoriesResponse.getBody().getTicketCategories().get(0).getId());
    form.setReservation(Collections.singletonList(ticketReservation));
    var res = eventApiV2Controller.reserveTickets(context.event.getShortName(), "en", form, new BeanPropertyBindingResult(form, "reservation"), new ServletWebRequest(new MockHttpServletRequest(), new MockHttpServletResponse()), null);
    assertEquals(HttpStatus.OK, res.getStatusCode());
    var resBody = res.getBody();
    assertNotNull(resBody);
    assertTrue(resBody.isSuccess());
    assertEquals(0, resBody.getErrorCount());
    var reservationId = resBody.getValue();
    checkStatus(reservationId, HttpStatus.OK, false, TicketReservation.TicketReservationStatus.PENDING, context);
    var resInfoRes = reservationApiV2Controller.getReservationInfo(reservationId, context.getPublicUser());
    assertEquals(HttpStatus.OK, resInfoRes.getStatusCode());
    var reservation = resInfoRes.getBody();
    assertNotNull(reservation);
    assertEquals(reservationId, reservation.getId());
    assertEquals(1, reservation.getTicketsByCategory().size());
    assertEquals(numberOfTickets, reservation.getTicketsByCategory().get(0).getTickets().size());
    var contactForm = new ContactAndTicketsForm();
    // move to overview status
    contactForm = new ContactAndTicketsForm();
    contactForm.setEmail("test@test.com");
    contactForm.setBillingAddress("my billing address");
    contactForm.setFirstName("full");
    contactForm.setLastName("name");
    var tickets = reservation.getTicketsByCategory().get(0).getTickets().stream().map(t -> {
        var ticketForm = new UpdateTicketOwnerForm();
        ticketForm.setFirstName("ticketfull");
        ticketForm.setLastName("ticketname");
        ticketForm.setEmail("tickettest@test.com");
        ticketForm.setAdditional(Collections.singletonMap("field1", Collections.singletonList("value")));
        return Map.entry(t.getUuid(), ticketForm);
    }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    contactForm.setTickets(tickets);
    var overviewRes = reservationApiV2Controller.validateToOverview(reservationId, "en", false, contactForm, new BeanPropertyBindingResult(contactForm, "paymentForm"), context.getPublicAuthentication());
    assertEquals(HttpStatus.OK, overviewRes.getStatusCode());
    checkStatus(reservationId, HttpStatus.OK, true, TicketReservation.TicketReservationStatus.PENDING, context);
    var reservationCodeForm = new ReservationCodeForm();
    reservationCodeForm.setCode(Objects.requireNonNullElseGet(context.subscriptionPin, context.subscriptionId::toString));
    reservationCodeForm.setType(ReservationCodeForm.ReservationCodeType.SUBSCRIPTION);
    var bindingResult = new BeanPropertyBindingResult(reservationCodeForm, "reservationCodeForm");
    var codeApplicationResult = reservationApiV2Controller.applyCode(reservationId, reservationCodeForm, bindingResult);
    assertTrue(codeApplicationResult.getStatusCode().is2xxSuccessful());
    var codeApplicationResponse = codeApplicationResult.getBody();
    assertNotNull(codeApplicationResponse);
    assertTrue(codeApplicationResponse.isSuccess());
    assertFalse(bindingResult.hasErrors(), bindingResult::toString);
    assertEquals(true, codeApplicationResponse.getValue());
    // reload reservation, and assert it is now free of charge
    resInfoRes = reservationApiV2Controller.getReservationInfo(reservationId, context.getPublicUser());
    assertEquals(HttpStatus.OK, resInfoRes.getStatusCode());
    reservation = resInfoRes.getBody();
    assertNotNull(reservation);
    assertTrue(reservation.getOrderSummary().isFree());
    // assert that there is a row in the summary for the subscription
    var summaryRowSubscription = reservation.getOrderSummary().getSummary().stream().filter(r -> r.getType() == SummaryRow.SummaryType.APPLIED_SUBSCRIPTION).findFirst();
    assertTrue(summaryRowSubscription.isPresent());
    assertEquals(numberOfTickets, summaryRowSubscription.get().getAmount());
    // proceed with the confirmation
    var paymentForm = new PaymentForm();
    paymentForm.setPrivacyPolicyAccepted(true);
    paymentForm.setTermAndConditionsAccepted(true);
    paymentForm.setSelectedPaymentMethod(PaymentMethod.NONE);
    var propertyBindingResult = new BeanPropertyBindingResult(paymentForm, "paymentForm");
    var handleRes = reservationApiV2Controller.confirmOverview(reservationId, "en", paymentForm, propertyBindingResult, new MockHttpServletRequest(), null);
    log.warn("received {}", propertyBindingResult);
    assertEquals(HttpStatus.OK, handleRes.getStatusCode());
    checkStatus(reservationId, HttpStatus.OK, true, TicketReservation.TicketReservationStatus.COMPLETE, context);
    // trigger email processing
    triggerEmailProcessingAndCheck(context, reservationId);
}
Also used : ScanAudit(alfio.model.audit.ScanAudit) alfio.repository(alfio.repository) UsersApiController(alfio.controller.api.admin.UsersApiController) alfio.manager(alfio.manager) PaymentProxy(alfio.model.transaction.PaymentProxy) Parser(ch.digitalfondue.jfiveparse.Parser) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) ZonedDateTime(java.time.ZonedDateTime) RequiredArgsConstructor(lombok.RequiredArgsConstructor) NamedParameterJdbcTemplate(org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate) TicketAndCheckInResult(alfio.manager.support.TicketAndCheckInResult) Element(ch.digitalfondue.jfiveparse.Element) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) BigDecimal(java.math.BigDecimal) ByteArrayInputStream(java.io.ByteArrayInputStream) ImageIO(javax.imageio.ImageIO) ReservationApiV2Controller(alfio.controller.api.v2.user.ReservationApiV2Controller) QRCodeReader(com.google.zxing.qrcode.QRCodeReader) ExtensionEvent(alfio.manager.support.extension.ExtensionEvent) TypeReference(com.fasterxml.jackson.core.type.TypeReference) HybridBinarizer(com.google.zxing.common.HybridBinarizer) DecodeHintType(com.google.zxing.DecodeHintType) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpSession(org.springframework.mock.web.MockHttpSession) alfio.controller.form(alfio.controller.form) AdditionalServiceApiController(alfio.controller.api.admin.AdditionalServiceApiController) Selector(ch.digitalfondue.jfiveparse.Selector) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ConfigurationRepository(alfio.repository.system.ConfigurationRepository) IOUtils(org.apache.commons.io.IOUtils) CheckInStatus(alfio.manager.support.CheckInStatus) Principal(java.security.Principal) alfio.model(alfio.model) UserRepository(alfio.repository.user.UserRepository) CheckInApiController(alfio.controller.api.admin.CheckInApiController) alfio.model.modification(alfio.model.modification) Mockito.mock(org.mockito.Mockito.mock) java.util(java.util) TicketApiV2Controller(alfio.controller.api.v2.user.TicketApiV2Controller) ScanAuditRepository(alfio.repository.audit.ScanAuditRepository) CSVReader(com.opencsv.CSVReader) LocalDateTime(java.time.LocalDateTime) BasicEventInfo(alfio.controller.api.v2.model.BasicEventInfo) PurchaseContextType(alfio.model.PurchaseContext.PurchaseContextType) Supplier(java.util.function.Supplier) alfio.util(alfio.util) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) IndexController(alfio.controller.IndexController) EventCode(alfio.controller.api.v2.model.EventCode) Language(alfio.controller.api.v2.model.Language) Objects.requireNonNull(java.util.Objects.requireNonNull) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) TranslationsApiController(alfio.controller.api.v2.TranslationsApiController) EventApiController(alfio.controller.api.admin.EventApiController) ReservationAccessDenied(alfio.controller.api.v2.user.support.ReservationAccessDenied) PaymentMethod(alfio.model.transaction.PaymentMethod) User(alfio.model.user.User) AttendeeApiController(alfio.controller.api.v1.AttendeeApiController) BufferedImageLuminanceSource(com.google.zxing.client.j2se.BufferedImageLuminanceSource) IntegrationTestUtil(alfio.test.util.IntegrationTestUtil) InputStreamReader(java.io.InputStreamReader) InfoApiController(alfio.controller.api.v2.InfoApiController) Extension(alfio.extension.Extension) Mockito(org.mockito.Mockito) HttpStatus(org.springframework.http.HttpStatus) ExtensionService(alfio.extension.ExtensionService) EventApiV2Controller(alfio.controller.api.v2.user.EventApiV2Controller) StringReader(java.io.StringReader) Log4j2(lombok.extern.log4j.Log4j2) Assertions(org.junit.jupiter.api.Assertions) BinaryBitmap(com.google.zxing.BinaryBitmap) DigestUtils(org.apache.commons.codec.digest.DigestUtils) ConfigurationKeys(alfio.model.system.ConfigurationKeys) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse)

Example 99 with BeanPropertyBindingResult

use of org.springframework.validation.BeanPropertyBindingResult in project Asqatasun by Asqatasun.

the class UserManagementControllerTest method testSubmitEditUserForm.

/**
 * Test of submitEditUserForm method, of class UserManagementController.
 */
@Test
public void testSubmitEditUserForm() throws Exception {
    setUpMockRoleDataService();
    setUpMockUserDataService(false, true, false);
    setUpMockAuthenticationContext();
    // Finally the form is conform and the admin page is returned
    CreateUserCommand createUserCommand = createUserCommandFactory.getNewCreateUserCommand();
    createUserCommand.setEmail("user@test.com");
    createUserCommand.setLastName("newName");
    createUserCommand.setFirstName("newFirstName");
    createUserCommand.setPhoneNumber("0102030405");
    createUserCommand.setActivated(false);
    createUserCommand.setAdmin(true);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.getSession().setAttribute(TgolKeyStore.USER_ID_KEY, 5L);
    BindingResult bindingResult = new BeanPropertyBindingResult(createUserCommand, "createUserCommand");
    Model model = new ExtendedModelMap();
    String result = instance.submitEditUserForm(createUserCommand, bindingResult, request, model);
    assertEquals(TgolKeyStore.ADMIN_VIEW_NAME, result);
    assertFalse(bindingResult.hasErrors());
    assertTrue(bindingResult.getFieldErrors().isEmpty());
    assertEquals(2, model.asMap().size());
    assertEquals("user@test.com", model.asMap().get(TgolKeyStore.UPDATED_USER_NAME_KEY));
    assertTrue(((List<User>) model.asMap().get(TgolKeyStore.USER_LIST_KEY)).isEmpty());
}
Also used : BindingResult(org.springframework.validation.BindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) ExtendedModelMap(org.springframework.ui.ExtendedModelMap) User(org.asqatasun.entity.user.User) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Model(org.springframework.ui.Model) CreateUserCommand(org.asqatasun.webapp.command.CreateUserCommand) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 100 with BeanPropertyBindingResult

use of org.springframework.validation.BeanPropertyBindingResult in project chassis by Kixeye.

the class RawWebSocketMessage method deserialize.

/**
 * Deserializes the given message.
 *
 * @param action
 * @return
 * @throws Exception
 */
public T deserialize(WebSocketAction action) throws Exception {
    // first deserialize
    T message = null;
    if (messageClass != null) {
        message = serDe.deserialize(new ByteBufferBackedInputStream(rawData), messageClass);
    }
    // then validate
    if (message != null && action.shouldValidatePayload()) {
        SpringValidatorAdapter validatorAdapter = new SpringValidatorAdapter(messageValidator);
        BeanPropertyBindingResult result = new BeanPropertyBindingResult(message, messageClass.getName());
        validatorAdapter.validate(message, result);
        if (result.hasErrors()) {
            throw new MethodArgumentNotValidException(new MethodParameter(action.getMethod(), action.getPayloadParameterIndex()), result);
        }
    }
    return message;
}
Also used : BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) SpringValidatorAdapter(org.springframework.validation.beanvalidation.SpringValidatorAdapter) MethodParameter(org.springframework.core.MethodParameter) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) ByteBufferBackedInputStream(com.fasterxml.jackson.databind.util.ByteBufferBackedInputStream)

Aggregations

BeanPropertyBindingResult (org.springframework.validation.BeanPropertyBindingResult)153 Test (org.junit.jupiter.api.Test)71 RestServerError (org.entando.entando.aps.system.exception.RestServerError)28 Errors (org.springframework.validation.Errors)24 ApsSystemException (com.agiletec.aps.system.exception.ApsSystemException)23 BindingResult (org.springframework.validation.BindingResult)23 ValidationGenericException (org.entando.entando.web.common.exceptions.ValidationGenericException)21 StringReader (java.io.StringReader)20 TestBean (org.springframework.beans.testfixture.beans.TestBean)18 List (java.util.List)17 Document (org.dom4j.Document)17 Element (org.dom4j.Element)17 SAXReader (org.dom4j.io.SAXReader)17 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)15 ResourceNotFoundException (org.entando.entando.aps.system.exception.ResourceNotFoundException)14 ArrayList (java.util.ArrayList)13 ValidationConflictException (org.entando.entando.web.common.exceptions.ValidationConflictException)13 FieldError (org.springframework.validation.FieldError)12 PropertyEditorSupport (java.beans.PropertyEditorSupport)10 Test (org.junit.Test)9