public void testAppContextClassHierarchy() { Class<?>[] clazz = ClassUtils.getClassHierarchy(OsgiBundleXmlApplicationContext.class, ClassUtils.ClassSet.ALL_CLASSES); //Closeable.class, Class<?>[] expected = new Class<?>[] { OsgiBundleXmlApplicationContext.class, AbstractDelegatedExecutionApplicationContext.class, AbstractOsgiBundleApplicationContext.class, AbstractRefreshableApplicationContext.class, AbstractApplicationContext.class, DefaultResourceLoader.class, ResourceLoader.class, AutoCloseable.class, DelegatedExecutionOsgiBundleApplicationContext.class, ConfigurableOsgiBundleApplicationContext.class, ConfigurableApplicationContext.class, ApplicationContext.class, Lifecycle.class, Closeable.class, EnvironmentCapable.class, ListableBeanFactory.class, HierarchicalBeanFactory.class, ApplicationEventPublisher.class, ResourcePatternResolver.class, MessageSource.class, BeanFactory.class, DisposableBean.class }; assertTrue(compareArrays(expected, clazz)); }
/** * Try to retrieve the given message from the parent MessageSource, if any. * @param code the code to lookup up, such as 'calculator.noRateSet' * @param args array of arguments that will be filled in for params * within the message * @param locale the Locale in which to do the lookup * @return the resolved message, or {@code null} if not found * @see #getParentMessageSource() */ protected String getMessageFromParent(String code, Object[] args, Locale locale) { MessageSource parent = getParentMessageSource(); if (parent != null) { if (parent instanceof AbstractMessageSource) { // Call internal method to avoid getting the default code back // in case of "useCodeAsDefaultMessage" being activated. return ((AbstractMessageSource) parent).getMessageInternal(code, args, locale); } else { // Check parent MessageSource, returning null if not found there. return parent.getMessage(code, args, null, locale); } } // Not found in parent either. return null; }
/** * This implementation returns a SimpleTheme instance, holding a * ResourceBundle-based MessageSource whose basename corresponds to * the given theme name (prefixed by the configured "basenamePrefix"). * <p>SimpleTheme instances are cached per theme name. Use a reloadable * MessageSource if themes should reflect changes to the underlying files. * @see #setBasenamePrefix * @see #createMessageSource */ @Override public Theme getTheme(String themeName) { if (themeName == null) { return null; } synchronized (this.themeCache) { Theme theme = this.themeCache.get(themeName); if (theme == null) { String basename = this.basenamePrefix + themeName; MessageSource messageSource = createMessageSource(basename); theme = new SimpleTheme(themeName, messageSource); initParent(theme); this.themeCache.put(themeName, theme); if (logger.isDebugEnabled()) { logger.debug("Theme created: name '" + themeName + "', basename [" + basename + "]"); } } return theme; } }
@Override public MessageSource getMessageService(String messageFilename) { if (messageFilename != null) { MessageSource ms = messageServices.get(messageFilename); if (ms == null) { ResourceBundleMessageSource rbms = (ResourceBundleMessageSource) beanFactory .getBean(LOADED_MESSAGE_SOURCE_BEAN); rbms.setBasename(messageFilename); messageServices.put(messageFilename, rbms); ms = rbms; } return ms; } else { return null; } }
/** * 查找错误消息 * * @param source * @param code * @param params * @param defaultMsg * @return */ public static String getChinese(MessageSource source, String code, Object[] params, String defaultMsg) { if (Check.NuNObj(source)) { throw new IllegalArgumentException("message source is null"); } if (Check.NuNStrStrict(code)) { throw new IllegalArgumentException("code is empty"); } //如果没有object 默认设置为空数组 if (Check.NuNObj(params)) { params = new Object[]{}; } if (Check.NuNStrStrict(defaultMsg)) { return source.getMessage(code, params, Locale.SIMPLIFIED_CHINESE); } else { return source.getMessage(code, params, defaultMsg, Locale.SIMPLIFIED_CHINESE); } }
/** * 查找错误消息 * * @param source * @param code * @param params * @param defaultMsg * @return */ public static int getIntMessage(MessageSource source, String code, Object[] params, String defaultMsg) { if (Check.NuNObj(source)) { throw new IllegalArgumentException("message source is null"); } if (Check.NuNStrStrict(code)) { throw new IllegalArgumentException("code is empty"); } //如果没有object 默认设置为空数组 if (Check.NuNObj(params)) { params = new Object[]{}; } String message = null; if (Check.NuNStrStrict(defaultMsg)) { message = source.getMessage(code, params, Locale.SIMPLIFIED_CHINESE); } else { message = source.getMessage(code, params, defaultMsg, Locale.SIMPLIFIED_CHINESE); } if (Check.NuNStrStrict(message)) { throw new NumberFormatException("message is empty"); } else { return Integer.valueOf(message); } }
/** * 查找错误消息 * * @param source * @param code * @param params * @param defaultMsg * * @return */ public static String getChinese(MessageSource source, String code, Object[] params, String defaultMsg) { if (Check.isNull(source)) { throw new IllegalArgumentException("message source is null"); } if (Check.isNullOrEmpty(code)) { throw new IllegalArgumentException("code is empty"); } //如果没有object 默认设置为空数组 if (Check.isNull(params)) { params = new Object[]{}; } if (Check.isNullOrEmpty(defaultMsg)) { return source.getMessage(code, params, Locale.SIMPLIFIED_CHINESE); } else { return source.getMessage(code, params, defaultMsg, Locale.SIMPLIFIED_CHINESE); } }
/** * 查找错误消息 * * @param source * @param code * @param params * @param defaultMsg * * @return */ public static int getIntMessage(MessageSource source, String code, Object[] params, String defaultMsg) { if (Check.isNull(source)) { throw new IllegalArgumentException("message source is null"); } if (Check.isNullOrEmpty(code)) { throw new IllegalArgumentException("code is empty"); } //如果没有object 默认设置为空数组 if (Check.isNull(params)) { params = new Object[]{}; } String message = null; if (Check.isNullOrEmpty(defaultMsg)) { message = source.getMessage(code, params, Locale.SIMPLIFIED_CHINESE); } else { message = source.getMessage(code, params, defaultMsg, Locale.SIMPLIFIED_CHINESE); } if (Check.isNullOrEmpty(message)) { throw new NumberFormatException("message is empty"); } else { return Integer.valueOf(message); } }
public MailService(JHipsterProperties jHipsterProperties, JavaMailSender javaMailSender, MessageSource messageSource, SpringTemplateEngine templateEngine) { this.jHipsterProperties = jHipsterProperties; this.javaMailSender = javaMailSender; this.messageSource = messageSource; this.templateEngine = templateEngine; }
/** * Constructor. * * @param messageSource The message source to use */ @Autowired public ErrorFieldsExceptionHandler( final MessageSource messageSource ) { this.messageSource = messageSource; }
@Bean @Description("Spring mail message resolver") public MessageSource emailMessageSource() { log.info("loading non-reloadable mail messages resources"); ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:/mails/messages/messages"); messageSource.setDefaultEncoding(CharEncoding.UTF_8); return messageSource; }
/** * Represents a factory method to instantiate {@code MessageHelper} singleton following by * "Double Checked Locking & Volatile" pattern. * * @param messageSource {@code MessageSource} used as the underlying messages bundle * @return {@code MessageHelper} */ public static MessageHelper singleton(final MessageSource messageSource) { MessageHelper helper = instance; if (helper == null) { synchronized (MessageHelper.class) { helper = instance; if (helper == null) { Assert.notNull(messageSource); instance = new MessageHelper(messageSource); helper = instance; } } } return helper; }
public static Message writeAfterThrowingApplicationMessage(Exception e, User user, String type, MessageSource messageSource, Locale locale) { Message message = new Message(); String body = ""; message.setType(Message.ERROR); message.setAuthor(user); switch (type) { case "CREATE": body = messageSource.getMessage("app.create.error", null, locale); break; case "UPDATE": body = "Error update application - " + e.getLocalizedMessage(); break; case "DELETE": body = "Error delete application - " + e.getLocalizedMessage(); break; case "START": body = "Error start application - " + e.getLocalizedMessage(); break; case "STOP": body = "Error stop application - " + e.getLocalizedMessage(); break; case "RESTART": body = "Error restart application - " + e.getLocalizedMessage(); break; default: body = "Error : unkown error"; break; } message.setEvent(body); return message; }
@Bean public MessageSource mailMessageSource() { ResourceBundleMessageSource msgsource = new ResourceBundleMessageSource(); if (nixmashModeEnabled) msgsource.setBasename("mail-nixmash"); else msgsource.setBasename("mail-messages"); return msgsource; }
@Bean public MessageSource messageSource() { ResourceBundleMessageSource msgsource = new ResourceBundleMessageSource(); if (nixmashModeEnabled) msgsource.setBasename("nixmash"); else msgsource.setBasename("messages"); msgsource.setUseCodeAsDefaultMessage( Boolean.parseBoolean(environment.getRequiredProperty(USE_CODE_AS_DEFAULT_MESSAGE))); return msgsource; }
@Bean public MessageSource defaultMessageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasenames("messages", "i18n/messages"); messageSource.setDefaultEncoding(Charset.forName("UTF-8").name()); messageSource.setFallbackToSystemLocale(true); messageSource.setCacheSeconds(-1); messageSource.setAlwaysUseMessageFormat(false); messageSource.setUseCodeAsDefaultMessage(true); return messageSource; }
public void testInterfacesHierarchy() { //Closeable.class, Class<?>[] clazz = ClassUtils.getAllInterfaces(DelegatedExecutionOsgiBundleApplicationContext.class); Class<?>[] expected = { ConfigurableOsgiBundleApplicationContext.class, ConfigurableApplicationContext.class, ApplicationContext.class, Lifecycle.class, Closeable.class, EnvironmentCapable.class, ListableBeanFactory.class, HierarchicalBeanFactory.class, MessageSource.class, ApplicationEventPublisher.class, ResourcePatternResolver.class, BeanFactory.class, ResourceLoader.class, AutoCloseable.class }; assertTrue(compareArrays(expected, clazz)); }
/** * Initialize the MessageSource. * Use parent's if none defined in this context. */ protected void initMessageSource() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) { this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class); // Make MessageSource aware of parent MessageSource. if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) { HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource; if (hms.getParentMessageSource() == null) { // Only set parent context as parent MessageSource if no parent MessageSource // registered already. hms.setParentMessageSource(getInternalParentMessageSource()); } } if (logger.isDebugEnabled()) { logger.debug("Using MessageSource [" + this.messageSource + "]"); } } else { // Use empty MessageSource to be able to accept getMessage calls. DelegatingMessageSource dms = new DelegatingMessageSource(); dms.setParentMessageSource(getInternalParentMessageSource()); this.messageSource = dms; beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource); if (logger.isDebugEnabled()) { logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME + "': using default [" + this.messageSource + "]"); } } }
/** * Return the internal MessageSource used by the context. * @return the internal MessageSource (never {@code null}) * @throws IllegalStateException if the context has not been initialized yet */ private MessageSource getMessageSource() throws IllegalStateException { if (this.messageSource == null) { throw new IllegalStateException("MessageSource not initialized - " + "call 'refresh' before accessing messages via the context: " + this); } return this.messageSource; }
/** * Create a SimpleTheme. * @param name the name of the theme * @param messageSource the MessageSource that resolves theme messages */ public SimpleTheme(String name, MessageSource messageSource) { Assert.notNull(name, "Name must not be null"); Assert.notNull(messageSource, "MessageSource must not be null"); this.name = name; this.messageSource = messageSource; }
/** * 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; }
/** * Get the MsgSource, combining getToolMessageService() and getLoadedMessageSourceService(). Caches the result so it * only needs to be calculated once (most tools will require more than one call to this code! */ private MessageSource getMsgSource() { if (msgSource == null) { if (getToolMessageService() != null) { msgSource = getToolMessageService().getMessageSource(); } if (msgSource == null && getLoadedMessageSourceService() != null && getLanguageFilename() != null) { msgSource = getLoadedMessageSourceService().getMessageService(getLanguageFilename()); } } return msgSource; }
@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 } }
private String getI18nMessage(Connection conn) throws MigrationException { // get spring bean ApplicationContext context = new ClassPathXmlApplicationContext("org/lamsfoundation/lams/messageContext.xml"); MessageService messageService = (MessageService) context.getBean("commonMessageService"); // get server locale String defaultLocale = "en_AU"; String getDefaultLocaleStmt = "select config_value from lams_configuration where config_key='ServerLanguage'"; try { PreparedStatement query = conn.prepareStatement(getDefaultLocaleStmt); ResultSet results = query.executeQuery(); while (results.next()) { defaultLocale = results.getString("config_value"); } } catch (Exception e) { throw new MigrationException("Problem running update; ", e); } String[] tokenisedLocale = defaultLocale.split("_"); Locale locale = new Locale(tokenisedLocale[0], tokenisedLocale[1]); // get i18n'd message for text 'run sequences' MessageSource messageSource = messageService.getMessageSource(); String i18nMessage = messageSource.getMessage("runsequences.folder.name", new Object[] { "" }, locale); if (i18nMessage != null && i18nMessage.startsWith("???")) { // default to English if not present return " Run Sequences"; } return i18nMessage; }
private String getI18nMessage(Connection conn) throws MigrationException { // get spring bean ApplicationContext context = new ClassPathXmlApplicationContext("org/lamsfoundation/lams/messageContext.xml"); MessageService messageService = (MessageService) context.getBean("commonMessageService"); // get server locale String defaultLocale = "en_AU"; String getDefaultLocaleStmt = "select config_value from lams_configuration where config_key='ServerLanguage'"; try { PreparedStatement query = conn.prepareStatement(getDefaultLocaleStmt); ResultSet results = query.executeQuery(); while (results.next()) { defaultLocale = results.getString("config_value"); } } catch (Exception e) { throw new MigrationException("Problem running update; ", e); } String[] tokenisedLocale = defaultLocale.split("_"); Locale locale = new Locale(tokenisedLocale[0], tokenisedLocale[1]); // get i18n'd message for text 'run sequences' MessageSource messageSource = messageService.getMessageSource(); String i18nMessage = messageSource.getMessage("public.folder.name", null, locale); if (i18nMessage != null && i18nMessage.startsWith("???")) { // default to English if not present return "Public Folder"; } return i18nMessage; }
/** * Set localization parameters * @param messageSource * @param locale * @return */ @Deprecated public YadaNotify yadaMessageSource(MessageSource messageSource, Locale locale) { this.messageSource = messageSource; this.locale = locale; return this; }
@Autowired public StudyPlanServiceImpl( StudyPlanRepository studyPlanRepository, SubjectForStudyPlanRepository subjectForStudyPlanRepository, SubjectService subjectService, GradeService gradeService, MessageSource messageSource) { this.studyPlanRepository = studyPlanRepository; this.subjectForStudyPlanRepository = subjectForStudyPlanRepository; this.subjectService = subjectService; this.gradeService = gradeService; this.messageSource = messageSource; }
@Bean(name = "messageSource") public MessageSource messageSource() { ReloadableResourceBundleMessageSource reloadMessage = new ReloadableResourceBundleMessageSource(); reloadMessage.setBasename("classpath:/messages"); reloadMessage.setDefaultEncoding("UTF-8"); reloadMessage.setCacheSeconds(0); return reloadMessage; }
@Before public void before() { messageSource = mock(MessageSource.class); token = mock(TokenModel.class); mailServer = mock(JavaMailSender.class); tokenDeliverySystem = new TokenDeliverySystemEmail(messageSource, mailServer); captor = ArgumentCaptor.forClass(SimpleMailMessage.class); user.setId(1l); }