org.springframework.context.i18n.LocaleContextHolder#getLocale ( )源码实例Demo

下面列出了org.springframework.context.i18n.LocaleContextHolder#getLocale ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: data-prep   文件: SpringLocalizationRule.java
@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);
            }
        }
    };
}
 
源代码2 项目: match-trade   文件: JsonResult.java
/**
 * <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;
}
 
@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);
			});
}
 
/**
 * 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;
}
 
源代码5 项目: jdal   文件: FormUtils.java
/**
 * 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;
}
 
源代码6 项目: jdal   文件: DateConverter.java
@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;
}
 
源代码7 项目: FlyCms   文件: CheckUtils.java
/**
 * 抛出校验错误异常
 *
 * @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);
}
 
源代码8 项目: albert   文件: UserSessionUtil.java
public static String getSysLanguage(){
       Locale locale = LocaleContextHolder.getLocale(); 
	if(locale != null){
		return locale.getLanguage() + "_" + locale.getCountry();
	} else {
		return Constants.LOCALE_LANGUAGE.en_US;
	}
}
 
/**
 * 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";
}
 
源代码10 项目: SuperBoot   文件: GlobalExceptionHandler.java
/**
 * 字段验证异常处理,统一处理增加国际化支持
 *
 * @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());
}
 
源代码11 项目: lams   文件: OutputFactory.java
/**
    * 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;
   }
 
源代码12 项目: Spring-Boot-I18n-Pro   文件: LocaleMessage.java
public Locale getLocale() {
    return LocaleContextHolder.getLocale();
}
 
源代码13 项目: data-prep   文件: NoOpSecurity.java
@Override
public Locale getLocale() {
    return LocaleContextHolder.getLocale();
}
 
源代码14 项目: entando-core   文件: RestExceptionHandler.java
private String resolveLocalizedErrorMessage(String code, Object[] args) {
    Locale currentLocale = LocaleContextHolder.getLocale();
    String localizedErrorMessage = getMessageSource().getMessage(code, args, currentLocale);
    return localizedErrorMessage;
}
 
源代码15 项目: Spring-Boot-I18n-Pro   文件: LocaleMessage.java
public String getMessage(String code, Object[] args, String defaultMessage) {
    Locale locale = LocaleContextHolder.getLocale();
    return this.getMessage(code, args, defaultMessage, locale);
}
 
@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;
}
 
源代码17 项目: wallride   文件: UserService.java
@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;
}
 
源代码18 项目: lams   文件: LearningDesignService.java
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.");
    }
}
   }
 
@Override
public Locale getLocale() {
    return LocaleContextHolder.getLocale();
}
 
源代码20 项目: pybbs   文件: LocaleMessageSourceUtil.java
/**
 * @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);
}