当前位置: 首页>>代码示例>>Java>>正文


Java LocaleContextHolder类代码示例

本文整理汇总了Java中org.springframework.context.i18n.LocaleContextHolder的典型用法代码示例。如果您正苦于以下问题:Java LocaleContextHolder类的具体用法?Java LocaleContextHolder怎么用?Java LocaleContextHolder使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


LocaleContextHolder类属于org.springframework.context.i18n包,在下文中一共展示了LocaleContextHolder类的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);
}
 
开发者ID:iBase4J,项目名称:iBase4J-Common,代码行数:19,代码来源:Resources.java

示例2: requestDestroyed

import org.springframework.context.i18n.LocaleContextHolder; //导入依赖的package包/类
@Override
public void requestDestroyed(ServletRequestEvent requestEvent) {
	ServletRequestAttributes attributes = null;
	Object reqAttr = requestEvent.getServletRequest().getAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE);
	if (reqAttr instanceof ServletRequestAttributes) {
		attributes = (ServletRequestAttributes) reqAttr;
	}
	RequestAttributes threadAttributes = RequestContextHolder.getRequestAttributes();
	if (threadAttributes != null) {
		// We're assumably within the original request thread...
		LocaleContextHolder.resetLocaleContext();
		RequestContextHolder.resetRequestAttributes();
		if (attributes == null && threadAttributes instanceof ServletRequestAttributes) {
			attributes = (ServletRequestAttributes) threadAttributes;
		}
	}
	if (attributes != null) {
		attributes.requestCompleted();
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:21,代码来源:RequestContextListener.java

示例3: service

import org.springframework.context.i18n.LocaleContextHolder; //导入依赖的package包/类
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	LocaleContextHolder.setLocale(request.getLocale());
	try {
		this.target.handleRequest(request, response);
	}
	catch (HttpRequestMethodNotSupportedException ex) {
		String[] supportedMethods = ex.getSupportedMethods();
		if (supportedMethods != null) {
			response.setHeader("Allow", StringUtils.arrayToDelimitedString(supportedMethods, ", "));
		}
		response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, ex.getMessage());
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:20,代码来源:HttpRequestHandlerServlet.java

示例4: prepareConnection

import org.springframework.context.i18n.LocaleContextHolder; //导入依赖的package包/类
/**
 * Prepare the given HTTP connection.
 * <p>The default implementation specifies POST as method,
 * "application/x-java-serialized-object" as "Content-Type" header,
 * and the given content length as "Content-Length" header.
 * @param connection the HTTP connection to prepare
 * @param contentLength the length of the content to send
 * @throws IOException if thrown by HttpURLConnection methods
 * @see java.net.HttpURLConnection#setRequestMethod
 * @see java.net.HttpURLConnection#setRequestProperty
 */
protected void prepareConnection(HttpURLConnection connection, int contentLength) throws IOException {
	if (this.connectTimeout >= 0) {
		connection.setConnectTimeout(this.connectTimeout);
	}
	if (this.readTimeout >= 0) {
		connection.setReadTimeout(this.readTimeout);
	}
	connection.setDoOutput(true);
	connection.setRequestMethod(HTTP_METHOD_POST);
	connection.setRequestProperty(HTTP_HEADER_CONTENT_TYPE, getContentType());
	connection.setRequestProperty(HTTP_HEADER_CONTENT_LENGTH, Integer.toString(contentLength));

	LocaleContext localeContext = LocaleContextHolder.getLocaleContext();
	if (localeContext != null) {
		Locale locale = localeContext.getLocale();
		if (locale != null) {
			connection.setRequestProperty(HTTP_HEADER_ACCEPT_LANGUAGE, StringUtils.toLanguageTag(locale));
		}
	}
	if (isAcceptGzipEncoding()) {
		connection.setRequestProperty(HTTP_HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:35,代码来源:SimpleHttpInvokerRequestExecutor.java

示例5: convert

import org.springframework.context.i18n.LocaleContextHolder; //导入依赖的package包/类
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
	String text = (String) source;
	if (!StringUtils.hasText(text)) {
		return null;
	}
	Object result;
	try {
		result = this.parser.parse(text, LocaleContextHolder.getLocale());
	}
	catch (ParseException ex) {
		throw new IllegalArgumentException("Unable to parse '" + text + "'", ex);
	}
	if (result == null) {
		throw new IllegalStateException("Parsers are not allowed to return null");
	}
	TypeDescriptor resultType = TypeDescriptor.valueOf(result.getClass());
	if (!resultType.isAssignableTo(targetType)) {
		result = this.conversionService.convert(result, resultType, targetType);
	}
	return result;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:23,代码来源:FormattingConversionService.java

示例6: disableStudyPlan

import org.springframework.context.i18n.LocaleContextHolder; //导入依赖的package包/类
@Override
@Transactional
public StudyPlan disableStudyPlan(Long id) {

	log.info("disabling study plan with id "+id);
    validator.validateStudyPlanId(id);
    StudyPlan studyPlan = findOne(id);
    if(studyPlan == null) {
        String msg = messageSource.getMessage("error.studyplan.notfound", null, LocaleContextHolder.getLocale());
        log.warn(msg);
        throw new BusinessObjectNotFoundException(msg);
    }
    studyPlan.setEnabled(false);
    studyPlanRepository.save(studyPlan);
    return studyPlan;
}
 
开发者ID:university-information-system,项目名称:uis,代码行数:17,代码来源:StudyPlanServiceImpl.java

示例7: addLeftJoinsRecurse

import org.springframework.context.i18n.LocaleContextHolder; //导入依赖的package包/类
private String addLeftJoinsRecurse(String attributePath, String context, YadaSql yadaSql, Class targetClass) {
	String[] parts = attributePath.split("\\.");
	if (parts.length>1) { // location.company.name
		String current = parts[0]; // location
		yadaSql.join("left join " + context + "." + current + " " + current); // e.location location
		return addLeftJoinsRecurse(StringUtils.substringAfter(attributePath, "."), current, yadaSql, targetClass);
	} else {
		try {
			// Last element of the path - if it's a YadaPersistentEnum we still need a join for the map
			if (yadaUtil.getType(targetClass, attributePath) == YadaPersistentEnum.class) {
				yadaSql.join("left join " + context + "." + attributePath + " " + attributePath); 	// left join user.status status
				yadaSql.join("left join " + attributePath + ".langToText langToText");				// left join status.langToText langToText
				String whereToAdd = "KEY(langToText)=:yadalang";
				if (yadaSql.getWhere().indexOf(whereToAdd)<0) {
					yadaSql.where(whereToAdd).and();
					yadaSql.setParameter("yadalang", LocaleContextHolder.getLocale().getLanguage());
				}
				return "langToText";
			}
		} catch (NoSuchFieldException e) {
			log.error("No field {} found on class {} (ignored)", attributePath, targetClass.getName());
		}
		return context + "." + attributePath; // e.phone, company.name
	}
}
 
开发者ID:xtianus,项目名称:yadaframework,代码行数:26,代码来源:YadaDataTableDao.java

示例8: sendEmailWithVerificationLink

import org.springframework.context.i18n.LocaleContextHolder; //导入依赖的package包/类
@Override
public void sendEmailWithVerificationLink(String xForwardedProto, String xForwardedHost, int xForwardedPort, String email, String emailToken, String recipientFullName) {
    Assert.hasText(emailToken, "emailToken must have text");
    Assert.hasText(email, "email must have text");
    Assert.hasText(recipientFullName, "recipientFullName must have text");
    final String fragment = emailSenderProperties.getPpUiVerificationEmailTokenArgName() + "=" + emailToken;

    final String verificationUrl = toPPUIVerificationUri(xForwardedProto, xForwardedHost, xForwardedPort, fragment);
    final Context ctx = new Context();
    ctx.setVariable(PARAM_RECIPIENT_NAME, recipientFullName);
    ctx.setVariable(PARAM_LINK_URL, verificationUrl);
    ctx.setVariable(PARAM_BRAND, emailSenderProperties.getBrand());
    ctx.setLocale(LocaleContextHolder.getLocale());// set locale to support multi-language
    sendEmail(ctx, email,
            PROP_EMAIL_VERIFICATION_LINK_SUBJECT,
            TEMPLATE_VERIFICATION_LINK_EMAIL,
            PROP_EMAIL_FROM_ADDRESS,
            PROP_EMAIL_FROM_PERSONAL,
            LocaleContextHolder.getLocale());
}
 
开发者ID:bhits,项目名称:patient-user-api,代码行数:21,代码来源:EmailSenderImpl.java

示例9: saveSettings

import org.springframework.context.i18n.LocaleContextHolder; //导入依赖的package包/类
public boolean saveSettings(long id, String name, boolean subscribe) {
	UserFilter f = filters.findByIdAndUserId(id,
			accounts.getCurrentUserId());
	if (null != f) {
		f.setName(name);
		f.setSubscribe(subscribe);
		fillLastNoticeId(f);
		filters.save(f);

		// save user language for use in email
		Account a = accounts.getCurrent();
		a.setLang(LocaleContextHolder.getLocale().getLanguage());
		accountRepo.save(a);

		return true;
	} else {
		return false;
	}
}
 
开发者ID:petabyte-research,项目名称:redflags,代码行数:20,代码来源:FilterSvc.java

示例10: searchRestProject

import org.springframework.context.i18n.LocaleContextHolder; //导入依赖的package包/类
/**
 * Search through a REST project and all its resources
 * @param restProject The REST project which will be searched
 * @param query The provided search query
 * @return A list of search results that matches the provided query
 */
private List<SearchResult> searchRestProject(final RestProject restProject, final SearchQuery query){
    final List<SearchResult> searchResults = new LinkedList<SearchResult>();
    if(SearchValidator.validate(restProject.getName(), query.getQuery())){
        final String projectType = messageSource.getMessage("general.type.project", null , LocaleContextHolder.getLocale());
        final SearchResult searchResult = new SearchResult();
        searchResult.setTitle(restProject.getName());
        searchResult.setLink(REST + SLASH + PROJECT + SLASH + restProject.getId());
        searchResult.setDescription(REST_TYPE + COMMA + projectType);
        searchResults.add(searchResult);
    }

    for(RestApplication restApplication : restProject.getApplications()){
        List<SearchResult> restApplicationSearchResult = searchRestApplication(restProject, restApplication, query);
        searchResults.addAll(restApplicationSearchResult);
    }
    return searchResults;
}
 
开发者ID:castlemock,项目名称:castlemock,代码行数:24,代码来源:RestProjectRepositoryImpl.java

示例11: isValidInSession

import org.springframework.context.i18n.LocaleContextHolder; //导入依赖的package包/类
public boolean isValidInSession(Object value, ConstraintValidatorContext context){
    if(value == null){
        return true;
    }

    TreeMap<String, Object> fieldMap = _countRows(value);
    if(fieldMap != null){
        String message = _messageSource.getMessage(context.getDefaultConstraintMessageTemplate(), null, _defaultMesssage, LocaleContextHolder.getLocale());
        Map.Entry<String, Object> field = fieldMap.entrySet().iterator().next();
        context.unwrap(HibernateConstraintValidatorContext.class)
                .addExpressionVariable("name", value.getClass().getSimpleName())
                .addExpressionVariable("fullName", value.getClass().getName())
                .addExpressionVariable("field", field.getKey())
                .addExpressionVariable("value", field.getValue())
                .addExpressionVariable("allFields", StringUtils.join(fieldMap.keySet(), ", "))
                .addExpressionVariable("values", StringUtils.join(fieldMap.values(), ", "))
                .buildConstraintViolationWithTemplate(message)
                .addPropertyNode(field.getKey())
                .addConstraintViolation()
                .disableDefaultConstraintViolation();

        return false;
    }

    return true;
}
 
开发者ID:Klinton90,项目名称:UniqueValidator,代码行数:27,代码来源:UniqueValidator.java

示例12: getAllStages

import org.springframework.context.i18n.LocaleContextHolder; //导入依赖的package包/类
/**
 * GET  /stages -> get all the stages.
 */
@RequestMapping(value = "/stages",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<List<Stage>> getAllStages(Pageable pageable, @RequestParam(value="filter", required = false) String filter, @RequestParam(value="province", required = false) Long province)
    throws URISyntaxException {
    log.debug("REST request to get a page of Stages");

    Page<Stage> page = (province != null)?stageRepository.findByProvinceId(pageable, province):(filter != null && filter.length() > 0)?stageRepository.findByFilter(pageable, filter, LocaleContextHolder.getLocale().getLanguage()):stageRepository.findAll(pageable);
    page.getContent().stream().forEach(s -> {
    	s.resolveTraduction();
    	if(s.getProvince() != null){
    		s.getProvince().resolveTraduction();
    	}
    });

    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/stages");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
开发者ID:jbernach,项目名称:transandalus-backend,代码行数:23,代码来源:StageResource.java

示例13: getTranslationText

import org.springframework.context.i18n.LocaleContextHolder; //导入依赖的package包/类
/**
 * Returns the translation text.
 * @return
 */
public String getTranslationText(){
	String text = null;
	String locale = LocaleContextHolder.getLocale().getLanguage();
	
	Translation t = getTranslations().get(locale);
	
	if(t != null){
		text = t.getTxContent();
	}else{
		// return the first translation if no one was found 
		t = getTranslations().values().stream().findFirst().orElse(null);
		if(t != null){
			text = t.getTxContent();
		}
	}
	
	return text;
}
 
开发者ID:jbernach,项目名称:transandalus-backend,代码行数:23,代码来源:I18n.java

示例14: 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()));
    }
}
 
开发者ID:barrykalok,项目名称:spring-boot-drools-example,代码行数:24,代码来源:ApiControllerAdvice.java

示例15: 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);
}
 
开发者ID:suomenriistakeskus,项目名称:oma-riista-web,代码行数:21,代码来源:GroupHuntingDaysExcelFeature.java


注:本文中的org.springframework.context.i18n.LocaleContextHolder类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。