Search in sources :

Example 1 with MessageSourceResolvable

use of org.springframework.context.MessageSourceResolvable in project alf.io by alfio-event.

the class ReservationController method handleReservation.

@RequestMapping(value = "/event/{eventName}/reservation/{reservationId}", method = RequestMethod.POST)
public String handleReservation(@PathVariable("eventName") String eventName, @PathVariable("reservationId") String reservationId, PaymentForm paymentForm, BindingResult bindingResult, Model model, HttpServletRequest request, Locale locale, RedirectAttributes redirectAttributes) {
    Optional<Event> eventOptional = eventRepository.findOptionalByShortName(eventName);
    if (!eventOptional.isPresent()) {
        return "redirect:/";
    }
    Event event = eventOptional.get();
    Optional<TicketReservation> ticketReservation = ticketReservationManager.findById(reservationId);
    if (!ticketReservation.isPresent()) {
        return redirectReservation(ticketReservation, eventName, reservationId);
    }
    if (paymentForm.shouldCancelReservation()) {
        ticketReservationManager.cancelPendingReservation(reservationId, false);
        SessionUtil.removeSpecialPriceData(request);
        return "redirect:/event/" + eventName + "/";
    }
    if (!ticketReservation.get().getValidity().after(new Date())) {
        bindingResult.reject(ErrorsCode.STEP_2_ORDER_EXPIRED);
    }
    final TotalPrice reservationCost = ticketReservationManager.totalReservationCostWithVAT(reservationId);
    if (isCaptchaInvalid(reservationCost.getPriceWithVAT(), paymentForm.getPaymentMethod(), request, event)) {
        log.debug("captcha validation failed.");
        bindingResult.reject(ErrorsCode.STEP_2_CAPTCHA_VALIDATION_FAILED);
    }
    if (paymentForm.getPaymentMethod() != PaymentProxy.PAYPAL || !paymentForm.hasPaypalTokens()) {
        if (!paymentForm.isPostponeAssignment() && !ticketRepository.checkTicketUUIDs(reservationId, paymentForm.getTickets().keySet())) {
            bindingResult.reject(ErrorsCode.STEP_2_MISSING_ATTENDEE_DATA);
        }
        paymentForm.validate(bindingResult, reservationCost, event, ticketFieldRepository.findAdditionalFieldsForEvent(event.getId()));
        if (bindingResult.hasErrors()) {
            SessionUtil.addToFlash(bindingResult, redirectAttributes);
            return redirectReservation(ticketReservation, eventName, reservationId);
        }
    }
    CustomerName customerName = new CustomerName(paymentForm.getFullName(), paymentForm.getFirstName(), paymentForm.getLastName(), event);
    // handle paypal redirect!
    if (paymentForm.getPaymentMethod() == PaymentProxy.PAYPAL && !paymentForm.hasPaypalTokens()) {
        OrderSummary orderSummary = ticketReservationManager.orderSummaryForReservationId(reservationId, event, locale);
        try {
            String checkoutUrl = paymentManager.createPayPalCheckoutRequest(event, reservationId, orderSummary, customerName, paymentForm.getEmail(), paymentForm.getBillingAddress(), locale, paymentForm.isPostponeAssignment(), paymentForm.isInvoiceRequested());
            assignTickets(eventName, reservationId, paymentForm, bindingResult, request, true);
            return "redirect:" + checkoutUrl;
        } catch (Exception e) {
            bindingResult.reject(ErrorsCode.STEP_2_PAYMENT_REQUEST_CREATION);
            SessionUtil.addToFlash(bindingResult, redirectAttributes);
            return redirectReservation(ticketReservation, eventName, reservationId);
        }
    }
    // handle mollie redirect
    if (paymentForm.getPaymentMethod() == PaymentProxy.MOLLIE) {
        OrderSummary orderSummary = ticketReservationManager.orderSummaryForReservationId(reservationId, event, locale);
        try {
            String checkoutUrl = mollieManager.createCheckoutRequest(event, reservationId, orderSummary, customerName, paymentForm.getEmail(), paymentForm.getBillingAddress(), locale, paymentForm.isInvoiceRequested(), paymentForm.getVatCountryCode(), paymentForm.getVatNr(), ticketReservation.get().getVatStatus());
            assignTickets(eventName, reservationId, paymentForm, bindingResult, request, true);
            return "redirect:" + checkoutUrl;
        } catch (Exception e) {
            bindingResult.reject(ErrorsCode.STEP_2_PAYMENT_REQUEST_CREATION);
            SessionUtil.addToFlash(bindingResult, redirectAttributes);
            return redirectReservation(ticketReservation, eventName, reservationId);
        }
    }
    // 
    final PaymentResult status = ticketReservationManager.confirm(paymentForm.getToken(), paymentForm.getPaypalPayerID(), event, reservationId, paymentForm.getEmail(), customerName, locale, paymentForm.getBillingAddress(), reservationCost, SessionUtil.retrieveSpecialPriceSessionId(request), Optional.ofNullable(paymentForm.getPaymentMethod()), paymentForm.isInvoiceRequested(), paymentForm.getVatCountryCode(), paymentForm.getVatNr(), ticketReservation.get().getVatStatus());
    if (!status.isSuccessful()) {
        String errorMessageCode = status.getErrorCode().get();
        MessageSourceResolvable message = new DefaultMessageSourceResolvable(new String[] { errorMessageCode, StripeManager.STRIPE_UNEXPECTED });
        bindingResult.reject(ErrorsCode.STEP_2_PAYMENT_PROCESSING_ERROR, new Object[] { messageSource.getMessage(message, locale) }, null);
        SessionUtil.addToFlash(bindingResult, redirectAttributes);
        return redirectReservation(ticketReservation, eventName, reservationId);
    }
    // 
    TicketReservation reservation = ticketReservationManager.findById(reservationId).orElseThrow(IllegalStateException::new);
    sendReservationCompleteEmail(request, event, reservation);
    sendReservationCompleteEmailToOrganizer(request, event, reservation);
    if (paymentForm.getPaymentMethod() != PaymentProxy.PAYPAL) {
        assignTickets(eventName, reservationId, paymentForm, bindingResult, request, paymentForm.getPaymentMethod() == PaymentProxy.OFFLINE);
    }
    return "redirect:/event/" + eventName + "/reservation/" + reservationId + "/success";
}
Also used : PaymentResult(alfio.manager.support.PaymentResult) DefaultMessageSourceResolvable(org.springframework.context.support.DefaultMessageSourceResolvable) DefaultMessageSourceResolvable(org.springframework.context.support.DefaultMessageSourceResolvable) MessageSourceResolvable(org.springframework.context.MessageSourceResolvable) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with MessageSourceResolvable

use of org.springframework.context.MessageSourceResolvable in project openmrs-core by openmrs.

the class MessageSourceServiceTest method getMessage_shouldReturnTheLastErrorCodeIfnoLocalizationIsFound.

/**
 * MessageSourceServiceImpl.getMessage()should return last error code if no localization found
 *
 * @see MessageSourceServiceImpl#getMessage(MessageSourceResolvable resolvable, Locale locale)
 */
@Test
public void getMessage_shouldReturnTheLastErrorCodeIfnoLocalizationIsFound() {
    MapBindingResult errors = new MapBindingResult(new HashMap<String, Object>(), "request");
    errors.rejectValue("myField", "myErrorCode");
    MessageSourceResolvable fieldError = errors.getFieldError("myField");
    Assert.assertEquals(3, fieldError.getCodes().length);
    Assert.assertEquals("myErrorCode.request.myField", fieldError.getCodes()[0]);
    Assert.assertEquals("myErrorCode.myField", fieldError.getCodes()[1]);
    Assert.assertEquals("myErrorCode", fieldError.getCodes()[2]);
    Assert.assertEquals("myErrorCode", Context.getMessageSourceService().getMessage(fieldError, Context.getLocale()));
}
Also used : MessageSourceResolvable(org.springframework.context.MessageSourceResolvable) MapBindingResult(org.springframework.validation.MapBindingResult) Test(org.junit.Test) BaseContextSensitiveTest(org.openmrs.test.BaseContextSensitiveTest)

Example 3 with MessageSourceResolvable

use of org.springframework.context.MessageSourceResolvable in project spring-framework by spring-projects.

the class ThemeTagTests method requestContext.

@Test
@SuppressWarnings("rawtypes")
void requestContext() throws ServletException {
    PageContext pc = createPageContext();
    RequestContext rc = new RequestContext((HttpServletRequest) pc.getRequest());
    assertThat(rc.getThemeMessage("themetest")).isEqualTo("theme test message");
    assertThat(rc.getThemeMessage("themetest", (String[]) null)).isEqualTo("theme test message");
    assertThat(rc.getThemeMessage("themetest", "default")).isEqualTo("theme test message");
    assertThat(rc.getThemeMessage("themetest", (Object[]) null, "default")).isEqualTo("theme test message");
    assertThat(rc.getThemeMessage("themetestArgs", new String[] { "arg1" })).isEqualTo("theme test message arg1");
    assertThat(rc.getThemeMessage("themetestArgs", Arrays.asList(new String[] { "arg1" }))).isEqualTo("theme test message arg1");
    assertThat(rc.getThemeMessage("themetesta", "default")).isEqualTo("default");
    assertThat(rc.getThemeMessage("themetesta", (List) null, "default")).isEqualTo("default");
    MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(new String[] { "themetest" });
    assertThat(rc.getThemeMessage(resolvable)).isEqualTo("theme test message");
}
Also used : DefaultMessageSourceResolvable(org.springframework.context.support.DefaultMessageSourceResolvable) MessageSourceResolvable(org.springframework.context.MessageSourceResolvable) DefaultMessageSourceResolvable(org.springframework.context.support.DefaultMessageSourceResolvable) PageContext(jakarta.servlet.jsp.PageContext) RequestContext(org.springframework.web.servlet.support.RequestContext) Test(org.junit.jupiter.api.Test)

Example 4 with MessageSourceResolvable

use of org.springframework.context.MessageSourceResolvable in project gocd by gocd.

the class JsonRenderer method gsonBuilder.

private static Gson gsonBuilder(final GoRequestContext requestContext) {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(JsonUrl.class, (JsonSerializer<JsonUrl>) (src, typeOfSrc, context) -> {
        if (requestContext == null) {
            return new JsonPrimitive(src.getUrl());
        } else {
            return new JsonPrimitive(requestContext.getFullRequestPath() + src.getUrl());
        }
    });
    builder.registerTypeHierarchyAdapter(MessageSourceResolvable.class, (JsonSerializer<MessageSourceResolvable>) (src, typeOfSrc, context) -> {
        if (requestContext == null) {
            return new JsonPrimitive(src.getDefaultMessage());
        } else {
            return new JsonPrimitive(requestContext.getMessage(src));
        }
    });
    builder.serializeNulls();
    return builder.create();
}
Also used : Gson(com.google.gson.Gson) StringWriter(java.io.StringWriter) Writer(java.io.Writer) JsonFakeMap(com.thoughtworks.go.util.json.JsonFakeMap) JsonUrl(com.thoughtworks.go.util.json.JsonUrl) JsonSerializer(com.google.gson.JsonSerializer) JsonPrimitive(com.google.gson.JsonPrimitive) JsonAware(com.thoughtworks.go.util.json.JsonAware) MessageSourceResolvable(org.springframework.context.MessageSourceResolvable) GsonBuilder(com.google.gson.GsonBuilder) MessageSourceResolvable(org.springframework.context.MessageSourceResolvable) GsonBuilder(com.google.gson.GsonBuilder) JsonPrimitive(com.google.gson.JsonPrimitive) JsonUrl(com.thoughtworks.go.util.json.JsonUrl)

Example 5 with MessageSourceResolvable

use of org.springframework.context.MessageSourceResolvable in project spring-framework by spring-projects.

the class ResourceBundleMessageSourceTests method doTestMessageAccess.

protected void doTestMessageAccess(boolean reloadable, boolean fallbackToSystemLocale, boolean expectGermanFallback, boolean useCodeAsDefaultMessage, boolean alwaysUseMessageFormat) {
    StaticApplicationContext ac = new StaticApplicationContext();
    if (reloadable) {
        StaticApplicationContext parent = new StaticApplicationContext();
        parent.refresh();
        ac.setParent(parent);
    }
    MutablePropertyValues pvs = new MutablePropertyValues();
    String basepath = "org/springframework/context/support/";
    String[] basenames;
    if (reloadable) {
        basenames = new String[] { "classpath:" + basepath + "messages", "classpath:" + basepath + "more-messages" };
    } else {
        basenames = new String[] { basepath + "messages", basepath + "more-messages" };
    }
    pvs.add("basenames", basenames);
    if (!fallbackToSystemLocale) {
        pvs.add("fallbackToSystemLocale", Boolean.FALSE);
    }
    if (useCodeAsDefaultMessage) {
        pvs.add("useCodeAsDefaultMessage", Boolean.TRUE);
    }
    if (alwaysUseMessageFormat) {
        pvs.add("alwaysUseMessageFormat", Boolean.TRUE);
    }
    Class<?> clazz = reloadable ? (Class<?>) ReloadableResourceBundleMessageSource.class : ResourceBundleMessageSource.class;
    ac.registerSingleton("messageSource", clazz, pvs);
    ac.refresh();
    Locale.setDefault(expectGermanFallback ? Locale.GERMAN : Locale.CANADA);
    assertThat(ac.getMessage("code1", null, Locale.ENGLISH)).isEqualTo("message1");
    Object expected = fallbackToSystemLocale && expectGermanFallback ? "nachricht2" : "message2";
    assertThat(ac.getMessage("code2", null, Locale.ENGLISH)).isEqualTo(expected);
    assertThat(ac.getMessage("code2", null, Locale.GERMAN)).isEqualTo("nachricht2");
    assertThat(ac.getMessage("code2", null, new Locale("DE", "at"))).isEqualTo("nochricht2");
    assertThat(ac.getMessage("code2", null, new Locale("DE", "at", "oo"))).isEqualTo("noochricht2");
    if (reloadable) {
        assertThat(ac.getMessage("code2", null, Locale.GERMANY)).isEqualTo("nachricht2xml");
    }
    MessageSourceAccessor accessor = new MessageSourceAccessor(ac);
    LocaleContextHolder.setLocale(new Locale("DE", "at"));
    try {
        assertThat(accessor.getMessage("code2")).isEqualTo("nochricht2");
    } finally {
        LocaleContextHolder.setLocale(null);
    }
    assertThat(ac.getMessage("code3", null, Locale.ENGLISH)).isEqualTo("message3");
    MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable("code3");
    assertThat(ac.getMessage(resolvable, Locale.ENGLISH)).isEqualTo("message3");
    resolvable = new DefaultMessageSourceResolvable(new String[] { "code4", "code3" });
    assertThat(ac.getMessage(resolvable, Locale.ENGLISH)).isEqualTo("message3");
    assertThat(ac.getMessage("code3", null, Locale.ENGLISH)).isEqualTo("message3");
    resolvable = new DefaultMessageSourceResolvable(new String[] { "code4", "code3" });
    assertThat(ac.getMessage(resolvable, Locale.ENGLISH)).isEqualTo("message3");
    Object[] args = new Object[] { "Hello", new DefaultMessageSourceResolvable(new String[] { "code1" }) };
    assertThat(ac.getMessage("hello", args, Locale.ENGLISH)).isEqualTo("Hello, message1");
    // test default message without and with args
    assertThat(ac.getMessage(null, null, null, Locale.ENGLISH)).isNull();
    assertThat(ac.getMessage(null, null, "default", Locale.ENGLISH)).isEqualTo("default");
    assertThat(ac.getMessage(null, args, "default", Locale.ENGLISH)).isEqualTo("default");
    assertThat(ac.getMessage(null, null, "{0}, default", Locale.ENGLISH)).isEqualTo("{0}, default");
    assertThat(ac.getMessage(null, args, "{0}, default", Locale.ENGLISH)).isEqualTo("Hello, default");
    // test resolvable with default message, without and with args
    resolvable = new DefaultMessageSourceResolvable(null, null, "default");
    assertThat(ac.getMessage(resolvable, Locale.ENGLISH)).isEqualTo("default");
    resolvable = new DefaultMessageSourceResolvable(null, args, "default");
    assertThat(ac.getMessage(resolvable, Locale.ENGLISH)).isEqualTo("default");
    resolvable = new DefaultMessageSourceResolvable(null, null, "{0}, default");
    assertThat(ac.getMessage(resolvable, Locale.ENGLISH)).isEqualTo("{0}, default");
    resolvable = new DefaultMessageSourceResolvable(null, args, "{0}, default");
    assertThat(ac.getMessage(resolvable, Locale.ENGLISH)).isEqualTo("Hello, default");
    // test message args
    assertThat(ac.getMessage("hello", new Object[] { "Arg1", "Arg2" }, Locale.ENGLISH)).isEqualTo("Arg1, Arg2");
    assertThat(ac.getMessage("hello", null, Locale.ENGLISH)).isEqualTo("{0}, {1}");
    if (alwaysUseMessageFormat) {
        assertThat(ac.getMessage("escaped", null, Locale.ENGLISH)).isEqualTo("I'm");
    } else {
        assertThat(ac.getMessage("escaped", null, Locale.ENGLISH)).isEqualTo("I''m");
    }
    assertThat(ac.getMessage("escaped", new Object[] { "some arg" }, Locale.ENGLISH)).isEqualTo("I'm");
    if (useCodeAsDefaultMessage) {
        assertThat(ac.getMessage("code4", null, Locale.GERMAN)).isEqualTo("code4");
    } else {
        assertThatExceptionOfType(NoSuchMessageException.class).isThrownBy(() -> ac.getMessage("code4", null, Locale.GERMAN));
    }
}
Also used : Locale(java.util.Locale) NoSuchMessageException(org.springframework.context.NoSuchMessageException) MessageSourceResolvable(org.springframework.context.MessageSourceResolvable) MutablePropertyValues(org.springframework.beans.MutablePropertyValues)

Aggregations

MessageSourceResolvable (org.springframework.context.MessageSourceResolvable)9 Test (org.junit.jupiter.api.Test)5 DefaultMessageSourceResolvable (org.springframework.context.support.DefaultMessageSourceResolvable)3 PageContext (jakarta.servlet.jsp.PageContext)2 NoSuchMessageException (org.springframework.context.NoSuchMessageException)2 RequestContext (org.springframework.web.servlet.support.RequestContext)2 PaymentResult (alfio.manager.support.PaymentResult)1 Gson (com.google.gson.Gson)1 GsonBuilder (com.google.gson.GsonBuilder)1 JsonPrimitive (com.google.gson.JsonPrimitive)1 JsonSerializer (com.google.gson.JsonSerializer)1 JsonAware (com.thoughtworks.go.util.json.JsonAware)1 JsonFakeMap (com.thoughtworks.go.util.json.JsonFakeMap)1 JsonUrl (com.thoughtworks.go.util.json.JsonUrl)1 StringWriter (java.io.StringWriter)1 Writer (java.io.Writer)1 Locale (java.util.Locale)1 Test (org.junit.Test)1 BaseContextSensitiveTest (org.openmrs.test.BaseContextSensitiveTest)1 MutablePropertyValues (org.springframework.beans.MutablePropertyValues)1