KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > scripting > support > ScriptFactoryPostProcessor


1 /*
2  * Copyright 2002-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.scripting.support;
18
19 import java.util.HashMap JavaDoc;
20 import java.util.Iterator JavaDoc;
21 import java.util.Map JavaDoc;
22
23 import net.sf.cglib.asm.Type;
24 import net.sf.cglib.core.Signature;
25 import net.sf.cglib.proxy.InterfaceMaker;
26 import org.apache.commons.logging.Log;
27 import org.apache.commons.logging.LogFactory;
28
29 import org.springframework.aop.TargetSource;
30 import org.springframework.aop.framework.AopInfrastructureBean;
31 import org.springframework.aop.framework.ProxyFactory;
32 import org.springframework.aop.support.DelegatingIntroductionInterceptor;
33 import org.springframework.beans.BeanUtils;
34 import org.springframework.beans.PropertyValue;
35 import org.springframework.beans.factory.BeanClassLoaderAware;
36 import org.springframework.beans.factory.BeanDefinitionStoreException;
37 import org.springframework.beans.factory.BeanFactory;
38 import org.springframework.beans.factory.BeanFactoryAware;
39 import org.springframework.beans.factory.DisposableBean;
40 import org.springframework.beans.factory.config.BeanDefinition;
41 import org.springframework.beans.factory.config.BeanPostProcessor;
42 import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
43 import org.springframework.beans.factory.support.AbstractBeanFactory;
44 import org.springframework.beans.factory.support.DefaultListableBeanFactory;
45 import org.springframework.beans.factory.support.RootBeanDefinition;
46 import org.springframework.context.ResourceLoaderAware;
47 import org.springframework.core.Conventions;
48 import org.springframework.core.Ordered;
49 import org.springframework.core.io.DefaultResourceLoader;
50 import org.springframework.core.io.ResourceLoader;
51 import org.springframework.scripting.ScriptFactory;
52 import org.springframework.scripting.ScriptSource;
53 import org.springframework.util.Assert;
54 import org.springframework.util.ClassUtils;
55 import org.springframework.util.ObjectUtils;
56 import org.springframework.util.StringUtils;
57
58 /**
59  * {@link org.springframework.beans.factory.config.BeanPostProcessor} that
60  * handles {@link org.springframework.scripting.ScriptFactory} definitions,
61  * replacing each factory with the actual scripted Java object generated by it.
62  *
63  * <p>This is similar to the
64  * {@link org.springframework.beans.factory.FactoryBean} mechanism, but is
65  * specifically tailored for scripts and not built into Spring's core
66  * container itself but rather implemented as an extension.
67  *
68  * <p><b>NOTE:</b> The most important characteristic of this post-processor
69  * is that constructor arguments are applied to the
70  * {@link org.springframework.scripting.ScriptFactory} instance
71  * while bean property values are applied to the generated scripted object.
72  * Typically, constructor arguments include a script source locator and
73  * potentially script interfaces, while bean property values include
74  * references and config values to inject into the scripted object itself.
75  *
76  * <p>The following {@link ScriptFactoryPostProcessor} will automatically
77  * be applied to the two
78  * {@link org.springframework.scripting.ScriptFactory} definitions below.
79  * At runtime, the actual scripted objects will be exposed for
80  * "bshMessenger" and "groovyMessenger", rather than the
81  * {@link org.springframework.scripting.ScriptFactory} instances. Both of
82  * those are supposed to be castable to the example's <code>Messenger</code>
83  * interfaces here.
84  *
85  * <pre class="code">&lt;bean class="org.springframework.scripting.support.ScriptFactoryPostProcessor"/&gt;
86  *
87  * &lt;bean id="bshMessenger" class="org.springframework.scripting.bsh.BshScriptFactory"&gt;
88  * &lt;constructor-arg value="classpath:mypackage/Messenger.bsh"/&gt;
89  * &lt;constructor-arg value="mypackage.Messenger"/&gt;
90  * &lt;property name="message" value="Hello World!"/&gt;
91  * &lt;/bean&gt;
92  *
93  * &lt;bean id="groovyMessenger" class="org.springframework.scripting.bsh.GroovyScriptFactory"&gt;
94  * &lt;constructor-arg value="classpath:mypackage/Messenger.groovy"/&gt;
95  * &lt;property name="message" value="Hello World!"/&gt;
96  * &lt;/bean&gt;</pre>
97  *
98  * <p><b>NOTE:</b> Please note that the above excerpt from a Spring
99  * XML bean definition file uses just the &lt;bean/&gt;-style syntax
100  * (in an effort to illustrate using the {@link ScriptFactoryPostProcessor} itself).
101  * In reality, you would never create a &lt;bean/&gt; definition for a
102  * {@link ScriptFactoryPostProcessor} explicitly; rather you would import the
103  * tags from the <code>'lang'</code> namespace and simply create scripted
104  * beans using the tags in that namespace... as part of doing so, a
105  * {@link ScriptFactoryPostProcessor} will implicitly be created for you.
106  *
107  * <p>The Spring reference documentation contains numerous examples of using
108  * tags in the <code>'lang'</code> namespace; by way of an example, find below
109  * a Groovy-backed bean defined using the <code>'lang:groovy'</code> tag.
110  *
111  * <pre class="code">
112  * &lt;?xml version="1.0" encoding="UTF-8"?&gt;
113  * &lt;beans xmlns="http://www.springframework.org/schema/beans"
114  * xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
115  * xmlns:lang="http://www.springframework.org/schema/lang"&gt;
116  *
117  * &lt;!-- this is the bean definition for the Groovy-backed Messenger implementation --&gt;
118  * &lt;lang:groovy id="messenger" script-source="classpath:Messenger.groovy"&gt;
119  * &lt;lang:property name="message" value="I Can Do The Frug" /&gt;
120  * &lt;/lang:groovy&gt;
121  *
122  * &lt;!-- an otherwise normal bean that will be injected by the Groovy-backed Messenger --&gt;
123  * &lt;bean id="bookingService" class="x.y.DefaultBookingService"&gt;
124  * &lt;property name="messenger" ref="messenger" /&gt;
125  * &lt;/bean&gt;
126  *
127  * &lt;/beans&gt;</pre>
128  *
129  * @author Juergen Hoeller
130  * @author Rob Harrop
131  * @author Rick Evans
132  * @since 2.0
133  */

134 public class ScriptFactoryPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
135         implements BeanClassLoaderAware, BeanFactoryAware, ResourceLoaderAware, DisposableBean, Ordered {
136
137     /**
138      * The {@link org.springframework.core.io.Resource}-style prefix that denotes
139      * an inline script.
140      * <p>An inline script is a script that is defined right there in the (typically XML)
141      * configuration, as opposed to being defined in an external file.
142      */

143     public static final String JavaDoc INLINE_SCRIPT_PREFIX = "inline:";
144
145     public static final String JavaDoc REFRESH_CHECK_DELAY_ATTRIBUTE =
146             Conventions.getQualifiedAttributeName(ScriptFactoryPostProcessor.class, "refreshCheckDelay");
147
148     private static final String JavaDoc SCRIPT_FACTORY_NAME_PREFIX = "scriptFactory.";
149
150     private static final String JavaDoc SCRIPTED_OBJECT_NAME_PREFIX = "scriptedObject.";
151
152
153     /** Logger available to subclasses */
154     protected final Log logger = LogFactory.getLog(getClass());
155
156     private long defaultRefreshCheckDelay = -1;
157
158     private ClassLoader JavaDoc beanClassLoader = ClassUtils.getDefaultClassLoader();
159
160     private AbstractBeanFactory beanFactory;
161
162     private ResourceLoader resourceLoader = new DefaultResourceLoader();
163
164     final DefaultListableBeanFactory scriptBeanFactory = new DefaultListableBeanFactory();
165
166     /** Map from bean name String to ScriptSource object */
167     private final Map JavaDoc scriptSourceCache = new HashMap JavaDoc();
168
169
170     /**
171      * Set the delay between refresh checks, in milliseconds.
172      * Default is -1, indicating no refresh checks at all.
173      * <p>Note that an actual refresh will only happen when
174      * the {@link org.springframework.scripting.ScriptSource} indicates
175      * that it has been modified.
176      * @see org.springframework.scripting.ScriptSource#isModified()
177      */

178     public void setDefaultRefreshCheckDelay(long defaultRefreshCheckDelay) {
179         this.defaultRefreshCheckDelay = defaultRefreshCheckDelay;
180     }
181
182     public void setBeanClassLoader(ClassLoader JavaDoc classLoader) {
183         this.beanClassLoader = classLoader;
184     }
185
186     public void setBeanFactory(BeanFactory beanFactory) {
187         if (!(beanFactory instanceof AbstractBeanFactory)) {
188             throw new IllegalStateException JavaDoc(
189                     "ScriptFactoryPostProcessor must run in AbstractBeanFactory, not in " + beanFactory);
190         }
191         this.beanFactory = (AbstractBeanFactory) beanFactory;
192
193         // Required so that references (up container hierarchies) are correctly resolved.
194
this.scriptBeanFactory.setParentBeanFactory(this.beanFactory);
195
196         // Required so that all BeanPostProcessors, Scopes, etc become available.
197
this.scriptBeanFactory.copyConfigurationFrom(this.beanFactory);
198
199         // Filter out BeanPostProcessors that are part of the AOP infrastructure,
200
// since those are only meant to apply to beans defined in the original factory.
201
for (Iterator JavaDoc it = this.scriptBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) {
202             BeanPostProcessor postProcessor = (BeanPostProcessor) it.next();
203             if (postProcessor instanceof AopInfrastructureBean) {
204                 it.remove();
205             }
206         }
207     }
208
209     public void setResourceLoader(ResourceLoader resourceLoader) {
210         this.resourceLoader = resourceLoader;
211     }
212
213     public int getOrder() {
214         return Integer.MIN_VALUE;
215     }
216
217
218     public Class JavaDoc predictBeanType(Class JavaDoc beanClass, String JavaDoc beanName) {
219         // We only apply special treatment to ScriptFactory implementations here.
220
if (!ScriptFactory.class.isAssignableFrom(beanClass)) {
221             return null;
222         }
223
224         RootBeanDefinition bd = this.beanFactory.getMergedBeanDefinition(beanName);
225         String JavaDoc scriptFactoryBeanName = SCRIPT_FACTORY_NAME_PREFIX + beanName;
226         String JavaDoc scriptedObjectBeanName = SCRIPTED_OBJECT_NAME_PREFIX + beanName;
227         prepareScriptBeans(bd, scriptFactoryBeanName, scriptedObjectBeanName);
228
229         ScriptFactory scriptFactory =
230                 (ScriptFactory) this.scriptBeanFactory.getBean(scriptFactoryBeanName, ScriptFactory.class);
231         ScriptSource scriptSource =
232                 getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator());
233         Class JavaDoc[] interfaces = scriptFactory.getScriptInterfaces();
234
235         Class JavaDoc scriptedType = null;
236         try {
237             scriptedType = scriptFactory.getScriptedObjectType(scriptSource);
238         }
239         catch (Exception JavaDoc ex) {
240             if (logger.isDebugEnabled()) {
241                 logger.debug("Could not determine the scripted object type for script factory [" + scriptFactory + "]", ex);
242             }
243         }
244
245         if (scriptedType != null) {
246             return scriptedType;
247         }
248         else if (ObjectUtils.isEmpty(interfaces)) {
249             if (bd.isSingleton()) {
250                 return this.scriptBeanFactory.getBean(scriptedObjectBeanName).getClass();
251             }
252             else {
253                 return null;
254             }
255         }
256         else {
257             return (interfaces.length == 1 ? interfaces[0] : createCompositeInterface(interfaces));
258         }
259     }
260
261     public Object JavaDoc postProcessBeforeInstantiation(Class JavaDoc beanClass, String JavaDoc beanName) {
262         // We only apply special treatment to ScriptFactory implementations here.
263
if (!ScriptFactory.class.isAssignableFrom(beanClass)) {
264             return null;
265         }
266
267         RootBeanDefinition bd = this.beanFactory.getMergedBeanDefinition(beanName);
268         String JavaDoc scriptFactoryBeanName = SCRIPT_FACTORY_NAME_PREFIX + beanName;
269         String JavaDoc scriptedObjectBeanName = SCRIPTED_OBJECT_NAME_PREFIX + beanName;
270         prepareScriptBeans(bd, scriptFactoryBeanName, scriptedObjectBeanName);
271
272         long refreshCheckDelay = resolveRefreshCheckDelay(bd);
273         if (refreshCheckDelay >= 0) {
274             ScriptFactory scriptFactory =
275                     (ScriptFactory) this.scriptBeanFactory.getBean(scriptFactoryBeanName, ScriptFactory.class);
276             ScriptSource scriptSource =
277                     getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator());
278             Class JavaDoc[] interfaces = scriptFactory.getScriptInterfaces();
279             RefreshableScriptTargetSource ts =
280                     new RefreshableScriptTargetSource(this.scriptBeanFactory, scriptedObjectBeanName, scriptSource);
281             ts.setRefreshCheckDelay(refreshCheckDelay);
282             return createRefreshableProxy(ts, interfaces);
283         }
284
285         return this.scriptBeanFactory.getBean(scriptedObjectBeanName);
286     }
287
288
289     /**
290      * Prepare the script beans in the internal BeanFactory that this
291      * post-processor uses. Each original bean definition will be split
292      * into a ScriptFactory definition and a scripted object definition.
293      * @param bd the original bean definition in the main BeanFactory
294      * @param scriptFactoryBeanName the name of the internal ScriptFactory bean
295      * @param scriptedObjectBeanName the name of the internal scripted object bean
296      */

297     protected void prepareScriptBeans(
298             RootBeanDefinition bd, String JavaDoc scriptFactoryBeanName, String JavaDoc scriptedObjectBeanName) {
299
300         // Avoid recreation of the script bean definition in case of a prototype.
301
synchronized (this.scriptBeanFactory) {
302             if (!this.scriptBeanFactory.containsBeanDefinition(scriptedObjectBeanName)) {
303
304                 this.scriptBeanFactory.registerBeanDefinition(
305                         scriptFactoryBeanName, createScriptFactoryBeanDefinition(bd));
306                 ScriptFactory scriptFactory =
307                         (ScriptFactory) this.scriptBeanFactory.getBean(scriptFactoryBeanName, ScriptFactory.class);
308                 ScriptSource scriptSource =
309                         getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator());
310                 Class JavaDoc[] interfaces = scriptFactory.getScriptInterfaces();
311
312                 Class JavaDoc[] scriptedInterfaces = interfaces;
313                 if (scriptFactory.requiresConfigInterface() && !bd.getPropertyValues().isEmpty()) {
314                     PropertyValue[] pvs = bd.getPropertyValues().getPropertyValues();
315                     Class JavaDoc configInterface = createConfigInterface(pvs, interfaces);
316                     scriptedInterfaces = (Class JavaDoc[]) ObjectUtils.addObjectToArray(interfaces, configInterface);
317                 }
318
319                 RootBeanDefinition objectBd = createScriptedObjectBeanDefinition(
320                         bd, scriptFactoryBeanName, scriptSource, scriptedInterfaces);
321                 long refreshCheckDelay = resolveRefreshCheckDelay(bd);
322                 if (refreshCheckDelay >= 0) {
323                     objectBd.setSingleton(false);
324                 }
325
326                 this.scriptBeanFactory.registerBeanDefinition(scriptedObjectBeanName, objectBd);
327             }
328         }
329     }
330
331     /**
332      * Get the refresh check delay for the given {@link ScriptFactory} {@link BeanDefinition}.
333      * If the {@link BeanDefinition} has a
334      * {@link org.springframework.core.AttributeAccessor metadata attribute}
335      * under the key {@link #REFRESH_CHECK_DELAY_ATTRIBUTE} which is a valid {@link Number}
336      * type, then this value is used. Otherwise, the the {@link #defaultRefreshCheckDelay}
337      * value is used.
338      * @param beanDefinition the BeanDefinition to check
339      * @return the refresh check delay
340      */

341     protected long resolveRefreshCheckDelay(BeanDefinition beanDefinition) {
342         long refreshCheckDelay = this.defaultRefreshCheckDelay;
343         Object JavaDoc attributeValue = beanDefinition.getAttribute(REFRESH_CHECK_DELAY_ATTRIBUTE);
344         if (attributeValue instanceof Number JavaDoc) {
345             refreshCheckDelay = ((Number JavaDoc) attributeValue).longValue();
346         }
347         else if (attributeValue instanceof String JavaDoc) {
348             refreshCheckDelay = Long.parseLong((String JavaDoc) attributeValue);
349         }
350         else if (attributeValue != null) {
351             throw new BeanDefinitionStoreException(
352                     "Invalid refresh check delay attribute [" + REFRESH_CHECK_DELAY_ATTRIBUTE +
353                     "] with value [" + attributeValue + "]: needs to be of type Number or String");
354         }
355         return refreshCheckDelay;
356     }
357
358     /**
359      * Create a ScriptFactory bean definition based on the given script definition,
360      * extracting only the definition data that is relevant for the ScriptFactory
361      * (that is, only bean class and constructor arguments).
362      * @param bd the full script bean definition
363      * @return the extracted ScriptFactory bean definition
364      * @see org.springframework.scripting.ScriptFactory
365      */

366     protected RootBeanDefinition createScriptFactoryBeanDefinition(RootBeanDefinition bd) {
367         RootBeanDefinition scriptBd = new RootBeanDefinition();
368         scriptBd.setBeanClassName(bd.getBeanClassName());
369         scriptBd.getConstructorArgumentValues().addArgumentValues(bd.getConstructorArgumentValues());
370         return scriptBd;
371     }
372
373     /**
374      * Obtain a ScriptSource for the given bean, lazily creating it
375      * if not cached already.
376      * @param beanName the name of the scripted bean
377      * @param scriptSourceLocator the script source locator associated with the bean
378      * @return the corresponding ScriptSource instance
379      * @see #convertToScriptSource
380      */

381     protected ScriptSource getScriptSource(String JavaDoc beanName, String JavaDoc scriptSourceLocator) {
382         synchronized (this.scriptSourceCache) {
383             ScriptSource scriptSource = (ScriptSource) this.scriptSourceCache.get(beanName);
384             if (scriptSource == null) {
385                 scriptSource = convertToScriptSource(scriptSourceLocator, this.resourceLoader);
386                 this.scriptSourceCache.put(beanName, scriptSource);
387             }
388             return scriptSource;
389         }
390     }
391
392     /**
393      * Convert the given script source locator to a ScriptSource instance.
394      * <p>By default, supported locators are Spring resource locations
395      * (such as "file:C:/myScript.bsh" or "classpath:myPackage/myScript.bsh")
396      * and inline scripts ("inline:myScriptText...").
397      * @param scriptSourceLocator the script source locator
398      * @param resourceLoader the ResourceLoader to use (if necessary)
399      * @return the ScriptSource instance
400      */

401     protected ScriptSource convertToScriptSource(String JavaDoc scriptSourceLocator, ResourceLoader resourceLoader) {
402         if (scriptSourceLocator.startsWith(INLINE_SCRIPT_PREFIX)) {
403             return new StaticScriptSource(scriptSourceLocator.substring(INLINE_SCRIPT_PREFIX.length()));
404         }
405         else {
406             return new ResourceScriptSource(resourceLoader.getResource(scriptSourceLocator));
407         }
408     }
409
410     /**
411      * Create a config interface for the given bean property values.
412      * <p>This implementation creates the interface via CGLIB's InterfaceMaker,
413      * determining the property types from the given interfaces (as far as possible).
414      * @param pvs the bean property values to create a config interface for
415      * @param interfaces the interfaces to check against (might define
416      * getters corresponding to the setters we're supposed to generate)
417      * @return the config interface
418      * @see net.sf.cglib.proxy.InterfaceMaker
419      * @see org.springframework.beans.BeanUtils#findPropertyType
420      */

421     protected Class JavaDoc createConfigInterface(PropertyValue[] pvs, Class JavaDoc[] interfaces) {
422         Assert.notEmpty(pvs, "Property values must not be empty");
423         InterfaceMaker maker = new InterfaceMaker();
424         for (int i = 0; i < pvs.length; i++) {
425             String JavaDoc propertyName = pvs[i].getName();
426             Class JavaDoc propertyType = BeanUtils.findPropertyType(propertyName, interfaces);
427             String JavaDoc setterName = "set" + StringUtils.capitalize(propertyName);
428             Signature signature = new Signature(setterName, Type.VOID_TYPE, new Type[] {Type.getType(propertyType)});
429             maker.add(signature, new Type[0]);
430         }
431         return maker.create();
432     }
433
434     /**
435      * Create a composite interface Class for the given interfaces,
436      * implementing the given interfaces in one single Class.
437      * <p>The default implementation builds a JDK proxy class
438      * for the given interfaces.
439      * @param interfaces the interfaces to merge
440      * @return the merged interface as Class
441      * @see java.lang.reflect.Proxy#getProxyClass
442      */

443     protected Class JavaDoc createCompositeInterface(Class JavaDoc[] interfaces) {
444         return ClassUtils.createCompositeInterface(interfaces, this.beanClassLoader);
445     }
446
447     /**
448      * Create a bean definition for the scripted object, based on the given script
449      * definition, extracting the definition data that is relevant for the scripted
450      * object (that is, everything but bean class and constructor arguments).
451      * @param bd the full script bean definition
452      * @param scriptFactoryBeanName the name of the internal ScriptFactory bean
453      * @param scriptSource the ScriptSource for the scripted bean
454      * @param interfaces the interfaces that the scripted bean is supposed to implement
455      * @return the extracted ScriptFactory bean definition
456      * @see org.springframework.scripting.ScriptFactory#getScriptedObject
457      */

458     protected RootBeanDefinition createScriptedObjectBeanDefinition(
459             RootBeanDefinition bd, String JavaDoc scriptFactoryBeanName, ScriptSource scriptSource, Class JavaDoc[] interfaces) {
460
461         RootBeanDefinition objectBd = new RootBeanDefinition(bd);
462         objectBd.setFactoryBeanName(scriptFactoryBeanName);
463         objectBd.setFactoryMethodName("getScriptedObject");
464         objectBd.getConstructorArgumentValues().clear();
465         objectBd.getConstructorArgumentValues().addIndexedArgumentValue(0, scriptSource);
466         objectBd.getConstructorArgumentValues().addIndexedArgumentValue(1, interfaces);
467         return objectBd;
468     }
469
470     /**
471      * Create a refreshable proxy for the given AOP TargetSource.
472      * @param ts the refreshable TargetSource
473      * @param interfaces the proxy interfaces (may be <code>null</code> to
474      * indicate proxying of all interfaces implemented by the target class)
475      * @return the generated proxy
476      * @see RefreshableScriptTargetSource
477      */

478     protected Object JavaDoc createRefreshableProxy(TargetSource ts, Class JavaDoc[] interfaces) {
479         ProxyFactory proxyFactory = new ProxyFactory();
480         proxyFactory.setTargetSource(ts);
481
482         if (interfaces == null) {
483             interfaces = ClassUtils.getAllInterfacesForClass(ts.getTargetClass());
484         }
485         proxyFactory.setInterfaces(interfaces);
486
487         DelegatingIntroductionInterceptor introduction = new DelegatingIntroductionInterceptor(ts);
488         introduction.suppressInterface(TargetSource.class);
489         proxyFactory.addAdvice(introduction);
490
491         return proxyFactory.getProxy(this.beanClassLoader);
492     }
493
494
495     /**
496      * Destroy the inner bean factory (used for scripts) on shutdown.
497      */

498     public void destroy() {
499         this.scriptBeanFactory.destroySingletons();
500     }
501
502 }
503
Popular Tags