Search in sources :

Example 86 with BeanPropertyBindingResult

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

the class ReverseChargeManagerIntegrationTest method createReservation.

private ReservationInfo createReservation(String id, boolean requestInvoice) {
    var categories = ticketCategoryRepository.findAllTicketCategories(event.getId());
    var form = new ReservationForm();
    var first = new TicketReservationModification();
    first.setQuantity(2);
    first.setTicketCategoryId(categories.get(0).getId());
    var second = new TicketReservationModification();
    second.setQuantity(2);
    second.setTicketCategoryId(categories.get(1).getId());
    form.setReservation(List.of(first, second));
    var reservationId = id;
    if (reservationId == null) {
        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());
        reservationId = resBody.getValue();
    }
    // enter billing data
    var contactForm = new ContactAndTicketsForm();
    // move to overview status
    contactForm = new ContactAndTicketsForm();
    contactForm.setFirstName("First");
    contactForm.setLastName("Last");
    contactForm.setEmail("test@test.com");
    contactForm.setAddCompanyBillingDetails(requestInvoice);
    contactForm.setInvoiceRequested(requestInvoice);
    if (requestInvoice) {
        contactForm.setBillingAddressLine1("Piazza della Riforma");
        contactForm.setBillingAddressCity("Lugano");
        contactForm.setBillingAddressZip("6900");
        contactForm.setVatCountryCode("CH");
        contactForm.setVatNr("123456789");
    }
    var tickets = ticketRepository.findTicketsInReservation(reservationId).stream().map(t -> {
        var ticketForm = new UpdateTicketOwnerForm();
        ticketForm.setFirstName("ticketfull");
        ticketForm.setLastName("ticketname");
        ticketForm.setEmail("tickettest@test.com");
        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"), null);
    assertEquals(HttpStatus.OK, overviewRes.getStatusCode());
    var resInfoRes = reservationApiV2Controller.getReservationInfo(reservationId, null);
    assertEquals(HttpStatus.OK, resInfoRes.getStatusCode());
    var reservation = resInfoRes.getBody();
    assertNotNull(reservation);
    assertFalse(reservation.getOrderSummary().isFree());
    return reservation;
}
Also used : ContactAndTicketsForm(alfio.controller.form.ContactAndTicketsForm) ReservationForm(alfio.controller.form.ReservationForm) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) TicketReservationModification(alfio.model.modification.TicketReservationModification) TicketCategoryRepository(alfio.repository.TicketCategoryRepository) AlfioMetadata(alfio.model.metadata.AlfioMetadata) Autowired(org.springframework.beans.factory.annotation.Autowired) ActiveProfiles(org.springframework.test.context.ActiveProfiles) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) BigDecimal(java.math.BigDecimal) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) LocalTime(java.time.LocalTime) ReservationApiV2Controller(alfio.controller.api.v2.user.ReservationApiV2Controller) OrganizationRepository(alfio.repository.user.OrganizationRepository) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) EventRepository(alfio.repository.EventRepository) Collectors(java.util.stream.Collectors) ConfigurationRepository(alfio.repository.system.ConfigurationRepository) Test(org.junit.jupiter.api.Test) List(java.util.List) Initializer(alfio.config.Initializer) ContactAndTicketsForm(alfio.controller.form.ContactAndTicketsForm) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) LocalDate(java.time.LocalDate) Configuration(alfio.model.system.Configuration) DataSourceConfiguration(alfio.config.DataSourceConfiguration) ClockProvider(alfio.util.ClockProvider) ConfigurationManager(alfio.manager.system.ConfigurationManager) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) DateTimeModification(alfio.model.modification.DateTimeModification) SummaryRow(alfio.model.SummaryRow) ControllerConfiguration(alfio.controller.api.ControllerConfiguration) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) ReservationInfo(alfio.controller.api.v2.model.ReservationInfo) BaseIntegrationTest(alfio.util.BaseIntegrationTest) TicketCategoryModification(alfio.model.modification.TicketCategoryModification) TicketRepository(alfio.repository.TicketRepository) UpdateTicketOwnerForm(alfio.controller.form.UpdateTicketOwnerForm) IntegrationTestUtil(alfio.test.util.IntegrationTestUtil) HttpStatus(org.springframework.http.HttpStatus) TicketCategory(alfio.model.TicketCategory) EventApiV2Controller(alfio.controller.api.v2.user.EventApiV2Controller) UserManager(alfio.manager.user.UserManager) ContextConfiguration(org.springframework.test.context.ContextConfiguration) Assertions(org.junit.jupiter.api.Assertions) Event(alfio.model.Event) TestConfiguration(alfio.TestConfiguration) ConfigurationKeys(alfio.model.system.ConfigurationKeys) Transactional(org.springframework.transaction.annotation.Transactional) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ReservationForm(alfio.controller.form.ReservationForm) UpdateTicketOwnerForm(alfio.controller.form.UpdateTicketOwnerForm) TicketReservationModification(alfio.model.modification.TicketReservationModification) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) Map(java.util.Map) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse)

Example 87 with BeanPropertyBindingResult

use of org.springframework.validation.BeanPropertyBindingResult in project grails-core by grails.

the class DataBindingUtils method bindObjectToDomainInstance.

/**
     * Binds the given source object to the given target object performing type conversion if necessary
     *
     * @param domain The GrailsDomainClass instance
     * @param object The object to bind to
     * @param source The source object
     * @param include The list of properties to include
     * @param exclude The list of properties to exclude
     * @param filter The prefix to filter by
     *
     * @see grails.core.GrailsDomainClass
     *
     * @return A BindingResult or null if it wasn't successful
     */
@SuppressWarnings("unchecked")
public static BindingResult bindObjectToDomainInstance(GrailsDomainClass domain, Object object, Object source, List include, List exclude, String filter) {
    BindingResult bindingResult = null;
    GrailsApplication grailsApplication = null;
    if (domain != null) {
        grailsApplication = domain.getApplication();
    }
    if (grailsApplication == null) {
        grailsApplication = Holders.findApplication();
    }
    try {
        final DataBindingSource bindingSource = createDataBindingSource(grailsApplication, object.getClass(), source);
        final DataBinder grailsWebDataBinder = getGrailsWebDataBinder(grailsApplication);
        grailsWebDataBinder.bind(object, bindingSource, filter, include, exclude);
    } catch (InvalidRequestBodyException e) {
        String messageCode = "invalidRequestBody";
        Class objectType = object.getClass();
        String defaultMessage = "An error occurred parsing the body of the request";
        String[] codes = getMessageCodes(messageCode, objectType);
        bindingResult = new BeanPropertyBindingResult(object, objectType.getName());
        bindingResult.addError(new ObjectError(bindingResult.getObjectName(), codes, null, defaultMessage));
    } catch (Exception e) {
        bindingResult = new BeanPropertyBindingResult(object, object.getClass().getName());
        bindingResult.addError(new ObjectError(bindingResult.getObjectName(), e.getMessage()));
    }
    if (domain != null && bindingResult != null) {
        BindingResult newResult = new ValidationErrors(object);
        for (Object error : bindingResult.getAllErrors()) {
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                final boolean isBlank = BLANK.equals(fieldError.getRejectedValue());
                if (!isBlank) {
                    newResult.addError(fieldError);
                } else if (domain.hasPersistentProperty(fieldError.getField())) {
                    final boolean isOptional = domain.getPropertyByName(fieldError.getField()).isOptional();
                    if (!isOptional) {
                        newResult.addError(fieldError);
                    }
                } else {
                    newResult.addError(fieldError);
                }
            } else {
                newResult.addError((ObjectError) error);
            }
        }
        bindingResult = newResult;
    }
    MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(object.getClass());
    if (mc.hasProperty(object, "errors") != null && bindingResult != null) {
        ValidationErrors errors = new ValidationErrors(object);
        errors.addAllErrors(bindingResult);
        mc.setProperty(object, "errors", errors);
    }
    return bindingResult;
}
Also used : BindingResult(org.springframework.validation.BindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) ValidationErrors(grails.validation.ValidationErrors) FieldError(org.springframework.validation.FieldError) CollectionDataBindingSource(grails.databinding.CollectionDataBindingSource) DataBindingSource(grails.databinding.DataBindingSource) InvalidRequestBodyException(org.grails.web.databinding.bindingsource.InvalidRequestBodyException) ObjectError(org.springframework.validation.ObjectError) MetaClass(groovy.lang.MetaClass) GrailsApplication(grails.core.GrailsApplication) InvalidRequestBodyException(org.grails.web.databinding.bindingsource.InvalidRequestBodyException) GrailsDomainClass(grails.core.GrailsDomainClass) MetaClass(groovy.lang.MetaClass) DataBinder(grails.databinding.DataBinder) GrailsWebDataBinder(grails.web.databinding.GrailsWebDataBinder)

Example 88 with BeanPropertyBindingResult

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

the class EventController method makeSimpleReservation.

private String makeSimpleReservation(String eventName, ServletWebRequest request, RedirectAttributes redirectAttributes, Locale locale, String trimmedCode, Event event, int ticketCategoryId) {
    ReservationForm form = new ReservationForm();
    form.setPromoCode(trimmedCode);
    TicketReservationModification reservation = new TicketReservationModification();
    reservation.setAmount(1);
    reservation.setTicketCategoryId(ticketCategoryId);
    form.setReservation(Collections.singletonList(reservation));
    return validateAndReserve(eventName, form, new BeanPropertyBindingResult(form, "reservationForm"), request, redirectAttributes, locale, event);
}
Also used : BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) ReservationForm(alfio.controller.form.ReservationForm) TicketReservationModification(alfio.model.modification.TicketReservationModification)

Example 89 with BeanPropertyBindingResult

use of org.springframework.validation.BeanPropertyBindingResult in project Gemma by PavlidisLab.

the class PubMedQueryControllerTest method testOnSubmitInvalidValue.

@Test
public final void testOnSubmitInvalidValue() throws Exception {
    MockHttpServletRequest request = this.newPost("/pubMedSearch.html");
    ModelAndView mv = controller.onSubmit(request, new PubMedSearchCommand("bad idea"), new BeanPropertyBindingResult(new PubMedSearchCommand("bad idea"), "searchCriteria"), new SimpleSessionStatus());
    Errors errors = (Errors) mv.getModel().get(BindingResult.MODEL_KEY_PREFIX + "searchCriteria");
    assertTrue("Expected an error", errors != null);
    assertEquals("bibRefSearch", mv.getViewName());
}
Also used : Errors(org.springframework.validation.Errors) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ModelAndView(org.springframework.web.servlet.ModelAndView) SimpleSessionStatus(org.springframework.web.bind.support.SimpleSessionStatus) Test(org.junit.Test) BaseSpringWebTest(ubic.gemma.web.util.BaseSpringWebTest)

Example 90 with BeanPropertyBindingResult

use of org.springframework.validation.BeanPropertyBindingResult in project Gemma by PavlidisLab.

the class PubMedQueryControllerTest method testOnSubmitAlreadyExists.

@Test
public final void testOnSubmitAlreadyExists() throws Exception {
    // put it in the system.
    this.getTestPersistentBibliographicReference("12299");
    MockHttpServletRequest request = this.newPost("/pubMedSearch.html");
    ModelAndView mv = controller.onSubmit(request, new PubMedSearchCommand("12299"), new BeanPropertyBindingResult(new PubMedSearchCommand("12299"), "searchCriteria"), new SimpleSessionStatus());
    Errors errors = (Errors) mv.getModel().get(BindingResult.MODEL_KEY_PREFIX + "searchCriteria");
    assertNull("Errors in model: " + errors, errors);
    assertNotNull(mv.getModel().get("bibliographicReference"));
    assertNotNull(request.getSession().getAttribute("messages"));
    assertEquals("bibRefView", mv.getViewName());
}
Also used : Errors(org.springframework.validation.Errors) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ModelAndView(org.springframework.web.servlet.ModelAndView) SimpleSessionStatus(org.springframework.web.bind.support.SimpleSessionStatus) Test(org.junit.Test) BaseSpringWebTest(ubic.gemma.web.util.BaseSpringWebTest)

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