View Javadoc

1   /*
2    * Copyright 2007 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.ws.transport.support;
18  
19  import java.io.IOException;
20  import java.io.InputStream;
21  import java.util.ArrayList;
22  import java.util.Collections;
23  import java.util.List;
24  import java.util.Properties;
25  import javax.servlet.ServletContext;
26  
27  import org.springframework.beans.BeanUtils;
28  import org.springframework.beans.BeansException;
29  import org.springframework.beans.factory.BeanCreationException;
30  import org.springframework.beans.factory.BeanFactory;
31  import org.springframework.beans.factory.BeanFactoryAware;
32  import org.springframework.beans.factory.BeanInitializationException;
33  import org.springframework.beans.factory.BeanNameAware;
34  import org.springframework.beans.factory.InitializingBean;
35  import org.springframework.context.ApplicationContext;
36  import org.springframework.context.ApplicationContextAware;
37  import org.springframework.context.ApplicationEventPublisherAware;
38  import org.springframework.context.MessageSourceAware;
39  import org.springframework.context.ResourceLoaderAware;
40  import org.springframework.core.OrderComparator;
41  import org.springframework.core.io.Resource;
42  import org.springframework.util.Assert;
43  import org.springframework.util.ClassUtils;
44  import org.springframework.util.StringUtils;
45  import org.springframework.web.context.ServletContextAware;
46  import org.springframework.web.context.WebApplicationContext;
47  
48  /**
49   * Helper class for for loading default implementations of an interface. Encapsulates a properties object, which
50   * contains strategy interface names as keys, and comma-separated class names as values.
51   * <p/>
52   * Simulates the {@link BeanFactory normal lifecycle} for beans, by calling {@link
53   * BeanFactoryAware#setBeanFactory(BeanFactory)}, {@link ApplicationContextAware#setApplicationContext(ApplicationContext)},
54   * etc.
55   *
56   * @author Arjen Poutsma
57   * @since 1.0.0
58   */
59  public class DefaultStrategiesHelper {
60  
61      /** Keys are strategy interface names, values are implementation class names. */
62      private Properties defaultStrategies;
63  
64      /** Initializes a new instance of the <code>DefaultStrategiesHelper</code> based on the given set of properties. */
65      public DefaultStrategiesHelper(Properties defaultStrategies) {
66          Assert.notNull(defaultStrategies, "defaultStrategies must not be null");
67          this.defaultStrategies = defaultStrategies;
68      }
69  
70      /** Initializes a new instance of the <code>DefaultStrategiesHelper</code> based on the given resource. */
71      public DefaultStrategiesHelper(Resource resource) throws IllegalStateException {
72          try {
73              InputStream is = resource.getInputStream();
74              defaultStrategies = new Properties();
75              try {
76                  defaultStrategies.load(is);
77              }
78              finally {
79                  is.close();
80              }
81          }
82          catch (IOException ex) {
83              throw new IllegalStateException("Could not load '" + resource + "': " + ex.getMessage());
84          }
85      }
86  
87      /**
88       * Create a list of strategy objects for the given strategy interface. Strategies are retrieved from the
89       * <code>Properties</code> object given at construction-time.
90       *
91       * @param strategyInterface the strategy interface
92       * @return a list of corresponding strategy objects
93       * @throws BeansException if initialization failed
94       */
95      public List getDefaultStrategies(Class strategyInterface) throws BeanInitializationException {
96          return getDefaultStrategies(strategyInterface, null);
97      }
98  
99      /**
100      * Create a list of strategy objects for the given strategy interface. Strategies are retrieved from the
101      * <code>Properties</code> object given at construction-time. It instantiates the strategy objects and satisifies
102      * <code>ApplicationContextAware</code> with the supplied context if necessary.
103      *
104      * @param strategyInterface  the strategy interface
105      * @param applicationContext used to satisfy strategies that are application context aware, may be
106      *                           <code>null</code>
107      * @return a list of corresponding strategy objects
108      * @throws BeansException if initialization failed
109      */
110     public List getDefaultStrategies(Class strategyInterface, ApplicationContext applicationContext)
111             throws BeanInitializationException {
112         String key = strategyInterface.getName();
113         try {
114             List result = null;
115             String value = defaultStrategies.getProperty(key);
116             if (value != null) {
117                 String[] classNames = StringUtils.commaDelimitedListToStringArray(value);
118                 result = new ArrayList(classNames.length);
119                 for (int i = 0; i < classNames.length; i++) {
120                     Class clazz = ClassUtils.forName(classNames[i]);
121                     Object strategy = instantiateBean(clazz, applicationContext);
122                     result.add(strategy);
123                 }
124             }
125             else {
126                 result = Collections.EMPTY_LIST;
127             }
128             Collections.sort(result, new OrderComparator());
129             return result;
130         }
131         catch (ClassNotFoundException ex) {
132             throw new BeanInitializationException("Could not find default strategy class for interface [" + key + "]",
133                     ex);
134         }
135     }
136 
137     /** Instantiates the given bean, simulating the standard bean lifecycle. */
138     private Object instantiateBean(Class clazz, ApplicationContext applicationContext) {
139         Object strategy = BeanUtils.instantiateClass(clazz);
140         if (strategy instanceof BeanNameAware) {
141             BeanNameAware beanNameAware = (BeanNameAware) strategy;
142             beanNameAware.setBeanName(clazz.getName());
143         }
144         if (applicationContext != null) {
145             if (strategy instanceof BeanFactoryAware) {
146                 ((BeanFactoryAware) strategy).setBeanFactory(applicationContext);
147             }
148             if (strategy instanceof ResourceLoaderAware) {
149                 ((ResourceLoaderAware) strategy).setResourceLoader(applicationContext);
150             }
151             if (strategy instanceof ApplicationEventPublisherAware) {
152                 ((ApplicationEventPublisherAware) strategy).setApplicationEventPublisher(applicationContext);
153             }
154             if (strategy instanceof MessageSourceAware) {
155                 ((MessageSourceAware) strategy).setMessageSource(applicationContext);
156             }
157             if (strategy instanceof ApplicationContextAware) {
158                 ApplicationContextAware applicationContextAware = (ApplicationContextAware) strategy;
159                 applicationContextAware.setApplicationContext(applicationContext);
160             }
161             if (applicationContext instanceof WebApplicationContext && strategy instanceof ServletContextAware) {
162                 ServletContext servletContext = ((WebApplicationContext) applicationContext).getServletContext();
163                 ((ServletContextAware) strategy).setServletContext(servletContext);
164             }
165         }
166         if (strategy instanceof InitializingBean) {
167             InitializingBean initializingBean = (InitializingBean) strategy;
168             try {
169                 initializingBean.afterPropertiesSet();
170             }
171             catch (Throwable ex) {
172                 throw new BeanCreationException("Invocation of init method failed", ex);
173             }
174         }
175         return strategy;
176     }
177 
178     /**
179      * Return the default strategy object for the given strategy interface.
180      *
181      * @param strategyInterface the strategy interface
182      * @return the corresponding strategy object
183      * @throws BeansException if initialization failed
184      * @see #getDefaultStrategies
185      */
186     public Object getDefaultStrategy(Class strategyInterface) throws BeanInitializationException {
187         return getDefaultStrategy(strategyInterface, null);
188     }
189 
190     /**
191      * Return the default strategy object for the given strategy interface.
192      * <p/>
193      * Delegates to {@link #getDefaultStrategies(Class,ApplicationContext)}, expecting a single object in the list.
194      *
195      * @param strategyInterface  the strategy interface
196      * @param applicationContext used to satisfy strategies that are application context aware, may be
197      *                           <code>null</code>
198      * @return the corresponding strategy object
199      * @throws BeansException if initialization failed
200      */
201     public Object getDefaultStrategy(Class strategyInterface, ApplicationContext applicationContext)
202             throws BeanInitializationException {
203         List result = getDefaultStrategies(strategyInterface, applicationContext);
204         if (result.size() != 1) {
205             throw new BeanInitializationException(
206                     "Could not find exactly 1 strategy for interface [" + strategyInterface.getName() + "]");
207         }
208         return result.get(0);
209     }
210 
211 }