/** 国际化信息 */ 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); }
@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(); } }
@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(); } }
/** * 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); } }
@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; }
@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; }
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 } }
@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()); }
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; } }
/** * 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; }
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; }
/** * 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); }
/** * 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; }
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())); } }
@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); }
@RequestMapping(value = "newUser", method = RequestMethod.POST) public ModelAndView createUser(@Valid UserPrincipal newUser, BindingResult error, Map<String, Object> model) throws ExecutionException { if (error.hasErrors()) { List<String> messages = Utils.INSTANCE.fieldErrors2String(error.getFieldErrors()); model.put("errors", messages); addUserModel(model, newUser, Type.USER); return new ModelAndView("userForm"); } try { userService.addUser(newUser); } catch (RuntimeException e) { if (e.getCause() instanceof UserExistException) { List<String> errors = new LinkedList<>(); errors.add(i18n.getMessage("user.exists", null, LocaleContextHolder.getLocale())); model.put("errors", errors); addUserModel(model, newUser, Type.USER); return new ModelAndView("userForm"); } else { throw e; } } return new ModelAndView(new RedirectView("/user", true)); }
@RequestMapping(value = "consents/{consentId}/attestation", method = RequestMethod.GET) public ConsentAttestationDto getConsentAttestationDto(Principal principal, @PathVariable("consentId") Long consentId) throws ConsentGenException { final Long patientId = patientService.findIdByUsername(principal.getName()); Locale locale = LocaleContextHolder.getLocale(); //TODO (#10): Move check for consent belonging to this user and consent signed stage to service if (consentService.isConsentBelongToThisUser(consentId, patientId) && consentService.getConsentStatus(consentId).equals(ConsentStatus.CONSENT_SAVED)) { ConsentAttestationDto consentAttestationDto = consentService.getConsentAttestationDto(principal.getName(),consentId); //return consentService.getConsentAttestationDto(principal.getName(),consentId); if (!locale.getLanguage().equalsIgnoreCase("en")) { for (PurposeOfUseCode purposeOfUseCode : consentAttestationDto.getPurposeOfUseCodes()) { String useCode = purposeOfUseCode.getCode(); purposeOfUseCode.setDisplayName(messageSource.getMessage(useCode + ".NAME", null, locale)); purposeOfUseCode.setOriginalText(messageSource.getMessage(useCode + ".DESCRIPTION", null, locale)); } ConsentTermsVersions consentTerm = consentAttestationDto.getConsentTermsVersions(); consentTerm.setConsentTermsText(messageSource.getMessage("CONSENT.TERMS.TEXT", null, locale)); } return consentAttestationDto; } else throw new InternalServerErrorException("Consent Attestation Dto Not Found"); }
@Override protected void buildExcelDocument(final Map<String, Object> model, final Workbook workbook, final HttpServletRequest request, final HttpServletResponse response) { response.setHeader("Content-disposition", "attachment; filename=" + createFilename()); Sheet sheet = workbook.createSheet(); sheet.setDefaultColumnWidth(20); createHeaderRow(sheet, LocaleContextHolder.getLocale()); int row = 2; for (RhyContactSearchResultDTO result : results) { Row sheetRow = sheet.createRow(row++); int col = 0; for (String cellValue : createRow(result)) { sheetRow.createCell(col++).setCellValue(cellValue); } } }
/** * Search through a SOAP port and all its resources * @param soapProject The SOAP project which will be searched * @param soapPort The SOAP port which will be searched * @param query The provided search query * @return A list of search results that matches the provided query */ private List<SearchResult> searchSoapPort(final SoapProject soapProject, final SoapPort soapPort, final SearchQuery query){ final List<SearchResult> searchResults = new LinkedList<SearchResult>(); if(SearchValidator.validate(soapPort.getName(), query.getQuery())){ final String portType = messageSource.getMessage("soap.type.port", null , LocaleContextHolder.getLocale()); final SearchResult searchResult = new SearchResult(); searchResult.setTitle(soapPort.getName()); searchResult.setLink(SOAP + SLASH + PROJECT + SLASH + soapProject.getId() + SLASH + PORT + SLASH + soapPort.getId()); searchResult.setDescription(SOAP_TYPE + COMMA + portType); searchResults.add(searchResult); } for(SoapOperation soapOperation : soapPort.getOperations()){ List<SearchResult> soapOperationSearchResult = searchSoapOperation(soapProject, soapPort, soapOperation, query); searchResults.addAll(soapOperationSearchResult); } return searchResults; }
/** * Search through a SOAP operation and all its resources * @param soapProject The SOAP project which will be searched * @param soapPort The SOAP port which will be searched * @param soapOperation The SOAP operation which will be searched * @param query The provided search query * @return A list of search results that matches the provided query */ private List<SearchResult> searchSoapOperation(final SoapProject soapProject, final SoapPort soapPort, final SoapOperation soapOperation, final SearchQuery query){ final List<SearchResult> searchResults = new LinkedList<SearchResult>(); if(SearchValidator.validate(soapOperation.getName(), query.getQuery())){ final String operationType = messageSource.getMessage("soap.type.operation", null , LocaleContextHolder.getLocale()); final SearchResult searchResult = new SearchResult(); searchResult.setTitle(soapOperation.getName()); searchResult.setLink(SOAP + SLASH + PROJECT + SLASH + soapProject.getId() + SLASH + PORT + SLASH + soapPort.getId() + SLASH + OPERATION + SLASH + soapOperation.getId()); searchResult.setDescription(SOAP_TYPE + COMMA + operationType); searchResults.add(searchResult); } for(SoapMockResponse soapMockResponse : soapOperation.getMockResponses()){ SearchResult soapMockResponseSearchResult = searchSoapMockResponse(soapProject, soapPort, soapOperation, soapMockResponse, query); if(soapMockResponseSearchResult != null){ searchResults.add(soapMockResponseSearchResult); } } return searchResults; }
@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.exportClubAreaFeatures(id, locale); final String filename = huntingClubAreaPrintFeature.getClubAreaExportFileName(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("Club area map export for printing has failed", ex); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("Kartan tulostus epäonnistui. Yritä myöhemmin uudelleen"); } }
@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"); } }
@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("Parse attempt failed for value [" + 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; }
@Test public void testBindingErrorWithFormatterAgainstList() { BeanWithIntegerList tb = new BeanWithIntegerList(); DataBinder binder = new DataBinder(tb); FormattingConversionService conversionService = new FormattingConversionService(); DefaultConversionService.addDefaultConverters(conversionService); conversionService.addFormatterForFieldType(Float.class, new NumberStyleFormatter()); binder.setConversionService(conversionService); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("integerList[0]", "1x2"); LocaleContextHolder.setLocale(Locale.GERMAN); try { binder.bind(pvs); assertTrue(tb.getIntegerList().isEmpty()); assertEquals("1x2", binder.getBindingResult().getFieldValue("integerList[0]")); assertTrue(binder.getBindingResult().hasFieldErrors("integerList[0]")); } finally { LocaleContextHolder.resetLocaleContext(); } }
@Test public void shouldNotValidateWhenFirstNameEmpty() { LocaleContextHolder.setLocale(Locale.ENGLISH); Person person = new Person(); person.setFirstName(""); person.setLastName("smith"); Validator validator = createValidator(); Set<ConstraintViolation<Person>> constraintViolations = validator.validate(person); assertThat(constraintViolations.size()).isEqualTo(1); ConstraintViolation<Person> violation = constraintViolations.iterator().next(); assertThat(violation.getPropertyPath().toString()).isEqualTo("firstName"); assertThat(violation.getMessage()).isEqualTo("may not be empty"); }
@Before public void setUp() { DefaultConversionService.addDefaultConverters(conversionService); conversionService.setEmbeddedValueResolver(new StringValueResolver() { @Override public String resolveStringValue(String strVal) { if ("${pattern}".equals(strVal)) { return "#,##.00"; } else { return strVal; } } }); conversionService.addFormatterForFieldType(Number.class, new NumberStyleFormatter()); conversionService.addFormatterForFieldAnnotation(new NumberFormatAnnotationFormatterFactory()); LocaleContextHolder.setLocale(Locale.US); binder = new DataBinder(new TestBean()); binder.setConversionService(conversionService); }
@Override protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { LocaleContextHolder.setLocale(request.getLocale()); try { this.target.service(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(); } }
@Test public void testDefaultFormattersOn() throws Exception { FormattingConversionServiceFactoryBean factory = new FormattingConversionServiceFactoryBean(); factory.afterPropertiesSet(); FormattingConversionService fcs = factory.getObject(); TypeDescriptor descriptor = new TypeDescriptor(TestBean.class.getDeclaredField("pattern")); LocaleContextHolder.setLocale(Locale.GERMAN); try { Object value = fcs.convert("15,00", TypeDescriptor.valueOf(String.class), descriptor); assertEquals(15.0, value); value = fcs.convert(15.0, descriptor, TypeDescriptor.valueOf(String.class)); assertEquals("15", value); } finally { LocaleContextHolder.resetLocaleContext(); } }
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request); if (localeResolver == null) { return true; } try { Cookie[] cookies = request.getCookies(); if (cookies != null){ for (Cookie cookie : cookies){ if (Objects.equal("lang", cookie.getName())){ LocaleContextHolder.setLocale(new Locale(cookie.getValue())); } } } } catch (Exception e) { Logs.error("occur errors when resolve locale: {}", Throwables.getStackTraceAsString(e)); } return true; }
/** * The login method examines the status of the current user and determines which action should be taken. * The following outcomes are possible: * 1. The user is already logged in, then the user should be redirected to the main page. * 2. The user is not logged in and will try to login. The user will get to the login * view page. If the user have logged out and been redirected to the login page, the a message * should be displayed informing the user that they have been successfully logged out. Another * message could be displayed if the user provided invalid login credentials or if the login * didn't work. * to the page * @param error The error message if a logged in failed due to various reasons * @param logout The logout variable is use to determined if user has been logged out and redirected to the login page. * @param request The login request, which contains the specific error event * @return The login view (With special messages in case of any specific event has occurred). */ @RequestMapping(method = RequestMethod.GET) public ModelAndView login(@RequestParam(value = "error", required = false) final String error, @RequestParam(value = "logout", required = false) final String logout, final HttpServletRequest request) { if(isLoggedIn()){ LOGGER.debug("User is already logged in. Redirecting the user."); return redirect(); } final ModelAndView model = createModelAndView(); model.setViewName(PAGE); model.addObject(DEMO_MODE, demoMode); if (error != null) { LOGGER.debug("Unable to login"); model.addObject(ERROR, getErrorMessage(request, SPRING_SECURITY_LAST_EXCEPTION)); } if (logout != null) { LOGGER.debug("Logout successful"); model.addObject(MSG, messageSource.getMessage("general.login.label.logoutsuccessful", null , LocaleContextHolder.getLocale())); } return model; }
/** * 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(locale.toString().replace("-", "_")).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; }
@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; }
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); }
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; }