001    package org.springframework.richclient.context.support;
002    
003    import java.util.Locale;
004    
005    import org.springframework.beans.BeansException;
006    import org.springframework.beans.factory.BeanInitializationException;
007    import org.springframework.beans.factory.config.BeanPostProcessor;
008    import org.springframework.context.MessageSource;
009    import org.springframework.context.NoSuchMessageException;
010    import org.springframework.context.support.DefaultMessageSourceResolvable;
011    import org.springframework.richclient.core.LabelConfigurable;
012    import org.springframework.richclient.core.LabelInfo;
013    import org.springframework.richclient.core.TitleConfigurable;
014    import org.springframework.util.StringUtils;
015    
016    public class LabelConfigurableBeanPostProcessor implements BeanPostProcessor {
017            /** The key fragment used to retrieve the label for a given object. */
018            public static final String LABEL_KEY = "label";
019    
020            private MessageSource messageSource;
021    
022            public LabelConfigurableBeanPostProcessor(MessageSource messageSource) {
023                    this.messageSource = messageSource;
024            }
025    
026            public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
027                    if (bean instanceof LabelConfigurable) {
028                            LabelConfigurable configurable = (LabelConfigurable) bean;
029    
030                            try {
031                                    String label = messageSource.getMessage(new DefaultMessageSourceResolvable(name + "." + LABEL_KEY),
032                                                    Locale.getDefault());
033    
034                                    if (StringUtils.hasText(label)) {
035                                            configurable.setLabelInfo(LabelInfo.valueOf(label));
036                                    }
037                            }
038                            catch (NoSuchMessageException e) {
039                                    throw new BeanInitializationException("Unable to initialize bean " + name, e);
040                            }
041                    }
042    
043                    return bean;
044            }
045    
046            public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
047                    return bean;
048            }
049    }