View Javadoc

1   /**
2    * This file Copyright (c) 2003-2010 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;
35  
36  import info.magnolia.cms.core.Content;
37  import info.magnolia.cms.core.HierarchyManager;
38  import info.magnolia.cms.util.ObservationUtil;
39  import info.magnolia.content2bean.Content2BeanException;
40  import info.magnolia.content2bean.Content2BeanTransformer;
41  import info.magnolia.content2bean.Content2BeanUtil;
42  import info.magnolia.content2bean.TransformationState;
43  import info.magnolia.content2bean.impl.Content2BeanTransformerImpl;
44  import info.magnolia.context.MgnlContext;
45  import org.apache.commons.proxy.ObjectProvider;
46  import org.apache.commons.proxy.factory.cglib.CglibProxyFactory;
47  import org.slf4j.Logger;
48  import org.slf4j.LoggerFactory;
49  
50  import javax.jcr.RepositoryException;
51  import javax.jcr.observation.EventIterator;
52  import javax.jcr.observation.EventListener;
53  import java.lang.reflect.Modifier;
54  import java.util.Map;
55  
56  /**
57   * Generic observed singleton factory.
58   *
59   * @author philipp
60   * @version $Id: $
61   */
62  public class ObservedComponentFactory<T> implements ComponentFactory<T>, EventListener {
63      private static final Logger log = LoggerFactory.getLogger(ObservedComponentFactory.class);
64  
65      private static final int DEFAULT_MAX_DELAY = 5000;
66      private static final int DEFAULT_DELAY = 1000;
67  
68      /**
69       * Repository name used.
70       */
71      private final String repository;
72  
73      /**
74       * Path to the node in the config repository.
75       */
76      private final String path;
77  
78      /**
79       * @deprecated since 4.3 - this should be private - use {@link #getComponentType()} instead.
80       * (rename to "type" once made private)
81       */
82      protected final Class<T> interf;
83  
84      /**
85       * The object delivered by this factory.
86       * @deprecated since 4.3 - this should be private - use {@link #getObservedObject()} instead.
87       */
88      protected T observedObject;
89  
90      public ObservedComponentFactory(String repository, String path, Class<T> type) {
91          this.repository = repository;
92          this.path = path;
93          this.interf = type;
94          load();
95          startObservation(path);
96      }
97  
98      @SuppressWarnings("unchecked") // until commons-proxy becomes generics-aware, we have to ignore this warning
99      public T newInstance() {
100         if (getObservedObject() == null) {
101             // TODO - replace this by a default implementation or some form of null proxy
102             // this only happens if load() did not set observedObject
103             log.warn("An instance of {} couldn't be loaded from {}:{} yet, returning null.", new Object[]{interf, repository, path});
104             return null;
105         }
106 
107         return (T) new CglibProxyFactory().createDelegatorProxy(new ObjectProvider() {
108             public Object getObject() {
109                 return getObservedObject();
110             }
111         }, new Class[]{
112                 // we want to expose the observed object's concrete class and interfaces so that client code can cast if they want 
113                 getObservedObject().getClass()
114         });
115     }
116 
117     protected void startObservation(String handle) {
118         ObservationUtil.registerDeferredChangeListener(repository, handle, this, DEFAULT_DELAY, DEFAULT_MAX_DELAY);
119     }
120 
121     public void onEvent(EventIterator events) {
122         reload();
123     }
124 
125     protected void reload() {
126         load();
127     }
128 
129     protected void load() {
130         final HierarchyManager hm = MgnlContext.getSystemContext().getHierarchyManager(repository);
131         if (hm.isExist(path)) {
132             try {
133                 final Content node = hm.getContent(path);
134                 onRegister(node);
135             } catch (RepositoryException e) {
136                 log.error("Can't read configuration for " + interf + " from [" + repository + ":" + path + "], will return null.", e);
137             }
138         } else {
139             log.debug("{} does not exist, will return a default implementation for {}.", path, interf);
140             instantiateDefault();
141         }
142     }
143 
144     protected void instantiateDefault() {
145         if (isConcrete(interf)) {
146             log.info("{} does not exist, will return a new instance of {}.", path, interf);
147             final ClassFactory classFactory = Classes.getClassFactory();
148             this.observedObject = classFactory.newInstance(interf);
149         } else {
150             log.warn("{} does not exist, default implementation for {} is unknown, will return null.", path, interf);
151         }
152     }
153 
154     protected boolean isConcrete(Class<?> clazz) {
155         return !Modifier.isAbstract(clazz.getModifiers());
156     }
157 
158     protected void onRegister(Content node) {
159         try {
160             final T instance = transformNode(node);
161 
162             if (this.observedObject != null) {
163                 log.info("Re-loaded {} from {}", interf.getName(), node.getHandle());
164             } else {
165                 log.debug("Loading {} from {}", interf.getName(), node.getHandle());
166             }
167             this.observedObject = instance;
168 
169         } catch (Content2BeanException e) {
170             log.error("Can't transform [" + repository + ":" + path + "] to " + interf, e);
171         }
172     }
173 
174     protected T transformNode(Content node) throws Content2BeanException {
175         return (T) Content2BeanUtil.toBean(node, true, getContent2BeanTransformer());
176     }
177 
178     protected Content2BeanTransformer getContent2BeanTransformer() {
179         // we can not discover again the same class we are building
180         return new Content2BeanTransformerImpl() {
181             public Object newBeanInstance(TransformationState state, Map properties) throws Content2BeanException {
182                 if (state.getCurrentType().getType().equals(interf)) {
183                     final ClassFactory classFactory = Classes.getClassFactory();
184                     return classFactory.newInstance(interf);
185                 }
186                 return super.newBeanInstance(state, properties);
187             }
188         };
189     }
190 
191     protected Class<T> getComponentType() {
192         return interf;
193     }
194 
195     /**
196      * Returns the latest converted object observed by this factory.
197      * Since 4.3, if you are using {@link info.magnolia.objectfactory.DefaultClassFactory}, calling this shouldn't be needed,
198      * {@link #newInstance()} returned a proxy, so you'll always see this object.
199      *
200      * @deprecated since 4.3 - {@link info.magnolia.objectfactory.DefaultComponentProvider#newInstance(Class)} returns a proxy of the observed object instead of this factory, so this method shouldn't be needed publicly.
201      */
202     public T getObservedObject() {
203         return this.observedObject;
204     }
205 
206     public String toString() {
207         return super.toString() + ":" + interf + "(Observing: " + repository + ":" + path + ")";
208     }
209 }