PageRenderTime 4637ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/extensions/struts2/src/com/google/inject/struts2/GuiceObjectFactory.java

https://gitlab.com/metamorphiccode/guice
Java | 247 lines | 173 code | 36 blank | 38 comment | 19 complexity | 75fee3940f765d33bb85cda08c5540e6 MD5 | raw file
  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. package com.google.inject.struts2;
  17. import com.google.inject.AbstractModule;
  18. import com.google.inject.Binder;
  19. import com.google.inject.Guice;
  20. import com.google.inject.Injector;
  21. import com.google.inject.Module;
  22. import com.google.inject.internal.Annotations;
  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.lang.annotation.Annotation;
  31. import java.util.ArrayList;
  32. import java.util.HashSet;
  33. import java.util.List;
  34. import java.util.Map;
  35. import java.util.Set;
  36. import java.util.logging.Logger;
  37. /**
  38. * @deprecated Use {@link com.google.inject.struts2.Struts2Factory} instead.
  39. */
  40. @Deprecated
  41. public class GuiceObjectFactory extends ObjectFactory {
  42. static final Logger logger =
  43. Logger.getLogger(GuiceObjectFactory.class.getName());
  44. Module module;
  45. volatile Injector injector;
  46. boolean developmentMode = false;
  47. List<ProvidedInterceptor> interceptors
  48. = new ArrayList<ProvidedInterceptor>();
  49. @Override
  50. public boolean isNoArgConstructorRequired() {
  51. return false;
  52. }
  53. @Inject(value = "guice.module", required = false)
  54. void setModule(String moduleClassName) {
  55. try {
  56. // Instantiate user's module.
  57. @SuppressWarnings({"unchecked"})
  58. Class<? extends Module> moduleClass =
  59. (Class<? extends Module>) Class.forName(moduleClassName);
  60. this.module = moduleClass.newInstance();
  61. } catch (Exception e) {
  62. throw new RuntimeException(e);
  63. }
  64. }
  65. @Inject(value = "struts.devMode", required = false)
  66. void setDevelopmentMode(String developmentMode) {
  67. this.developmentMode = developmentMode.trim().equals("true");
  68. }
  69. Set<Class<?>> boundClasses = new HashSet<Class<?>>();
  70. public Class getClassInstance(String name) throws ClassNotFoundException {
  71. Class<?> clazz = super.getClassInstance(name);
  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. boundClasses.add(clazz);
  82. } catch (Throwable t) {
  83. // Struts should still work even though some classes aren't in the
  84. // classpath. It appears we always get the exception here when
  85. // this is the case.
  86. return clazz;
  87. }
  88. }
  89. }
  90. }
  91. return clazz;
  92. }
  93. @SuppressWarnings("unchecked")
  94. public Object buildBean(Class clazz, Map extraContext) {
  95. if (injector == null) {
  96. synchronized (this) {
  97. if (injector == null) {
  98. createInjector();
  99. }
  100. }
  101. }
  102. return injector.getInstance(clazz);
  103. }
  104. private void createInjector() {
  105. try {
  106. logger.info("Creating injector...");
  107. this.injector = Guice.createInjector(new AbstractModule() {
  108. protected void configure() {
  109. // Install default servlet bindings.
  110. install(new ServletModule());
  111. // Install user's module.
  112. if (module != null) {
  113. logger.info("Installing " + module + "...");
  114. install(module);
  115. }
  116. else {
  117. logger.info("No module found. Set 'guice.module' to a Module "
  118. + "class name if you'd like to use one.");
  119. }
  120. // Tell the injector about all the action classes, etc., so it
  121. // can validate them at startup.
  122. for (Class<?> boundClass : boundClasses) {
  123. // TODO: Set source from Struts XML.
  124. bind(boundClass);
  125. }
  126. // Validate the interceptor class.
  127. for (ProvidedInterceptor interceptor : interceptors) {
  128. interceptor.validate(binder());
  129. }
  130. }
  131. });
  132. // Inject interceptors.
  133. for (ProvidedInterceptor interceptor : interceptors) {
  134. interceptor.inject();
  135. }
  136. } catch (Throwable t) {
  137. t.printStackTrace();
  138. System.exit(1);
  139. }
  140. logger.info("Injector created successfully.");
  141. }
  142. @SuppressWarnings("unchecked")
  143. public Interceptor buildInterceptor(InterceptorConfig interceptorConfig,
  144. Map interceptorRefParams) throws ConfigurationException {
  145. // Ensure the interceptor class is present.
  146. Class<? extends Interceptor> interceptorClass;
  147. try {
  148. interceptorClass = getClassInstance(interceptorConfig.getClassName());
  149. } catch (ClassNotFoundException e) {
  150. throw new RuntimeException(e);
  151. }
  152. ProvidedInterceptor providedInterceptor = new ProvidedInterceptor(
  153. interceptorConfig, interceptorRefParams, interceptorClass);
  154. interceptors.add(providedInterceptor);
  155. return providedInterceptor;
  156. }
  157. Interceptor superBuildInterceptor(InterceptorConfig interceptorConfig,
  158. Map interceptorRefParams) throws ConfigurationException {
  159. return super.buildInterceptor(interceptorConfig, interceptorRefParams);
  160. }
  161. class ProvidedInterceptor implements Interceptor {
  162. final InterceptorConfig config;
  163. final Map params;
  164. final Class<? extends Interceptor> interceptorClass;
  165. Interceptor delegate;
  166. ProvidedInterceptor(InterceptorConfig config, Map params,
  167. Class<? extends Interceptor> interceptorClass) {
  168. this.config = config;
  169. this.params = params;
  170. this.interceptorClass = interceptorClass;
  171. }
  172. void validate(Binder binder) {
  173. // TODO: Set source from Struts XML.
  174. if (hasScope(interceptorClass)) {
  175. binder.addError("Scoping interceptors is not currently supported."
  176. + " Please remove the scope annotation from "
  177. + interceptorClass.getName() + ".");
  178. }
  179. // Make sure it implements Interceptor.
  180. if (!Interceptor.class.isAssignableFrom(interceptorClass)) {
  181. binder.addError(interceptorClass.getName() + " must implement "
  182. + Interceptor.class.getName() + ".");
  183. }
  184. }
  185. void inject() {
  186. delegate = superBuildInterceptor(config, params);
  187. }
  188. public void destroy() {
  189. if (null != delegate) {
  190. delegate.destroy();
  191. }
  192. }
  193. public void init() {
  194. throw new AssertionError();
  195. }
  196. public String intercept(ActionInvocation invocation) throws Exception {
  197. return delegate.intercept(invocation);
  198. }
  199. }
  200. /**
  201. * Returns true if the given class has a scope annotation.
  202. */
  203. private static boolean hasScope(Class<? extends Interceptor> interceptorClass) {
  204. for (Annotation annotation : interceptorClass.getAnnotations()) {
  205. if (Annotations.isScopeAnnotation(annotation.annotationType())) {
  206. return true;
  207. }
  208. }
  209. return false;
  210. }
  211. }