protected void service(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   final Locale locale = localeResolver.resolveLocale(request);
   LocaleContextHolder.setLocale(locale);
   ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
   RequestContextHolder.setRequestAttributes(requestAttributes);
   try {
     super.service(
         new HttpServletRequestWrapper(request) {
           @Override
           public Locale getLocale() {
             return locale;
           }
         },
         response);
   } finally {
     if (!locale.equals(LocaleContextHolder.getLocale())) {
       if (logger.isDebugEnabled()) {
         logger.debug("locale changed, updating locale resolver");
       }
       localeResolver.setLocale(request, response, LocaleContextHolder.getLocale());
     }
     LocaleContextHolder.resetLocaleContext();
     RequestContextHolder.resetRequestAttributes();
   }
 }
 public void showReasonForm(
     final StateChangeContext stateChangeContext, final ViewContextHolder viewContext) {
   final Entity order = stateChangeContext.getOwner();
   final Entity parameter = parameterService.getParameter();
   Long differenceForDateFrom = getEffectiveDateFromDifference(parameter, order);
   Long differenceForDateTo = getEffectiveDateToDifference(parameter, order);
   final Entity stateChangeEntity = stateChangeContext.getStateChangeEntity();
   String additionalInfoKey = null;
   String additionalInfo = null;
   // EFFECTIVE_DATE_FROM
   if (parameter.getBooleanField(ParameterFieldsO.REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_FROM)
       && differenceForDateFrom > 0L) {
     final String differenceAsString =
         TimeConverterService.convertTimeToString(String.valueOf(Math.abs(differenceForDateFrom)));
     additionalInfoKey = "orders.order.stateChange.additionalInfo.startTooLate";
     additionalInfo =
         translationService.translate(
             additionalInfoKey, LocaleContextHolder.getLocale(), differenceAsString);
   }
   if (parameter.getBooleanField(ParameterFieldsO.REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_FROM)
       && differenceForDateFrom < 0L) {
     final String differenceAsString =
         TimeConverterService.convertTimeToString(String.valueOf(Math.abs(differenceForDateFrom)));
     additionalInfoKey = "orders.order.stateChange.additionalInfo.startTooEarly";
     additionalInfo =
         translationService.translate(
             additionalInfoKey, LocaleContextHolder.getLocale(), differenceAsString);
   }
   // EFFECTIVE_DATE_TO
   if (parameter.getBooleanField(ParameterFieldsO.REASON_NEEDED_WHEN_DELAYED_EFFECTIVE_DATE_TO)
       && differenceForDateTo > 0L) {
     final String differenceAsString =
         TimeConverterService.convertTimeToString(String.valueOf(Math.abs(differenceForDateTo)));
     additionalInfoKey = "orders.order.stateChange.additionalInfo.endTooLate";
     additionalInfo =
         translationService.translate(
             additionalInfoKey, LocaleContextHolder.getLocale(), differenceAsString);
   }
   if (parameter.getBooleanField(ParameterFieldsO.REASON_NEEDED_WHEN_EARLIER_EFFECTIVE_DATE_TO)
       && differenceForDateTo < 0L) {
     final String differenceAsString =
         TimeConverterService.convertTimeToString(String.valueOf(Math.abs(differenceForDateTo)));
     additionalInfoKey = "orders.order.stateChange.additionalInfo.endTooEarly";
     additionalInfo =
         translationService.translate(
             additionalInfoKey, LocaleContextHolder.getLocale(), differenceAsString);
   }
   if (additionalInfo != null) {
     stateChangeEntity.setField(OrderStateChangeFields.ADDITIONAL_INFO, additionalInfo);
     stateChangeContext.save();
   }
   stateChangeContext.setStatus(StateChangeStatus.PAUSED);
   stateChangeContext.save();
   viewContext
       .getViewDefinitionState()
       .openModal(
           "../page/orders/orderStateChangeReasonDialog.html?context={\"form.id\": "
               + stateChangeContext.getStateChangeEntity().getId()
               + "}");
 }
Exemple #3
0
  public PasswordResetToken createPasswordResetToken(PasswordResetTokenCreateRequest request) {
    User user = userRepository.findByEmail(request.getEmail());
    if (user == null) {
      throw new EmailNotFoundException();
    }

    LocalDateTime now = LocalDateTime.now();
    PasswordResetToken passwordResetToken = new PasswordResetToken();
    passwordResetToken.setUser(user);
    passwordResetToken.setEmail(user.getEmail());
    passwordResetToken.setExpiredAt(now.plusHours(24));
    passwordResetToken.setCreatedAt(now);
    passwordResetToken.setCreatedBy(user.toString());
    passwordResetToken.setUpdatedAt(now);
    passwordResetToken.setUpdatedBy(user.toString());
    passwordResetToken = passwordResetTokenRepository.saveAndFlush(passwordResetToken);

    try {
      Blog blog = blogService.readBlogById(Blog.DEFAULT_ID);
      String blogTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage());

      ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath();
      if (blog.isMultiLanguage()) {
        builder.path("/{language}");
      }
      builder.path("/password-reset");
      builder.path("/{token}");

      Map<String, Object> urlVariables = new LinkedHashMap<>();
      urlVariables.put("language", request.getLanguage());
      urlVariables.put("token", passwordResetToken.getToken());
      String resetLink = builder.buildAndExpand(urlVariables).toString();

      Context ctx = new Context(LocaleContextHolder.getLocale());
      ctx.setVariable("passwordResetToken", passwordResetToken);
      ctx.setVariable("resetLink", resetLink);

      MimeMessage mimeMessage = mailSender.createMimeMessage();
      MimeMessageHelper message =
          new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
      message.setSubject(
          MessageFormat.format(
              messageSourceAccessor.getMessage(
                  "PasswordResetSubject", LocaleContextHolder.getLocale()),
              blogTitle));
      message.setFrom(mailProperties.getProperties().get("mail.from"));
      message.setTo(passwordResetToken.getEmail());

      String htmlContent = templateEngine.process("password-reset", ctx);
      message.setText(htmlContent, true); // true = isHtml

      mailSender.send(mimeMessage);
    } catch (MessagingException e) {
      throw new ServiceException(e);
    }

    return passwordResetToken;
  }
Exemple #4
0
  @CacheEvict(value = "users", allEntries = true)
  public List<UserInvitation> inviteUsers(
      UserInvitationCreateRequest form, BindingResult result, AuthorizedUser authorizedUser)
      throws MessagingException {
    String[] recipients = StringUtils.commaDelimitedListToStringArray(form.getInvitees());

    LocalDateTime now = LocalDateTime.now();

    List<UserInvitation> invitations = new ArrayList<>();
    for (String recipient : recipients) {
      UserInvitation invitation = new UserInvitation();
      invitation.setEmail(recipient);
      invitation.setMessage(form.getMessage());
      invitation.setExpiredAt(now.plusHours(72));
      invitation.setCreatedAt(now);
      invitation.setCreatedBy(authorizedUser.toString());
      invitation.setUpdatedAt(now);
      invitation.setUpdatedBy(authorizedUser.toString());
      invitation = userInvitationRepository.saveAndFlush(invitation);
      invitations.add(invitation);
    }

    Blog blog = blogService.readBlogById(Blog.DEFAULT_ID);
    for (UserInvitation invitation : invitations) {
      String websiteTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage());
      String signupLink =
          ServletUriComponentsBuilder.fromCurrentContextPath()
              .path("/_admin/signup")
              .queryParam("token", invitation.getToken())
              .buildAndExpand()
              .toString();

      final Context ctx = new Context(LocaleContextHolder.getLocale());
      ctx.setVariable("websiteTitle", websiteTitle);
      ctx.setVariable("authorizedUser", authorizedUser);
      ctx.setVariable("signupLink", signupLink);
      ctx.setVariable("invitation", invitation);

      final MimeMessage mimeMessage = mailSender.createMimeMessage();
      final MimeMessageHelper message =
          new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
      message.setSubject(
          MessageFormat.format(
              messageSourceAccessor.getMessage(
                  "InvitationMessageTitle", LocaleContextHolder.getLocale()),
              authorizedUser.toString(),
              websiteTitle));
      message.setFrom(authorizedUser.getEmail());
      message.setTo(invitation.getEmail());

      final String htmlContent = templateEngine.process("user-invite", ctx);
      message.setText(htmlContent, true); // true = isHtml

      mailSender.send(mimeMessage);
    }

    return invitations;
  }
Exemple #5
0
  @CacheEvict(value = "users", allEntries = true)
  public User updatePassword(PasswordUpdateRequest request, PasswordResetToken passwordResetToken) {
    User user = userRepository.findByIdForUpdate(request.getUserId());
    if (user == null) {
      throw new IllegalArgumentException("The user does not exist");
    }
    PasswordEncoder passwordEncoder = new StandardPasswordEncoder();
    user.setLoginPassword(passwordEncoder.encode(request.getPassword()));
    user.setUpdatedAt(LocalDateTime.now());
    user.setUpdatedBy(passwordResetToken.getUser().toString());
    user = userRepository.saveAndFlush(user);

    passwordResetTokenRepository.delete(passwordResetToken);

    try {
      Blog blog = blogService.readBlogById(Blog.DEFAULT_ID);
      String blogTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage());

      ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath();
      if (blog.isMultiLanguage()) {
        builder.path("/{language}");
      }
      builder.path("/login");

      Map<String, Object> urlVariables = new LinkedHashMap<>();
      urlVariables.put("language", request.getLanguage());
      urlVariables.put("token", passwordResetToken.getToken());
      String loginLink = builder.buildAndExpand(urlVariables).toString();

      Context ctx = new Context(LocaleContextHolder.getLocale());
      ctx.setVariable("passwordResetToken", passwordResetToken);
      ctx.setVariable("resetLink", loginLink);

      MimeMessage mimeMessage = mailSender.createMimeMessage();
      MimeMessageHelper message =
          new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
      message.setSubject(
          MessageFormat.format(
              messageSourceAccessor.getMessage(
                  "PasswordChangedSubject", LocaleContextHolder.getLocale()),
              blogTitle));
      message.setFrom(mailProperties.getProperties().get("mail.from"));
      message.setTo(passwordResetToken.getEmail());

      String htmlContent = templateEngine.process("password-changed", ctx);
      message.setText(htmlContent, true); // true = isHtml

      mailSender.send(mimeMessage);
    } catch (MessagingException e) {
      throw new ServiceException(e);
    }

    return user;
  }
Exemple #6
0
 /**
  * Set the locale of the current request (if there is one) into Spring's LocaleContextHolder.
  *
  * @param code The code to execute while the locale is set
  * @return the result of the code block
  */
 private static <T> T withRequestLocale(Supplier<T> code) {
   try {
     LocaleContextHolder.setLocale(Http.Context.current().lang().toLocale());
   } catch (Exception e) {
     // Just continue (Maybe there is no context or some internal error in LocaleContextHolder).
     // System default locale will be used.
   }
   try {
     return code.get();
   } finally {
     LocaleContextHolder.resetLocaleContext(); // Clean up ThreadLocal
   }
 }
  // SEC-3013
  @Test
  public void germanSystemLocaleWithEnglishLocaleContextHolder() {
    Locale beforeSystem = Locale.getDefault();
    Locale.setDefault(Locale.GERMAN);

    Locale beforeHolder = LocaleContextHolder.getLocale();
    LocaleContextHolder.setLocale(Locale.US);

    MessageSourceAccessor msgs = SpringSecurityMessageSource.getAccessor();
    assertThat("Access is denied")
        .isEqualTo(msgs.getMessage("AbstractAccessDecisionManager.accessDenied", "Ooops"));

    // Revert to original Locale
    Locale.setDefault(beforeSystem);
    LocaleContextHolder.setLocale(beforeHolder);
  }
 @After
 public void close() {
   LocaleContextHolder.resetLocaleContext();
   if (this.context != null) {
     this.context.close();
   }
 }
  /**
   * Map a list of Computer to a list of ComputerDTO.
   *
   * @param computers the computers to map
   * @return the computers as dto
   */
  public List<ComputerDto> listFromModel(List<Computer> computers) {
    DateTimeFormatter formatter =
        DateTimeFormatter.ofPattern(
            messageSource.getMessage("app.formatDate", null, LocaleContextHolder.getLocale()));
    List<ComputerDto> computersDto = new ArrayList<ComputerDto>();

    for (Computer computer : computers) {
      String introduced = null;
      String discontinued = null;
      long companyId = 0;
      String companyName = null;
      if (null != computer.getIntroduced()) {
        introduced = computer.getIntroduced().format(formatter);
      }
      if (null != computer.getDiscontinued()) {
        discontinued = computer.getDiscontinued().format(formatter);
      }
      if (null != computer.getCompany()) {
        companyId = computer.getCompany().getId();
        companyName = computer.getCompany().getName();
      }

      computersDto.add(
          new ComputerDto.ComputerDtoBuilder(computer.getName())
              .id(computer.getId())
              .companyId(companyId)
              .companyName(companyName)
              .introduced(introduced)
              .discontinued(discontinued)
              .build());
    }
    return computersDto;
  }
  @Override
  public Collection<String> validateLeague(League league) {

    Locale locale = LocaleContextHolder.getLocale();

    Collection<String> errors = new ArrayList<>();

    // check name is not empty
    if (StringUtils.isEmpty(league.getName())) {

      errors.add(this.messageSource.getMessage("createleague.name.mandatory", null, locale));
    }

    // check name is not a doublon
    if (!StringUtils.isEmpty(league.getName())) {

      Collection<League> leaguesWithSameName = this.leagueDao.findLeaguesByName(league.getName());

      for (League leagueWithSameName : leaguesWithSameName) {

        if (!ObjectUtils.equals(leagueWithSameName.getId(), league.getId())) {

          errors.add(
              this.messageSource.getMessage("createleague.name.alreadyexists", null, locale));
        }
      }
    }

    return errors;
  }
  private void setAdditionalInfo(
      final StateChangeContext stateChangeContext, final long difference) {
    if (difference == 0L) {
      return;
    }
    final Entity stateChangeEntity = stateChangeContext.getStateChangeEntity();
    final StateChangeEntityDescriber describer = stateChangeContext.getDescriber();
    final OrderState orderState =
        (OrderState) stateChangeContext.getStateEnumValue(describer.getTargetStateFieldName());

    String additionalInfoKey = null;
    if (OrderState.IN_PROGRESS.equals(orderState)) {
      if (difference < 0L) {
        additionalInfoKey = "orders.order.stateChange.additionalInfo.startTooEarly";
      } else {
        additionalInfoKey = "orders.order.stateChange.additionalInfo.startTooLate";
      }
    } else if (OrderState.COMPLETED.equals(orderState)) {
      if (difference < 0L) {
        additionalInfoKey = "orders.order.stateChange.additionalInfo.endTooEarly";
      } else {
        additionalInfoKey = "orders.order.stateChange.additionalInfo.endTooLate";
      }
    } else {
      return;
    }

    final String differenceAsString =
        TimeConverterService.convertTimeToString(String.valueOf(Math.abs(difference)));
    final String additionalInfo =
        translationService.translate(
            additionalInfoKey, LocaleContextHolder.getLocale(), differenceAsString);
    stateChangeEntity.setField(OrderStateChangeFields.ADDITIONAL_INFO, additionalInfo);
    stateChangeContext.save();
  }
  /** POST -> return the group details */
  @RequestMapping(value = "/{groupName}/details", method = RequestMethod.GET)
  @ResponseBody
  public ApiResponse<Object> getGroupDetails(@PathVariable String groupName) {
    LOG.debug("REST request to get Group details");
    final ApiResponse<Object> apiResponse = new ApiResponse<Object>();
    PermissionGroupsDTO permissionGroupDTO = null;

    // groupName is required
    if (groupName == null || groupName.length() <= 0) {
      LOG.debug("Group Name is required");
      apiResponse.setExplicitDismissal(Boolean.TRUE);
      apiResponse.setLevel(Level.ERROR);
      apiResponse.setCode("1044");
      apiResponse.setStatus("failure");
      apiResponse.setMessage(
          messageSource.getMessage(
              "1044", new Object[] {groupName}, LocaleContextHolder.getLocale()));
      LOG.debug(apiResponse.getMessage());
      return apiResponse;
    }

    // call service layer method getGroupDetails to save the group details
    try {
      permissionGroupDTO = groupService.getGroupDetails(groupName);
    } catch (Exception e) {
      LOG.debug("Exception thrown...", e.getMessage());
      apiResponse.setExplicitDismissal(Boolean.TRUE);
      apiResponse.setLevel(Level.ERROR);
      apiResponse.setCode("1049");
      apiResponse.setStatus("failure");
      apiResponse.setMessage(
          messageSource.getMessage(
              "1049", new Object[] {groupName}, LocaleContextHolder.getLocale()));
      return apiResponse;
    }
    if (permissionGroupDTO == null) {
      permissionGroupDTO =
          new PermissionGroupsDTO(
              groupName, null, new ArrayList<String>(), new ArrayList<String>());
    }
    apiResponse.setStatus("success");
    apiResponse.setData(permissionGroupDTO);

    LOG.debug("return");
    return apiResponse;
  }
 private void initContextHolders(
     HttpServletRequest request, ServletRequestAttributes requestAttributes) {
   LocaleContextHolder.setLocale(request.getLocale(), this.threadContextInheritable);
   RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);
   if (logger.isDebugEnabled()) {
     logger.debug("Bound request context to thread: " + request);
   }
 }
Exemple #14
0
  /**
   * This method looks for a "locale" request parameter. If it finds one, it sets it as the
   * preferred locale and also configures it to work with JSTL.
   *
   * @param request the current request
   * @param response the current response
   * @param chain the chain
   * @throws IOException when something goes wrong
   * @throws ServletException when a communication failure happens
   */
  @SuppressWarnings("unchecked")
  public void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    String locale = request.getParameter("locale");
    Locale preferredLocale = null;

    if (locale != null) {
      int indexOfUnderscore = locale.indexOf('_');
      if (indexOfUnderscore != -1) {
        String language = locale.substring(0, indexOfUnderscore);
        String country = locale.substring(indexOfUnderscore + 1);
        preferredLocale = new Locale(language, country);
      } else {
        preferredLocale = new Locale(locale);
      }
    }

    HttpSession session = request.getSession(false);

    if (session != null) {
      if (preferredLocale == null) {
        preferredLocale = (Locale) session.getAttribute(Constants.PREFERRED_LOCALE_KEY);
      } else {
        session.setAttribute(Constants.PREFERRED_LOCALE_KEY, preferredLocale);
        Config.set(session, Config.FMT_LOCALE, preferredLocale);
      }

      if (preferredLocale != null && !(request instanceof LocaleRequestWrapper)) {
        request = new LocaleRequestWrapper(request, preferredLocale);
        LocaleContextHolder.setLocale(preferredLocale);
      }
    }

    String theme = request.getParameter("theme");
    if (theme != null && request.isUserInRole(Constants.ADMIN_ROLE)) {
      Map<String, Object> config = (Map) getServletContext().getAttribute(Constants.CONFIG);
      config.put(Constants.CSS_THEME, theme);
    }

    chain.doFilter(request, response);

    // Reset thread-bound LocaleContext.
    LocaleContextHolder.setLocaleContext(null);
  }
 @Override
 public void setAsText(String text) throws IllegalArgumentException {
   try {
     setValue(this.formatter.parse(text, LocaleContextHolder.getLocale()));
   } catch (ParseException ex) {
     throw new IllegalArgumentException("Parse attempt failed for value [" + text + "]", ex);
   }
 }
  /**
   * Group search API for the new filter type search and sort criteria
   *
   * @author DiepLe
   * @param searchAndSortCriteria
   * @return
   */
  @RequestMapping(value = "/search", method = RequestMethod.POST)
  @ResponseBody
  public ApiResponse<Object> getGroupSummaryByNewFilterTypeSearchAndSortCriteria(
      @RequestBody SearchAndSortCriteria searchAndSortCriteria) {

    final ApiResponse<Object> apiResponse = new ApiResponse<>();
    List<PermissionGroupSummaryDTO> permissionGroupSummaryDTO = null;
    Long totalRecords = null;
    PermissionGroupSummariesDTO summaries = null;

    try {
      permissionGroupSummaryDTO =
          groupService.getGroupSummaryByNewSearchAndSortCriteria(searchAndSortCriteria);
      totalRecords = groupService.getTotalCountForSearchAndSortCriteria(searchAndSortCriteria);
      summaries = new PermissionGroupSummariesDTO();
      summaries.setGroupList(permissionGroupSummaryDTO);
      summaries.setTotalRecords(totalRecords);
    } catch (IllegalStateException e) {
      e.printStackTrace();
      apiResponse.setStatus("failure");
      apiResponse.setData(null);
      apiResponse.setLevel(Level.ERROR);
      apiResponse.setCode("1069");
      apiResponse.setMessage(
          messageSource.getMessage(
              "1069", new Object[] {e.getMessage()}, LocaleContextHolder.getLocale()));
      return apiResponse;
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
      apiResponse.setStatus("failure");
      apiResponse.setData(null);
      apiResponse.setLevel(Level.ERROR);
      apiResponse.setCode("1070");
      apiResponse.setMessage(
          messageSource.getMessage(
              "1070", new Object[] {e.getMessage()}, LocaleContextHolder.getLocale()));
      return apiResponse;
    } catch (Exception e) {
      throw new LucasRuntimeException(LucasRuntimeException.INTERNAL_ERROR, e);
    }

    apiResponse.setData(summaries);

    return apiResponse;
  }
  @Test
  public void testReplacableLookup() {
    // Change Locale to English
    Locale before = LocaleContextHolder.getLocale();
    LocaleContextHolder.setLocale(Locale.FRENCH);

    // Cause a message to be generated
    MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
    assertThat("Le jeton nonce est compromis FOOBAR")
        .isEqualTo(
            messages.getMessage(
                "DigestAuthenticationFilter.nonceCompromised",
                new Object[] {"FOOBAR"},
                "ERROR - FAILED TO LOOKUP"));

    // Revert to original Locale
    LocaleContextHolder.setLocale(before);
  }
 @Test
 public void localeViewResolution() throws Exception {
   LocaleContextHolder.setLocale(Locale.FRENCH);
   registerAndRefreshContext();
   MockHttpServletResponse response = render("includes", Locale.FRENCH);
   String result = response.getContentAsString();
   assertThat(result, containsString("voila"));
   assertThat(response.getContentType(), equalTo("text/html;charset=UTF-8"));
 }
 private MessageDTO processFieldError(FieldError error) {
   MessageDTO message = null;
   if (error != null) {
     Locale currentLocale = LocaleContextHolder.getLocale();
     String msg = msgSource.getMessage(error.getDefaultMessage(), null, currentLocale);
     ClientException clientException = new ClientException(RestErrorCodes.ERR_001, msg);
     message = new MessageDTO(MessageType.ERROR, clientException);
   }
   return message;
 }
  private void resetContextHolders(
      HttpServletRequest request,
      LocaleContext prevLocaleContext,
      RequestAttributes previousAttributes) {

    LocaleContextHolder.setLocaleContext(prevLocaleContext, this.threadContextInheritable);
    RequestContextHolder.setRequestAttributes(previousAttributes, this.threadContextInheritable);
    if (logger.isTraceEnabled()) {
      logger.trace("Cleared thread-bound request context: " + request);
    }
  }
 public void addMessage(MessageResolver messageResolver) {
   Locale currentLocale = LocaleContextHolder.getLocale();
   if (logger.isDebugEnabled()) {
     logger.debug("Resolving message using " + messageResolver);
   }
   Message message = messageResolver.resolveMessage(messageSource, currentLocale);
   List<Message> messages = sourceMessages.get(message.getSource());
   if (logger.isDebugEnabled()) {
     logger.debug("Adding resolved message " + message);
   }
   messages.add(message);
 }
Exemple #22
0
  /**
   * Return default datePattern (MM/dd/yyyy)
   *
   * @return a string representing the date pattern on the UI
   */
  public static String getDatePattern() {
    Locale locale = LocaleContextHolder.getLocale();
    String defaultDatePattern;
    try {
      defaultDatePattern =
          ResourceBundle.getBundle(Constants.BUNDLE_KEY, locale).getString("date.format");
    } catch (MissingResourceException mse) {
      defaultDatePattern = "MM/dd/yyyy";
    }

    return defaultDatePattern;
  }
 public String generateName(final Entity product) {
   LocalDate date = LocalDate.now();
   String currentDateString = String.format("%s.%s", date.getYear(), date.getMonthValue());
   String productName = product.getStringField(ProductFields.NAME);
   String productNumber = product.getStringField(ProductFields.NUMBER);
   return translationService.translate(
       "technologies.operation.name.default",
       LocaleContextHolder.getLocale(),
       productName,
       productNumber,
       currentDateString);
 }
  @After("pointCut()")
  public void addCategoryToModel() {
    List<Category> categories = getDataFromRest.getCategories();
    List<Category> inLocale = new ArrayList<Category>();
    String language = LocaleContextHolder.getLocale().getLanguage();

    for (Category c : categories) {
      inLocale.add(new Category(c, language));
    }

    request.setAttribute("categories", inLocale);
  }
  @Override
  public void execute(
      Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
      throws TemplateException, IOException {

    String siteLanguage = LocaleContextHolder.getLocale().getLanguage();
    String langValue = ((TemplateScalarModel) params.get("lang")).getAsString();

    if (langValue.equals(siteLanguage)) {
      body.render(env.getOut());
    }
  }
Exemple #26
0
  public void testSetLocaleInSessionWhenSessionIsNull() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter("locale", "es");

    MockHttpServletResponse response = new MockHttpServletResponse();
    filter.doFilter(request, response, new MockFilterChain());

    // no session, should result in null
    assertNull(request.getSession().getAttribute(Constants.PREFERRED_LOCALE_KEY));
    // thread locale should always have it, regardless of session
    assertNotNull(LocaleContextHolder.getLocale());
  }
 @Override
 public Date convert(String date) {
   if (StringUtils.hasText(date)) {
     try {
       DateFormat df =
           DateFormat.getDateInstance(DateFormat.SHORT, LocaleContextHolder.getLocale());
       df.setLenient(false);
       return df.parse(date);
     } catch (ParseException ex) {
       log.error(
           "Conversão falhou com a string \""
               + date
               + "\" no locale \""
               + LocaleContextHolder.getLocale()
               + "\". "
               + ex.toString());
       throw new ConversionFailedException(null, null, date, ex);
     }
   } else {
     return null;
   }
 }
  /**
   * Process this request, publishing an event regardless of the outcome.
   *
   * <p>The actual event handling is performed by the abstract {@link #doService} template method.
   */
  protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    long startTime = System.currentTimeMillis();
    Throwable failureCause = null;

    LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
    LocaleContext localeContext = buildLocaleContext(request);

    RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
    ServletRequestAttributes requestAttributes =
        buildRequestAttributes(request, response, previousAttributes);

    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    asyncManager.registerCallableInterceptor(
        FrameworkServlet.class.getName(), new RequestBindingInterceptor());

    initContextHolders(request, localeContext, requestAttributes);

    try {
      doService(request, response);
    } catch (ServletException ex) {
      failureCause = ex;
      throw ex;
    } catch (IOException ex) {
      failureCause = ex;
      throw ex;
    } catch (Throwable ex) {
      failureCause = ex;
      throw new NestedServletException("Request processing failed", ex);
    } finally {
      resetContextHolders(request, previousLocaleContext, previousAttributes);
      if (requestAttributes != null) {
        requestAttributes.requestCompleted();
      }

      if (logger.isDebugEnabled()) {
        if (failureCause != null) {
          this.logger.debug("Could not complete request", failureCause);
        } else {
          if (asyncManager.isConcurrentHandlingStarted()) {
            logger.debug("Leaving response open for concurrent processing");
          } else {
            this.logger.debug("Successfully completed request");
          }
        }
      }

      publishRequestHandledEvent(request, response, startTime, failureCause);
    }
  }
  @ExceptionHandler(ServiceException.class)
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  @ResponseBody
  public MessageDTO processServerError(ServiceException ex) {

    MessageDTO message = null;
    String messageKey = ex.getMessage();
    Locale currentLocale = LocaleContextHolder.getLocale();
    String messageDetails = msgSource.getMessage(messageKey, null, currentLocale);
    ex.setMessage(messageDetails);
    LOGGER.error("ServiceException occurred .", ex);
    message = new MessageDTO(MessageType.ERROR, ex);
    return message;
  }
  @ExceptionHandler(ClientException.class)
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  @ResponseBody
  public MessageDTO processClientError(ClientException ex) {

    MessageDTO message = null;
    String messageKey = ex.getMessage();
    Locale currentLocale = LocaleContextHolder.getLocale();
    String messageDetails = msgSource.getMessage(messageKey, null, currentLocale);
    ex.setMessage(messageDetails);
    LOGGER.error("ClientException occurred .", ex);
    message = new MessageDTO(MessageType.ERROR, ex);
    return message;
  }