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