View Javadoc
1   /**
2    * This file Copyright (c) 2003-2015 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.cms.beans.config;
35  
36  import info.magnolia.cms.core.Content;
37  import info.magnolia.cms.core.DefaultContent;
38  import info.magnolia.cms.util.ObservationUtil;
39  import info.magnolia.cms.util.SystemContentWrapper;
40  import info.magnolia.context.MgnlContext;
41  import info.magnolia.repository.RepositoryConstants;
42  
43  import java.util.ArrayList;
44  import java.util.HashMap;
45  import java.util.HashSet;
46  import java.util.Iterator;
47  import java.util.List;
48  import java.util.Map;
49  import java.util.Set;
50  
51  import javax.jcr.ItemNotFoundException;
52  import javax.jcr.Node;
53  import javax.jcr.RepositoryException;
54  import javax.jcr.Session;
55  import javax.jcr.observation.EventIterator;
56  import javax.jcr.observation.EventListener;
57  
58  import org.slf4j.Logger;
59  import org.slf4j.LoggerFactory;
60  
61  /**
62   * A lot of "manager" objects are observed. Will mean that they reload the registered content after the content was changed. To
63   * centralize this code we use this abstract manager. A subclass will implement onRegister and onClear.
64   */
65  public abstract class ObservedManager {
66      protected final Logger log = LoggerFactory.getLogger(getClass());
67  
68      /**
69       * UUIDs and paths of the registered main nodes. They will get registered again after a change.
70       */
71      protected Set<String> registeredUUIDs = new HashSet<String>();
72      private Map<String, String> UUIDToPathMap = new HashMap<String, String>();
73  
74      /**
75       * Register a node. The uuid and path are cached and then onRegister() called.
76       *
77       * @param node the node to register
78       */
79      public synchronized void register(Content node) {
80          if (node == null) {
81              log.warn("Tried to register a non-existing node!");
82              return;
83          }
84  
85          ObservationUtil.registerDeferredChangeListener(RepositoryConstants.CONFIG, node.getHandle(), new EventListener() {
86  
87              @Override
88              public void onEvent(EventIterator events) {
89                  reload();
90              }
91          }, 1000, 5000);
92  
93          try {
94              registeredUUIDs.add(node.getUUID());
95              UUIDToPathMap.put(node.getUUID(), node.getHandle());
96              onRegister(new SystemContentWrapper(node));
97          } catch (Exception e) {
98              log.warn("Was not able to register [{}]", node.getHandle(), e);
99          }
100     }
101 
102     /**
103      * Calls onClear and reregister the nodes by calling onRegister.
104      */
105     public synchronized void reload() {
106         // Call onClear and reregister the nodes by calling onRegister
107         onClear();
108 
109         Session session = null;
110         try {
111             session = MgnlContext.getSystemContext().getJCRSession(RepositoryConstants.CONFIG);
112         } catch (RepositoryException e) {
113             throw new RuntimeException(e);
114         }
115 
116         // copy to avoid ConcurrentModificationException since the list get changed during iteration
117         List<String> uuidsAndPaths = new ArrayList<String>(registeredUUIDs);
118 
119         for (Iterator<String> iter = uuidsAndPaths.iterator(); iter.hasNext(); ) {
120             String uuid = iter.next();
121             try {
122                 Node node = getNodeByIdentifierOrPath(session, uuid, UUIDToPathMap.get(uuid));
123                 reload(new DefaultContent(node));
124             } catch (Exception e) {
125                 registeredUUIDs.remove(uuid);
126                 UUIDToPathMap.remove(uuid);
127                 log.warn("Can't reload the node with uuid [{}] and path [{}]", uuid, UUIDToPathMap.get(uuid));
128             }
129         }
130         return;
131     }
132 
133     /**
134      * Get a node by uuid, or failing that, by its path.
135      *
136      * @return The node with the specified UUID, or failing that, the specified path.
137      * @throws RepositoryException if node cannot be located by either UUID or path.
138      */
139     protected static Node getNodeByIdentifierOrPath(Session session, String uuid, String path) throws RepositoryException {
140         Node node = null;
141 
142         try {
143             node = session.getNodeByIdentifier(uuid);
144         } catch (ItemNotFoundException e) {
145             node = session.getNode(path);
146         }
147 
148         return node;
149     }
150 
151     /**
152      * Reload a specific node.
153      */
154     protected void reload(Content node) {
155         onRegister(node);
156     }
157 
158     /**
159      * Clears the registered UUIDs and calls onClear().
160      */
161     public void clear() {
162         this.registeredUUIDs.clear();
163         this.UUIDToPathMap.clear();
164         onClear();
165     }
166 
167     /**
168      * Registers a node.
169      */
170     protected abstract void onRegister(Content node);
171 
172     /**
173      * The implementor should clear everything. If needed the nodes will get registered.
174      */
175     protected abstract void onClear();
176 
177 }