Java Code Examples for org.springframework.context.i18n.LocaleContextHolder#getLocale()

The following examples show how to use org.springframework.context.i18n.LocaleContextHolder#getLocale() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SpringLocalizationRule.java    From data-prep with Apache License 2.0 6 votes vote down vote up
@Override
public Statement apply(Statement base, Description description) {
    Statement statement = super.apply(base, description);
    return new Statement() {

        @Override
        public void evaluate() throws Throwable {
            final Locale previousLocale = LocaleContextHolder.getLocale();
            try {
                LocaleContextHolder.setLocale(locale);
                statement.evaluate();
            } finally {
                LocaleContextHolder.setLocale(previousLocale);
            }
        }
    };
}
 
Example 2
Source File: GroovyMarkupConfigurer.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Resolve a template from the given template path.
 * <p>The default implementation uses the Locale associated with the current request,
 * as obtained through {@link org.springframework.context.i18n.LocaleContextHolder LocaleContextHolder},
 * to find the template file. Effectively the locale configured at the engine level is ignored.
 * @see LocaleContextHolder
 * @see #setLocale
 */
protected URL resolveTemplate(ClassLoader classLoader, String templatePath) throws IOException {
	MarkupTemplateEngine.TemplateResource resource = MarkupTemplateEngine.TemplateResource.parse(templatePath);
	Locale locale = LocaleContextHolder.getLocale();
	URL url = classLoader.getResource(resource.withLocale(StringUtils.replace(locale.toString(), "-", "_")).toString());
	if (url == null) {
		url = classLoader.getResource(resource.withLocale(locale.getLanguage()).toString());
	}
	if (url == null) {
		url = classLoader.getResource(resource.withLocale(null).toString());
	}
	if (url == null) {
		throw new IOException("Unable to load template:" + templatePath);
	}
	return url;
}
 
Example 3
Source File: DefaultRenderingResponseBuilder.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected Mono<Void> writeToInternal(ServerWebExchange exchange, Context context) {
	MediaType contentType = exchange.getResponse().getHeaders().getContentType();
	Locale locale = LocaleContextHolder.getLocale(exchange.getLocaleContext());
	Stream<ViewResolver> viewResolverStream = context.viewResolvers().stream();

	return Flux.fromStream(viewResolverStream)
			.concatMap(viewResolver -> viewResolver.resolveViewName(name(), locale))
			.next()
			.switchIfEmpty(Mono.error(() ->
					new IllegalArgumentException("Could not resolve view with name '" + name() + "'")))
			.flatMap(view -> {
				List<MediaType> mediaTypes = view.getSupportedMediaTypes();
				return view.render(model(),
						contentType == null && !mediaTypes.isEmpty() ? mediaTypes.get(0) : contentType,
						exchange);
			});
}
 
Example 4
Source File: JsonResult.java    From match-trade with Apache License 2.0 6 votes vote down vote up
/**
 * <p>返回失败,无数据</p>
 * @param BindingResult
 * @return JsonResult
 */
public JsonResult<T> error(BindingResult result, MessageSource messageSource) {
    StringBuffer msg = new StringBuffer();
    // 获取错位字段集合
    List<FieldError> fieldErrors = result.getFieldErrors();
    // 获取本地locale,zh_CN
    Locale currentLocale = LocaleContextHolder.getLocale();
    for (FieldError fieldError : fieldErrors) {
        // 获取错误信息
        String errorMessage = messageSource.getMessage(fieldError, currentLocale);
        // 添加到错误消息集合内
        msg.append(fieldError.getField() + ":" + errorMessage + " ");
    }
    this.setCode(CODE_FAILED);
    this.setMsg(msg.toString());
    this.setData(null);
    return this;
}
 
Example 5
Source File: OutputFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Get the I18N description for this key. If the tool has supplied a messageService, then this is used to look up
    * the key and hence get the text. Otherwise if the tool has supplied a I18N languageFilename then it is accessed
    * via the shared toolActMessageService. If neither are supplied or the key is not found, then any "." in the name
    * are converted to space and this is used as the return value.
    *
    * This is normally used to get the description for a definition, in whic case the key should be in the format
    * output.desc.[definition name], key = definition name and addPrefix = true. For example a definition name of
    * "learner.mark" becomes output.desc.learner.mark.
    *
    * If you want to use this to get an arbitrary string from the I18N files, then set addPrefix = false and the
    * output.desc will not be added to the beginning.
    */
   protected String getI18NText(String key, boolean addPrefix) {
String translatedText = null;

MessageSource tmpMsgSource = getMsgSource();
if (tmpMsgSource != null) {
    if (addPrefix) {
	key = KEY_PREFIX + key;
    }
    Locale locale = LocaleContextHolder.getLocale();
    try {
	translatedText = tmpMsgSource.getMessage(key, null, locale);
    } catch (NoSuchMessageException e) {
	log.warn("Unable to internationalise the text for key " + key
		+ " as no matching key found in the msgSource");
    }
} else {
    log.warn("Unable to internationalise the text for key " + key
	    + " as no matching key found in the msgSource. The tool's OutputDefinition factory needs to set either (a) messageSource or (b) loadedMessageSourceService and languageFilename.");
}

if (translatedText == null || translatedText.length() == 0) {
    translatedText = key.replace('.', ' ');
}

return translatedText;
   }
 
Example 6
Source File: GlobalExceptionHandler.java    From SuperBoot with MIT License 5 votes vote down vote up
/**
 * 字段验证异常处理,统一处理增加国际化支持
 *
 * @param req 请求内容
 * @param e   异常信息
 * @return
 * @throws Exception
 */
@ExceptionHandler(value = MethodArgumentNotValidException.class)
@ResponseBody
public BaseMessage methodArgumentNotValidExceptionErrorHandler(HttpServletRequest req, Exception e) {
    MethodArgumentNotValidException c = (MethodArgumentNotValidException) e;
    List<FieldError> errors = c.getBindingResult().getFieldErrors();
    Locale locale = LocaleContextHolder.getLocale();
    StringBuffer errorMsg = new StringBuffer();
    for (FieldError err : errors) {
        String message = messageSource.getMessage(err, locale);
        errorMsg.append(err.getField() + ":" + message + ",");
    }

    return pubTools.genNoMsg(StatusCode.PARAMS_NOT_VALIDATE, errorMsg.subSequence(0, errorMsg.length() - 1).toString());
}
 
Example 7
Source File: StartPageFeedsController.java    From podcastpedia-web with MIT License 5 votes vote down vote up
/**
 * Returns list of newest podcasts to be generated as a rss feed.
 * Request comes from start page. 
 * 
 * @param model
 * @return
 */
@RequestMapping("newest.rss")
public String getNewestPodcastsRssFeed(Model model) {
	Locale locale = LocaleContextHolder.getLocale();        
    model.addAttribute("list_of_podcasts", getNewestPodcastsForLocale(locale));
    model.addAttribute("feed_title",  messageSource.getMessage("podcasts.newest.feed_title", null, LocaleContextHolder.getLocale()));
    model.addAttribute("feed_description",  messageSource.getMessage("podcasts.newest.feed_description", null, LocaleContextHolder.getLocale()));
    model.addAttribute("feed_link",  configService.getValue("HOST_AND_PORT_URL"));
    model.addAttribute("HOST_AND_PORT_URL", configService.getValue("HOST_AND_PORT_URL"));
    
    return "newestPodcastsRssFeedView";
}
 
Example 8
Source File: UserSessionUtil.java    From albert with MIT License 5 votes vote down vote up
public static String getSysLanguage(){
       Locale locale = LocaleContextHolder.getLocale(); 
	if(locale != null){
		return locale.getLanguage() + "_" + locale.getCountry();
	} else {
		return Constants.LOCALE_LANGUAGE.en_US;
	}
}
 
Example 9
Source File: CheckUtils.java    From FlyCms with MIT License 5 votes vote down vote up
/**
 * 抛出校验错误异常
 *
 * @param msgKey
 * @param args
 */
private static void fail(String msgKey, Object... args) {
    // 消息的参数化和国际化配置
    Locale locale = LocaleContextHolder.getLocale();
    msgKey = source.getMessage(msgKey, args, locale);
    //throw new CheckException(msgKey);
}
 
Example 10
Source File: DateConverter.java    From jdal with Apache License 2.0 5 votes vote down vote up
@Override
protected DateFormat getFormat(Locale locale) {
	if (locale == null) 
		locale = LocaleContextHolder.getLocale();
	
    DateFormat f = DateFormat.getDateTimeInstance(DateFormat.SHORT,
               DateFormat.SHORT, locale);
       f.setLenient(false);
       
       return f;
}
 
Example 11
Source File: FormUtils.java    From jdal with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new DateField with format for current locale and given style.
 * @param style DateFormat style
 * @return a new DateField
 */
public static DateField newDateField(int style) {
	DateField df = new DateField();
	Locale locale = LocaleContextHolder.getLocale();
	df.setLocale(locale);
	DateFormat dateFormat = DateFormat.getDateInstance(style);
	
	if (dateFormat instanceof SimpleDateFormat) {
		SimpleDateFormat sdf = (SimpleDateFormat) dateFormat;
		df.setDateFormat(sdf.toPattern());
	}
	
	return df;
}
 
Example 12
Source File: UserService.java    From wallride with Apache License 2.0 4 votes vote down vote up
@CacheEvict(value = WallRideCacheConfiguration.USER_CACHE, allEntries = true)
public User updatePassword(PasswordUpdateRequest request, PasswordResetToken passwordResetToken) {
	User user = userRepository.findOneForUpdateById(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.getBlogById(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;
}
 
Example 13
Source File: LearningDesignService.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private void internationaliseActivities(Collection<LibraryActivityDTO> activities) {
Iterator<LibraryActivityDTO> iter = activities.iterator();
Locale locale = LocaleContextHolder.getLocale();

if (log.isDebugEnabled()) {
    if (locale == null) {
	log.debug("internationaliseActivities: Locale missing.");
    }
}

while (iter.hasNext()) {
    LibraryActivityDTO activity = iter.next();
    // update the activity fields
    String languageFilename = activity.getLanguageFile();
    if (languageFilename != null) {
	MessageSource toolMessageSource = toolActMessageService.getMessageService(languageFilename);
	if (toolMessageSource != null) {
	    activity.setActivityTitle(toolMessageSource.getMessage(Activity.I18N_TITLE, null,
		    activity.getActivityTitle(), locale));
	    activity.setDescription(toolMessageSource.getMessage(Activity.I18N_DESCRIPTION, null,
		    activity.getDescription(), locale));
	} else {
	    log.warn("Unable to internationalise the library activity " + activity.getActivityID() + " "
		    + activity.getActivityTitle() + " message file " + activity.getLanguageFile()
		    + ". Activity Message source not available");
	}

	// update the tool field - note only tool activities have a tool entry.
	if ((activity.getActivityTypeID() != null)
		&& (Activity.TOOL_ACTIVITY_TYPE == activity.getActivityTypeID().intValue())) {
	    languageFilename = activity.getToolLanguageFile();
	    toolMessageSource = toolActMessageService.getMessageService(languageFilename);
	    if (toolMessageSource != null) {
		activity.setToolDisplayName(toolMessageSource.getMessage(Tool.I18N_DISPLAY_NAME, null,
			activity.getToolDisplayName(), locale));
	    } else {
		log.warn("Unable to internationalise the library activity " + activity.getActivityID() + " "
			+ activity.getActivityTitle() + " message file " + activity.getLanguageFile()
			+ ". Tool Message source not available");
	    }
	}
    } else {
	log.warn("Unable to internationalise the library activity " + activity.getActivityID() + " "
		+ activity.getActivityTitle() + ". No message file supplied.");
    }
}
   }
 
Example 14
Source File: TicketResource.java    From springboot-shiro-cas-mybatis with MIT License 4 votes vote down vote up
@Override
public Locale getLocale() {
    return LocaleContextHolder.getLocale();
}
 
Example 15
Source File: ServiceModelToSwagger2MapperImpl.java    From datax-web with MIT License 4 votes vote down vote up
@Override
protected Operation mapOperation(springfox.documentation.service.Operation from) {

    if (from == null) {
        return null;
    }

    Locale locale = LocaleContextHolder.getLocale();

    Operation operation = new Operation();

    operation.setSecurity(mapAuthorizations(from.getSecurityReferences()));
    operation.setVendorExtensions(vendorExtensionsMapper.mapExtensions(from.getVendorExtensions()));
    operation.setDescription(messageSource.getMessage(from.getNotes(), null, from.getNotes(), locale));
    operation.setOperationId(from.getUniqueId());
    operation.setResponses(mapResponseMessages(from.getResponseMessages()));
    operation.setSchemes(stringSetToSchemeList(from.getProtocol()));
    Set<String> tagsSet = new HashSet<>(1);

    if(from.getTags() != null && from.getTags().size() > 0){

        List<String> list = new ArrayList<String>(tagsSet.size());

        Iterator<String> it = from.getTags().iterator();
        while(it.hasNext()){
           String tag = it.next();
           list.add(
               StringUtils.isNotBlank(tag) ? messageSource.getMessage(tag, null, tag, locale) : " ");
        }

        operation.setTags(list);
    }else {
        operation.setTags(null);
    }

    operation.setSummary(from.getSummary());
    Set<String> set1 = from.getConsumes();
    if (set1 != null) {
        operation.setConsumes(new ArrayList<String>(set1));
    } else {
        operation.setConsumes(null);
    }

    Set<String> set2 = from.getProduces();
    if (set2 != null) {
        operation.setProduces(new ArrayList<String>(set2));
    } else {
        operation.setProduces(null);
    }


    operation.setParameters(parameterListToParameterList(from.getParameters()));
    if (from.getDeprecated() != null) {
        operation.setDeprecated(Boolean.parseBoolean(from.getDeprecated()));
    }

    return operation;
}
 
Example 16
Source File: LocaleMessage.java    From Spring-Boot-I18n-Pro with MIT License 4 votes vote down vote up
public String getMessage(String code, Object[] args, String defaultMessage) {
    Locale locale = LocaleContextHolder.getLocale();
    return this.getMessage(code, args, defaultMessage, locale);
}
 
Example 17
Source File: RestExceptionHandler.java    From entando-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
private String resolveLocalizedErrorMessage(String code, Object[] args) {
    Locale currentLocale = LocaleContextHolder.getLocale();
    String localizedErrorMessage = getMessageSource().getMessage(code, args, currentLocale);
    return localizedErrorMessage;
}
 
Example 18
Source File: NoOpSecurity.java    From data-prep with Apache License 2.0 4 votes vote down vote up
@Override
public Locale getLocale() {
    return LocaleContextHolder.getLocale();
}
 
Example 19
Source File: LocaleMessage.java    From Spring-Boot-I18n-Pro with MIT License 4 votes vote down vote up
public Locale getLocale() {
    return LocaleContextHolder.getLocale();
}
 
Example 20
Source File: LocaleMessageSourceUtil.java    From pybbs with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * @param code           :对应messages配置的key.
 * @param args           : 数组参数.
 * @param defaultMessage : 没有设置key的时候的默认值.
 * @return
 */
public String getMessage(String code, Object[] args, String defaultMessage) {
    //这里使用比较方便的方法,不依赖request.
    Locale locale = LocaleContextHolder.getLocale();
    return messageSource.getMessage(code, args, defaultMessage, locale);
}