KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > google > inject > struts2 > GuiceObjectFactory


1 /**
2  * Copyright (C) 2006 Google Inc.
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 com.google.inject.struts2;
18
19 import com.google.inject.AbstractModule;
20 import com.google.inject.Guice;
21 import com.google.inject.Injector;
22 import com.google.inject.Module;
23 import com.google.inject.servlet.ServletModule;
24 import com.opensymphony.xwork2.ActionInvocation;
25 import com.opensymphony.xwork2.ObjectFactory;
26 import com.opensymphony.xwork2.config.ConfigurationException;
27 import com.opensymphony.xwork2.config.entities.InterceptorConfig;
28 import com.opensymphony.xwork2.inject.Inject;
29 import com.opensymphony.xwork2.interceptor.Interceptor;
30 import java.util.HashSet JavaDoc;
31 import java.util.Map JavaDoc;
32 import java.util.Set JavaDoc;
33 import java.util.logging.Logger JavaDoc;
34
35 public class GuiceObjectFactory extends ObjectFactory {
36
37   static final Logger JavaDoc logger =
38       Logger.getLogger(GuiceObjectFactory.class.getName());
39
40   Module module;
41   Injector injector;
42   boolean developmentMode = false;
43
44   @Override JavaDoc
45   public boolean isNoArgConstructorRequired() {
46     return false;
47   }
48
49   @Inject(value = "guice.module", required = false)
50   void setModule(String JavaDoc moduleClassName) {
51     try {
52       // Instantiate user's module.
53
@SuppressWarnings JavaDoc({"unchecked"})
54       Class JavaDoc<? extends Module> moduleClass =
55           (Class JavaDoc<? extends Module>) Class.forName(moduleClassName);
56       this.module = moduleClass.newInstance();
57     } catch (Exception JavaDoc e) {
58       throw new RuntimeException JavaDoc(e);
59     }
60   }
61
62   @Inject(value = "struts.devMode", required = false)
63   void setDevelopmentMode(String JavaDoc developmentMode) {
64     this.developmentMode = developmentMode.trim().equals("true");
65   }
66
67   Set JavaDoc<Class JavaDoc<?>> boundClasses = new HashSet JavaDoc<Class JavaDoc<?>>();
68
69   public Class JavaDoc getClassInstance(String JavaDoc name) throws ClassNotFoundException JavaDoc {
70     Class JavaDoc<?> clazz = super.getClassInstance(name);
71
72     synchronized (this) {
73       if (injector == null) {
74         // We can only bind each class once.
75
if (!boundClasses.contains(clazz)) {
76           try {
77             // Calling these methods now helps us detect ClassNotFoundErrors
78
// early.
79
clazz.getDeclaredFields();
80             clazz.getDeclaredMethods();
81
82             boundClasses.add(clazz);
83           } catch (Throwable JavaDoc t) {
84             // Struts should still work even though some classes aren't in the
85
// classpath. It appears we always get the exception here when
86
// this is the case.
87
return clazz;
88           }
89         }
90       }
91     }
92
93     return clazz;
94   }
95
96   public Object JavaDoc buildBean(Class JavaDoc clazz, Map JavaDoc extraContext) {
97     synchronized (this) {
98       if (injector == null) {
99         try {
100           logger.info("Creating injector...");
101           this.injector = Guice.createInjector(new AbstractModule() {
102             protected void configure() {
103               install(new ServletModule());
104
105               // Tell the injector about all the action classes, etc., so it
106
// can validate them at startup.
107
for (Class JavaDoc<?> boundClass : boundClasses) {
108                 bind(boundClass);
109               }
110             }
111           });
112         } catch (Throwable JavaDoc t) {
113           t.printStackTrace();
114           System.exit(1);
115         }
116         logger.info("Injector created successfully.");
117       }
118     }
119
120     return injector.getInstance(clazz);
121   }
122
123   public Interceptor buildInterceptor(InterceptorConfig interceptorConfig,
124       Map JavaDoc interceptorRefParams) throws ConfigurationException {
125     try {
126       getClassInstance(interceptorConfig.getClassName());
127     } catch (ClassNotFoundException JavaDoc e) {
128       throw new RuntimeException JavaDoc(e);
129     }
130
131     // Defer the creation of interceptors so that we don't have to create the
132
// injector until we've bound all the actions. This enables us to
133
// validate all the dependencies at once.
134
return new LazyLoadedInterceptor(interceptorConfig, interceptorRefParams);
135   }
136
137   Interceptor superBuildInterceptor(InterceptorConfig interceptorConfig,
138       Map JavaDoc interceptorRefParams) throws ConfigurationException {
139     return super.buildInterceptor(interceptorConfig, interceptorRefParams);
140   }
141
142   class LazyLoadedInterceptor implements Interceptor {
143
144     final InterceptorConfig config;
145     final Map JavaDoc params;
146
147     LazyLoadedInterceptor(InterceptorConfig config, Map JavaDoc params) {
148       this.config = config;
149       this.params = params;
150     }
151
152     Interceptor delegate = null;
153
154     synchronized Interceptor getDelegate() {
155       if (delegate == null) {
156         delegate = superBuildInterceptor(config, params);
157         delegate.init();
158       }
159       return delegate;
160     }
161
162     public void destroy() {
163       getDelegate().destroy();
164     }
165
166     public void init() {
167       throw new AssertionError JavaDoc();
168     }
169
170     public String JavaDoc intercept(ActionInvocation invocation) throws Exception JavaDoc {
171       return getDelegate().intercept(invocation);
172     }
173   }
174 }
175
Popular Tags