@Test public void testRejectWithoutDefaultMessage() throws Exception { TestBean tb = new TestBean(); tb.setName("myName"); tb.setAge(99); BeanPropertyBindingResult ex = new BeanPropertyBindingResult(tb, "tb"); ex.reject("invalid"); ex.rejectValue("age", "invalidField"); StaticMessageSource ms = new StaticMessageSource(); ms.addMessage("invalid", Locale.US, "general error"); ms.addMessage("invalidField", Locale.US, "invalid field"); assertEquals("general error", ms.getMessage(ex.getGlobalError(), Locale.US)); assertEquals("invalid field", ms.getMessage(ex.getFieldError("age"), Locale.US)); }
@Override protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String name, TargetSource customTargetSource) { if (StaticMessageSource.class.equals(beanClass)) { return DO_NOT_PROXY; } else if (name.endsWith("ToBeProxied")) { boolean isFactoryBean = FactoryBean.class.isAssignableFrom(beanClass); if ((this.proxyFactoryBean && isFactoryBean) || (this.proxyObject && !isFactoryBean)) { return new Object[] {this.testInterceptor}; } else { return DO_NOT_PROXY; } } else { return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS; } }
@Test public void statusCodeAndReasonMessage() { Locale locale = Locale.CHINESE; LocaleContextHolder.setLocale(locale); try { StaticMessageSource messageSource = new StaticMessageSource(); messageSource.addMessage("gone.reason", locale, "Gone reason message"); exceptionResolver.setMessageSource(messageSource); StatusCodeAndReasonMessageException ex = new StatusCodeAndReasonMessageException(); exceptionResolver.resolveException(request, response, null, ex); assertEquals("Invalid status reason", "Gone reason message", response.getErrorMessage()); } finally { LocaleContextHolder.resetLocaleContext(); } }
/** * Removes the additional localization for the given key. * * @param key * Key of the localizations. */ public synchronized void removeLocalizations(String key) { StaticMessageSource removedDictionary = bundlesToLocalizations.remove(key); if (removedDictionary != null) { ArrayList<StaticMessageSource> newLocalizations = new ArrayList<StaticMessageSource>( localizations); newLocalizations.remove(removedDictionary); this.localizations = newLocalizations; } Iterator<Entry<String, Set<String>>> iterator = languageCodesToKeys.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, Set<String>> languageCodeToKeys = iterator.next(); Set<String> keys = languageCodeToKeys.getValue(); keys.remove(key); if (keys.isEmpty()) { iterator.remove(); } } ServiceLocator.findService(EventDispatcher.class).fire(new ResourceBundleChangedEvent()); }
public void testRejectWithoutDefaultMessage() throws Exception { TestBean tb = new TestBean(); tb.setName("myName"); tb.setAge(99); BeanPropertyBindingResult ex = new BeanPropertyBindingResult(tb, "tb"); ex.reject("invalid"); ex.rejectValue("age", "invalidField"); StaticMessageSource ms = new StaticMessageSource(); ms.addMessage("invalid", Locale.US, "general error"); ms.addMessage("invalidField", Locale.US, "invalid field"); assertEquals("general error", ms.getMessage(ex.getGlobalError(), Locale.US)); assertEquals("invalid field", ms.getMessage(ex.getFieldError("age"), Locale.US)); }
public void testConstructorWithoutMessageSource() { BeanTableModel beanTableModel = new BeanTableModel(TestBean.class) { protected String[] createColumnPropertyNames() { return new String[] { "stringProperty", "dateProperty" }; } protected Class[] createColumnClasses() { return new Class[] { String.class, Date.class }; } }; try { beanTableModel.setRowNumbers(false); fail("Must throw IllegalStateException: no messagesource set"); } catch (IllegalStateException e) { // test passes } StaticMessageSource messageSource = new StaticMessageSource(); beanTableModel.setMessageSource(messageSource); beanTableModel.setRowNumbers(false); }
public void testGetErrorMessage() { DefaultBindingErrorMessageProvider provider = new DefaultBindingErrorMessageProvider(); TestAbstractFormModel formModel = new TestAbstractFormModel(new Object()) { public FieldFace getFieldFace(String field) { return new DefaultFieldFace("Some Property", "", "", new LabelInfo("Some Property"), null); } }; formModel.add("someProperty", new ValueHolder("value")); StaticMessageSource messageSource = new StaticMessageSource(); messageSource.addMessage("typeMismatch", Locale.getDefault(), "{0} has an invalid format \"{1}\""); MessageSourceAccessor messageSourceAccessor = new MessageSourceAccessor(messageSource); provider.setMessageSourceAccessor(messageSourceAccessor); ValidationMessage message = provider.getErrorMessage(formModel, "someProperty", "new value", new IllegalArgumentException()); assertNotNull(message); assertEquals("someProperty", message.getProperty()); assertEquals("Some Property has an invalid format \"new value\"", message.getMessage()); }
@Test public void beanPostProcessorPublishesEvents() { GenericApplicationContext context = new GenericApplicationContext(); context.registerBeanDefinition("listener", new RootBeanDefinition(BeanThatListens.class)); context.registerBeanDefinition("messageSource", new RootBeanDefinition(StaticMessageSource.class)); context.registerBeanDefinition("postProcessor", new RootBeanDefinition(EventPublishingBeanPostProcessor.class)); context.refresh(); context.publishEvent(new MyEvent(this)); BeanThatListens listener = context.getBean(BeanThatListens.class); assertEquals(4, listener.getEventCount()); context.close(); }
private void setupFactory() throws IOException { this.factory = new PropertiesConfigurationFactory<Foo>(Foo.class); this.factory.setValidator(this.validator); this.factory.setTargetName(this.targetName); this.factory.setIgnoreUnknownFields(this.ignoreUnknownFields); this.factory.setMessageSource(new StaticMessageSource()); }
@Test public void testRequiredFieldsValidation() throws Exception { TargetWithValidatedMap target = new TargetWithValidatedMap(); BindingResult result = bind(target, "info[foo]: bar"); assertThat(result.getErrorCount()).isEqualTo(2); for (FieldError error : result.getFieldErrors()) { System.err.println( new StaticMessageSource().getMessage(error, Locale.getDefault())); } }
private Foo createFoo(final String yaml) throws Exception { YamlConfigurationFactory<Foo> factory = new YamlConfigurationFactory<Foo>( Foo.class); factory.setYaml(yaml); factory.setExceptionIfInvalid(true); factory.setPropertyAliases(this.aliases); factory.setValidator(this.validator); factory.setMessageSource(new StaticMessageSource()); factory.afterPropertiesSet(); return factory.getObject(); }
private Jee createJee(final String yaml) throws Exception { YamlConfigurationFactory<Jee> factory = new YamlConfigurationFactory<Jee>( Jee.class); factory.setYaml(yaml); factory.setExceptionIfInvalid(true); factory.setPropertyAliases(this.aliases); factory.setValidator(this.validator); factory.setMessageSource(new StaticMessageSource()); factory.afterPropertiesSet(); return factory.getObject(); }
/** * Adds a map with additional localizations for a specified local to this manager. * * @param key * Key of the localizations. If there is already a dictionary for this key, it will * be overwritten. * @param locale * The locale the localizations are for. * @param localizations * The localizations. The key is the message key and and value the value. */ public synchronized void addLocalizations(String key, Locale locale, Map<String, String> localizations) { if (localizations == null || localizations.isEmpty()) { LOGGER.debug("You can't add empty localizations for {}. The key was {}", locale, key); return; } String languageCode = locale.toString(); StaticMessageSource innerLocalizations = bundlesToLocalizations.containsKey(key) ? bundlesToLocalizations .get(key) : new StaticMessageSource(); for (Entry<String, String> localization : localizations.entrySet()) { innerLocalizations.addMessage(localization.getKey(), locale, localization.getValue()); } Set<String> keys = languageCodesToKeys.get(languageCode); if (keys == null) { keys = new HashSet<String>(); languageCodesToKeys.put(languageCode, keys); } keys.add(key); this.bundlesToLocalizations.put(key, innerLocalizations); ArrayList<StaticMessageSource> newLocalizations = new ArrayList<StaticMessageSource>( this.localizations); newLocalizations.remove(innerLocalizations); newLocalizations.add(0, innerLocalizations); this.localizations = newLocalizations; ServiceLocator.findService(EventDispatcher.class).fire(new ResourceBundleChangedEvent()); }
@Test public void testRequiredFieldsValidation() throws Exception { TargetWithValidatedMap target = new TargetWithValidatedMap(); BindingResult result = bind(target, "info[foo]: bar"); assertEquals(2, result.getErrorCount()); for (FieldError error : result.getFieldErrors()) { System.err.println( new StaticMessageSource().getMessage(error, Locale.getDefault())); } }
private TemplateFactory buildTemplateFactory() { StaticMessageSource messageSource = new StaticMessageSource(); messageSource.addMessage("test", Locale.getDefault(), "A very useful message"); ExpressionHandlerRegistry registry = new DefaultExpressionHandlerRegistry(); registry.registerExpressionHandler(new MessageExpressionHandler(messageSource)); return new SimpleTemplateFactory(registry, new DefaultContentEscapeHandlerRegistry(), '#', '.', '#'); }
protected void registerBasicServices(DefaultApplicationServices applicationServices) { super.registerBasicServices(applicationServices); StaticMessageSource messageSource = new StaticMessageSource(); messageSource.addMessage("dirty.message", Locale.getDefault(), "{0} has changed, original value was {1}."); messageSource.addMessage("revert.message", Locale.getDefault(), "Revert value to {0}."); messageSource.addMessage("property.label", Locale.getDefault(), "Property"); applicationServices.setMessageSource(messageSource); }
public void testRegisteredServiceIsReturned() { ValueChangeDetector vcd = new DefaultValueChangeDetector(); getApplicationServices().setValueChangeDetector(vcd); assertSame("Expected same object back", vcd, getApplicationServices().getService(ValueChangeDetector.class)); MessageSource msrc = new StaticMessageSource(); getApplicationServices().setMessageSource(msrc); assertSame("Expected same object back", msrc, getApplicationServices().getService(MessageSource.class)); }
public void testSetRegistryEntries() { ValueChangeDetector vcd = new DefaultValueChangeDetector(); MessageSource msrc = new StaticMessageSource(); HashMap entries = new HashMap(); entries.put("org.springframework.binding.value.ValueChangeDetector", vcd); entries.put("org.springframework.context.MessageSource", msrc); getApplicationServices().setRegistryEntries(entries); assertSame("Expected same object back", vcd, getApplicationServices().getService(ValueChangeDetector.class)); assertSame("Expected same object back", msrc, getApplicationServices().getService(MessageSource.class)); }
public void testGetTableCellRendererComponent() { StaticMessageSource messageSource = new StaticMessageSource(); messageSource.addMessage("org.springframework.richclient.table.renderer.EnumTableCellRendererTests$Numbers.ONE", Locale.getDefault(), "one"); messageSource.addMessage("org.springframework.richclient.table.renderer.EnumTableCellRendererTests$Numbers.TWO", Locale.getDefault(), "two"); messageSource.addMessage("org.springframework.richclient.table.renderer.EnumTableCellRendererTests$Numbers.THREE", Locale.getDefault(), "three"); messageSource.addMessage("org.springframework.richclient.table.renderer.EnumTableCellRendererTests$Numbers.FOUR", Locale.getDefault(), "four"); messageSource.addMessage("org.springframework.richclient.table.renderer.EnumTableCellRendererTests$Numbers.FIVE", Locale.getDefault(), "five"); messageSource.addMessage("org.springframework.richclient.table.renderer.EnumTableCellRendererTests$Numbers.SIX", Locale.getDefault(), "six"); messageSource.addMessage("org.springframework.richclient.table.renderer.EnumTableCellRendererTests$Numbers.SEVEN", Locale.getDefault(), "seven"); messageSource.addMessage("org.springframework.richclient.table.renderer.EnumTableCellRendererTests$Numbers.EIGHT", Locale.getDefault(), "eight"); messageSource.addMessage("org.springframework.richclient.table.renderer.EnumTableCellRendererTests$Numbers.NINE", Locale.getDefault(), "nine"); messageSource.addMessage("org.springframework.richclient.table.renderer.EnumTableCellRendererTests$Numbers.TEN", Locale.getDefault(), "ten"); MessageSourceAccessor msa = new MessageSourceAccessor(messageSource); tetcr = new EnumTableCellRenderer(msa); Object[][] rowData = { { Numbers.ONE }, { Numbers.TWO }, { Numbers.THREE }, { Numbers.FOUR }, { Numbers.FIVE }, { Numbers.SIX }, { Numbers.SEVEN }, { Numbers.EIGHT }, { Numbers.NINE }, { Numbers.TEN } }; Object[] columnNames = { "Numbers" }; JTable table = new JTable(rowData, columnNames); TableColumnModel tcm = table.getColumnModel(); tcm.getColumn(0).setCellRenderer(tetcr); tetcr.getTableCellRendererComponent(table, Numbers.SEVEN, false, false, 6, 0); Component component = tetcr.getTableCellRendererComponent(table, Numbers.SEVEN, false, false, 6, 0); assertTrue(component instanceof EnumTableCellRenderer); }
protected BaseTableModel getBaseTableModel() { return new BeanTableModel(TestBean.class, new StaticMessageSource()) { protected String[] createColumnPropertyNames() { return new String[] { "stringProperty", "dateProperty" }; } protected Class[] createColumnClasses() { return new Class[] { String.class, Date.class }; } }; }
public void testLoadFieldFace() { Icon testIcon = new TestIcon(Color.RED); MessageSourceFieldFaceSource fieldFaceSource = new MessageSourceFieldFaceSource(); StaticMessageSource messageSource = new StaticMessageSource(); messageSource.addMessage("context.field.caption", Locale.getDefault(), "the caption"); messageSource.addMessage("context.field.description", Locale.getDefault(), "the description"); messageSource.addMessage("context.field.label", Locale.getDefault(), "the label"); messageSource.addMessage("context.field.icon", Locale.getDefault(), "iconName"); fieldFaceSource.setMessageSourceAccessor(new MessageSourceAccessor(messageSource)); IconSource mockIconSource = (IconSource) EasyMock.createMock(IconSource.class); EasyMock.expect(mockIconSource.getIcon("iconName")).andReturn(testIcon); EasyMock.replay(mockIconSource); fieldFaceSource.setIconSource(mockIconSource); FieldFace face = fieldFaceSource.loadFieldFace("field", "context"); assertEquals("the caption", face.getCaption()); assertEquals("the label", face.getDisplayName()); assertEquals("the description", face.getDescription()); assertEquals(testIcon, face.getIcon()); EasyMock.verify(mockIconSource); }
protected void setUp() { this.personService = mock(PersonService.class); final StaticMessageSource staticMessageSource = new StaticMessageSource(); staticMessageSource.addMessage("personAddedFinalConfirm", Locale.getDefault(), "test"); staticMessageSource.addMessage("roleAdded", Locale.getDefault(), "test"); staticMessageSource.addMessage("errorCode", Locale.getDefault(), "test"); this.messageContext = new DefaultMessageContext(staticMessageSource); this.personSearchAction = new PersonSearchAction(this.personService); this.personSearchAction.setPreferredPersonIdentifierType("NETID"); this.referenceRepository = new MockReferenceRepository(); this.reconciliationCriteriaFactory = new MockReconciliationCriteriaFactory(); }