View Javadoc

1   /**
2    * This file Copyright (c) 2011 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.objectfactory.guice;
35  
36  import java.lang.reflect.InvocationTargetException;
37  import java.util.Set;
38  import javax.inject.Inject;
39  import javax.inject.Provider;
40  
41  import com.google.common.collect.ImmutableSet;
42  import com.google.common.collect.Sets;
43  import com.google.inject.Injector;
44  import com.google.inject.Key;
45  import com.google.inject.spi.Dependency;
46  import com.google.inject.spi.InjectionPoint;
47  import com.google.inject.spi.ProviderWithDependencies;
48  
49  import info.magnolia.objectfactory.ComponentFactory;
50  import info.magnolia.objectfactory.ComponentFactoryUtil;
51  import info.magnolia.objectfactory.ComponentProvider;
52  
53  /**
54   * Utilities for guice.
55   *
56   * @version $Id$
57   */
58  public class GuiceUtils {
59  
60      public static <T> Provider<T> providerForInstance(final T instance) {
61          return new Provider<T>() {
62              @Override
63              public T get() {
64                  return instance;
65              }
66  
67              @Override
68              public String toString() {
69                  return "Provider for: " + instance.toString();
70              }
71          };
72      }
73  
74      public static <T> Provider<T> providerForComponentFactory(final Class<? extends ComponentFactory<T>> componentFactoryClass) {
75          return new Provider<T>() {
76  
77              @Inject
78              private ComponentProvider componentProvider;
79  
80              @Override
81              public T get() {
82                  try {
83                      ComponentFactory<T> componentFactory = ComponentFactoryUtil.createFactory(componentFactoryClass, componentProvider);
84                      ((GuiceComponentProvider) componentProvider).injectMembers(componentFactory);
85                      T instance = componentFactory.newInstance();
86                      return instance;
87                  } catch (InstantiationException e) {
88                      throw new IllegalStateException("Failed to create ComponentFactory [" + componentFactoryClass + "]", e);
89                  } catch (IllegalAccessException e) {
90                      throw new IllegalStateException("Failed to create ComponentFactory [" + componentFactoryClass + "]", e);
91                  } catch (InvocationTargetException e) {
92                      throw new IllegalStateException("Failed to create ComponentFactory [" + componentFactoryClass + "]", e);
93                  }
94              }
95  
96              @Override
97              public String toString() {
98                  return "ComponentFactory: " + componentFactoryClass.toString();
99              }
100         };
101     }
102 
103     public static <T> Provider<T> providerForComponentFactory(final ComponentFactory<T> componentFactory) {
104 
105         // This method does exactly the same as com.google.inject.util.Providers#guicify
106 
107         // Ensure that we inject all injection points from the delegate provider.
108         Set<InjectionPoint> injectionPoints =
109                 InjectionPoint.forInstanceMethodsAndFields(componentFactory.getClass());
110         if(injectionPoints.isEmpty()) {
111             return new com.google.inject.Provider<T>() {
112                 @Override
113                 public T get() {
114                     return componentFactory.newInstance();
115                 }
116 
117                 @Override
118                 public String toString() {
119                     return "ComponentFactory: " + componentFactory.toString();
120                 }
121             };
122         } else {
123             Set<Dependency<?>> mutableDeps = Sets.newHashSet();
124             for(InjectionPoint ip : injectionPoints) {
125                 mutableDeps.addAll(ip.getDependencies());
126             }
127             final Set<Dependency<?>> dependencies = ImmutableSet.copyOf(mutableDeps);
128             return new ProviderWithDependencies<T>() {
129                 @SuppressWarnings("unused")
130                 @com.google.inject.Inject
131                 void initialize(Injector injector) {
132                     injector.injectMembers(componentFactory);
133                 }
134 
135                 @Override
136                 public Set<Dependency<?>> getDependencies() {
137                     return dependencies;
138                 }
139 
140                 @Override
141                 public T get() {
142                     return componentFactory.newInstance();
143                 }
144 
145                 @Override
146                 public String toString() {
147                     return "ComponentFactory: " + componentFactory.toString();
148                 }
149             };
150         }
151     }
152 
153     public static boolean hasExplicitBindingFor(Injector injector, Class<?> type) {
154         Key<?> key = Key.get(type);
155         Injector target = injector;
156         do {
157             if (target.getBindings().containsKey(key)) {
158                 return true;
159             }
160             target = target.getParent();
161         } while (target != null);
162         return false;
163     }
164 }