本文整理汇总了Java中org.springframework.context.i18n.LocaleContextHolder.getLocale方法的典型用法代码示例。如果您正苦于以下问题:Java LocaleContextHolder.getLocale方法的具体用法?Java LocaleContextHolder.getLocale怎么用?Java LocaleContextHolder.getLocale使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.springframework.context.i18n.LocaleContextHolder
的用法示例。
在下文中一共展示了LocaleContextHolder.getLocale方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getMessage
import org.springframework.context.i18n.LocaleContextHolder; //导入方法依赖的package包/类
/** 国际化信息 */
public static String getMessage(String key, Object... params) {
Locale locale = LocaleContextHolder.getLocale();
ResourceBundle message = MESSAGES.get(locale.getLanguage());
if (message == null) {
synchronized (MESSAGES) {
message = MESSAGES.get(locale.getLanguage());
if (message == null) {
message = ResourceBundle.getBundle("i18n/messages", locale);
MESSAGES.put(locale.getLanguage(), message);
}
}
}
if (params != null && params.length > 0) {
return String.format(message.getString(key), params);
}
return message.getString(key);
}
示例2: resolveError
import org.springframework.context.i18n.LocaleContextHolder; //导入方法依赖的package包/类
private void resolveError(BasicResponse response, ObjectError error) {
Locale currentLocale = LocaleContextHolder.getLocale();
String defaultMessage = error.getDefaultMessage();
if (StringUtils.isNotBlank(defaultMessage) && defaultMessage.startsWith("{DEMO-")) {
String errorCode = defaultMessage.substring(1, defaultMessage.length() - 1);
response.setErrorCode(errorCode);
response.setErrorMessage(getLocalizedErrorMessage(errorCode, error.getArguments()));
} else {
String[] errorCodes = error.getCodes();
for (String code : errorCodes) {
String message = getLocalizedErrorMessage(currentLocale, code, error.getArguments());
if (!code.equals(message)) {
response.setErrorCode(code);
response.setErrorMessage(message);
return;
}
}
response.setErrorCode(error.getCode());
response.setErrorMessage(getLocalizedErrorMessage(error.getCode(), error.getArguments()));
}
}
示例3: export
import org.springframework.context.i18n.LocaleContextHolder; //导入方法依赖的package包/类
@Transactional(readOnly = true)
public GroupHuntingDaysExcelView export(final long groupId) {
final HuntingClubGroup group = requireEntityService.requireHuntingGroup(groupId, EntityPermission.READ);
final LocalisedString clubName = group.getParentOrganisation().getNameLocalisation();
final LocalisedString groupName = group.getNameLocalisation();
final Locale locale = LocaleContextHolder.getLocale();
final Map<Integer, GameSpeciesDTO> species =
F.index(gameDiaryService.getGameSpecies(), GameSpeciesDTO::getCode);
final List<GroupHuntingDayDTO> days = sortDays(groupHuntingDayService.findByClubGroup(group));
final Map<GameDiaryEntryType, List<Long>> rejections = groupHuntingDayService.listRejected(group);
final List<HarvestDTO> harvests = postProcess(rejections.get(GameDiaryEntryType.HARVEST), huntingService.getHarvestsOfGroupMembers(group));
final List<ObservationDTO> observations = postProcess(rejections.get(GameDiaryEntryType.OBSERVATION), huntingService.getObservationsOfGroupMembers(group));
return new GroupHuntingDaysExcelView(locale, new EnumLocaliser(messageSource, locale), species, clubName,
groupName, days, harvests, observations);
}
示例4: purposeOfUseLookup
import org.springframework.context.i18n.LocaleContextHolder; //导入方法依赖的package包/类
@RequestMapping(value = "purposeOfUse")
public List<AddConsentFieldsDto> purposeOfUseLookup() {
List<AddConsentFieldsDto> purposeOfUseDto = purposeOfUseCodeService
.findAllPurposeOfUseCodesAddConsentFieldsDto();
Locale locale = LocaleContextHolder.getLocale();
if (!locale.getLanguage().equalsIgnoreCase("en")) {
for (AddConsentFieldsDto addConsentFieldsDto : purposeOfUseDto) {
//the properties file: key-value should be like : code.name=value, code.description=value
List<String> purposeNameAndDescription = getMultiLangName (locale, addConsentFieldsDto.getCode());
addConsentFieldsDto.setDisplayName(purposeNameAndDescription.get(0));//displayName
addConsentFieldsDto.setDescription(purposeNameAndDescription.get(1));//description
}
}
return purposeOfUseDto;
}
示例5: print
import org.springframework.context.i18n.LocaleContextHolder; //导入方法依赖的package包/类
@RequestMapping(value = "/{id:\\d+}/print",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<?> print(@PathVariable final long id,
@ModelAttribute @Valid final AreaPrintRequestDTO dto) {
try {
final Locale locale = LocaleContextHolder.getLocale();
final FeatureCollection featureCollection = huntingClubAreaPrintFeature.exportHarvestPermitAreaFeatures(id, locale);
final String filename = huntingClubAreaPrintFeature.getHarvestPermitAreaExportFileName(id, locale);
final byte[] imageData = huntingClubAreaPrintFeature.printGeoJson(dto, featureCollection);
final MediaType mediaType = MediaTypeExtras.APPLICATION_PDF;
return ResponseEntity.ok()
.contentType(mediaType)
.contentLength(imageData.length)
.header(ContentDispositionUtil.HEADER_NAME, ContentDispositionUtil.encodeAttachmentFilename(filename))
.body(imageData);
} catch (final Exception ex) {
LOG.error("Permit area map export for printing has failed", ex);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Kartan tulostus epäonnistui. Yritä myöhemmin uudelleen");
}
}
示例6: getMessage
import org.springframework.context.i18n.LocaleContextHolder; //导入方法依赖的package包/类
/**
* 国际化信息
*/
public static String getMessage(String key, Object... params) {
Locale locale = LocaleContextHolder.getLocale();
ResourceBundle message = MESSAGES.get(locale.getLanguage());
if (message == null) {
synchronized (MESSAGES) {
message = MESSAGES.get(locale.getLanguage());
if (message == null) {
message = ResourceBundle.getBundle("i18n/messages", locale);
MESSAGES.put(locale.getLanguage(), message);
}
}
}
if (params != null && params.length > 0) {
return String.format(message.getString(key), params);
}
return message.getString(key);
}
示例7: resolveLocalizedErrorMessage
import org.springframework.context.i18n.LocaleContextHolder; //导入方法依赖的package包/类
/**
* 解析错误信息
* TODO 国际化错误信息应该异常中处理
* @param fieldError
* @return
*/
private String resolveLocalizedErrorMessage(org.springframework.validation.FieldError fieldError) {
Locale currentLocale = LocaleContextHolder.getLocale();
String localizedErrorMessage = null;
if(messageSource != null){
try {
localizedErrorMessage = messageSource.getMessage(fieldError.getCode(), fieldError.getArguments(), currentLocale);
}catch (NoSuchMessageException noSuchMessageException){
logger.debug(noSuchMessageException);
noSuchMessageException.printStackTrace();
}
}
//If the message was not found, return the most accurate field error code instead.
//You can remove this check if you prefer to get the default error message.
if (localizedErrorMessage.equals(fieldError.getDefaultMessage())) {
String[] fieldErrorCodes = fieldError.getCodes();
localizedErrorMessage = fieldErrorCodes[0];
}
return localizedErrorMessage;
}
示例8: computeContextPath
import org.springframework.context.i18n.LocaleContextHolder; //导入方法依赖的package包/类
@Override
protected String computeContextPath(IExpressionContext context, String base, Map<String, Object> parameters) {
StringBuilder result = new StringBuilder(super.computeContextPath(context, base, parameters));
// Adding the current locale, but only if it is not a resource
boolean localizable = !nonLocalizedUrls.matcher(base).find();
if (localizable) {
Locale locale = LocaleContextHolder.getLocale();
String localeString = locale.getLanguage();
result.append("/").append(localeString);
}
return result.toString();
}
示例9: resolveMessagesFromBundleOrDefault
import org.springframework.context.i18n.LocaleContextHolder; //导入方法依赖的package包/类
private String[] resolveMessagesFromBundleOrDefault(final String[] resolved, final Exception e) {
final Locale locale = LocaleContextHolder.getLocale();
final String defaultKey = Stream.of(StringUtils.splitByCharacterTypeCamelCase(e.getClass().getSimpleName()))
.collect(Collectors.joining("_"))
.toUpperCase();
return Stream.of(resolved)
.map(key -> this.context.getMessage(key, null, defaultKey, locale))
.toArray(String[]::new);
}
示例10: serialize
import org.springframework.context.i18n.LocaleContextHolder; //导入方法依赖的package包/类
@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
if (date!=null) {
Locale locale = LocaleContextHolder.getLocale();
TimeZone timeZone = LocaleContextHolder.getTimeZone();
FastDateFormat fastDateFormat = FastDateFormat.getInstance("yyyy-MM-dd", timeZone, locale);
jsonGenerator.writeString(fastDateFormat.format(date));
} else {
jsonGenerator.writeString("");
}
}
示例11: processFieldError
import org.springframework.context.i18n.LocaleContextHolder; //导入方法依赖的package包/类
private List<ErrorMessage> processFieldError(List<FieldError> error) {
List<ErrorMessage> messages = new ArrayList<>();
if (error != null) {
for (int i = 0; i < error.size(); i++) {
Locale currentLocale = LocaleContextHolder.getLocale();
String msg = msgSource.getMessage(error.get(i).getDefaultMessage(), null, currentLocale);
messages.add(new ErrorMessage(ErrorMessageType.ERROR, msg, error.get(i).getField()));
}
}
return messages;
}
示例12: getLocalValue
import org.springframework.context.i18n.LocaleContextHolder; //导入方法依赖的package包/类
/**
* Get the localized value of an entity's attribute
* @param entityId the id of the entity
* @param entityClass the class of the entity
* @param attributeName the name of the attribute that must be defined as Map<Locale, String>
* @param locale the locale for the value, use null for the current request locale
* @param returnNull (optional) true if null must be returned when no value is present instead of the empty string
* @return the localized value in the specified locale, or in the default configured locale if the value is not set for that locale,
* or an empty string if no value is found or null if no value is found and returnNull is true.
*/
public String getLocalValue(long entityId, Class<?> entityClass, String attributeName, Locale locale, Boolean... returnNull) {
// select color from YadaArticle_color where YadaArticle_id=123 and locale="en_US"
if (locale==null) {
locale = LocaleContextHolder.getLocale();
}
String className = entityClass.getSimpleName();
String tableName = className + "_" + attributeName;
String idColumn = className + "_id";
YadaSql yadaSql = YadaSql.instance().selectFrom("select " + attributeName + " from " + tableName)
.where(idColumn + " = :entityId").and()
.where("locale = :localeString").and()
.setParameter("entityId", entityId)
.setParameter("localeString", locale.toString());
List<?> result = yadaSql.nativeQuery(em).getResultList();
if (result.isEmpty()) {
// Try with the default locale
Locale defaultLocale = config.getDefaultLocale();
if (defaultLocale!=null && !defaultLocale.equals(locale)) {
yadaSql.setParameter("localeString", defaultLocale.toString());
result = yadaSql.nativeQuery(em).getResultList();
}
}
if (result.isEmpty()) {
if (returnNull!=null && returnNull.length>0 && Boolean.TRUE.equals(returnNull[0])) {
return null;
}
return "";
}
return (String) result.get(0);
}
示例13: getI18NText
import org.springframework.context.i18n.LocaleContextHolder; //导入方法依赖的package包/类
/**
* 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;
}
示例14: internationaliseActivityTitle
import org.springframework.context.i18n.LocaleContextHolder; //导入方法依赖的package包/类
@Override
public String internationaliseActivityTitle(Long learningLibraryID) {
ToolActivity templateActivity = (ToolActivity) activityDAO.getTemplateActivityByLibraryID(learningLibraryID);
if (templateActivity != null) {
Locale locale = LocaleContextHolder.getLocale();
String languageFilename = templateActivity.getLanguageFile();
if (languageFilename != null) {
MessageSource toolMessageSource = toolActMessageService.getMessageService(languageFilename);
if (toolMessageSource != null) {
String title = toolMessageSource.getMessage(Activity.I18N_TITLE, null, templateActivity.getTitle(),
locale);
if (title != null && title.trim().length() > 0) {
return title;
}
} else {
log.warn("Unable to internationalise the library activity " + templateActivity.getTitle()
+ " message file " + templateActivity.getLanguageFile()
+ ". Activity Message source not available");
}
}
}
if (templateActivity.getTitle() != null && templateActivity.getTitle().trim().length() > 0) {
return templateActivity.getTitle();
} else {
return "Untitled"; // should never get here - just return something in case there is a bug. A blank title affect the layout of the main page
}
}
示例15: handleUserFacingException
import org.springframework.context.i18n.LocaleContextHolder; //导入方法依赖的package包/类
@ExceptionHandler(UserFacingException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public ModelAndView handleUserFacingException(HttpServletRequest request, UserFacingException ex) {
logger.warn("UserFacingException: " + request.getRequestURL(), ex);
ModelAndView mav = new ModelAndView();
Locale locale = LocaleContextHolder.getLocale();
String msg = messageSource.getMessage(ex.getMessage(), null, locale);
mav.addObject("message", msg);
mav.setViewName("error");
return mav;
}