View Javadoc
1   /**
2    * This file Copyright (c) 2015-2018 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.resourceloader;
35  
36  import info.magnolia.resourceloader.util.ResourceTreeWalker;
37  
38  import java.io.BufferedReader;
39  import java.io.IOException;
40  import java.io.InputStream;
41  import java.io.InputStreamReader;
42  import java.io.Reader;
43  import java.nio.charset.Charset;
44  import java.util.List;
45  import java.util.Set;
46  
47  import org.slf4j.Logger;
48  import org.slf4j.LoggerFactory;
49  
50  import com.google.common.collect.Sets;
51  
52  /**
53   * Exposes methods that {@link AbstractResource} simply delegates to. Consequently, one only has to implement and
54   * test AbstractResourceOrigin's methods, while navigation still happens naturally through the Resource methods.
55   * AbstractResource implementations are merely vehicles for the underlying resource.
56   *
57   * @param <P> Subclasses of AbstractResourceOrigin are expected to produce {@link Resource} instances which are subclasses of {@link AbstractResource}.
58   */
59  public abstract class AbstractResourceOrigin<P extends AbstractResource> implements ResourceOrigin<P> {
60  
61      private static final Logger log = LoggerFactory.getLogger(AbstractResourceOrigin.class);
62  
63      private final String name;
64  
65      private final Set<ResourceChangeHandler> resourceChangeHandlers = Sets.newConcurrentHashSet();
66  
67      private boolean isResourceMonitoringInitialized = false;
68  
69      protected AbstractResourceOrigin(String name) {
70          this.name = name;
71      }
72  
73      @Override
74      public String getName() {
75          return name;
76      }
77  
78      @Override
79      public void traverseWith(ResourceVisitor visitor) {
80          new ResourceTreeWalker(visitor).traverse(getRoot());
81      }
82  
83      /**
84       * @deprecated since 5.4.6 - use {@link #registerResourceChangeHandler(ResourceChangeHandler)} instead. See {@link ResourceOrigin#watchForChanges(ResourceVisitor)} JavaDoc for more details
85       */
86      @Override
87      @Deprecated
88      public void watchForChanges(final ResourceVisitor visitor) {
89          /**
90           * In order to still support resource change monitoring via the deprecated API we register a {@link ResourceChangeHandler resource change handler}
91           * which wraps a provided {@link ResourceVisitor} and delegates to it.
92           */
93          registerResourceChangeHandler(new ResourceChangeHandler() {
94              @Override
95              public void onResourceChanged(ResourceOriginChange change) {
96                  switch (change.getType()) {
97                  case MODIFIED: case ADDED:
98                      try {
99                          final Resource resource = getByPath(change.getRelatedResourcePath());
100                         if (resource.isDirectory()) {
101                             visitor.visitDirectory(resource);
102                         } else {
103                             visitor.visitFile(resource);
104                         }
105                     } catch (ResourceNotFoundException e) {
106                         log.error("Failed to dispatch resource change via deprecated ResourceVisitor for resource at [{}]: {}. Invoking visitor for a resource stub object", change.getRelatedResourcePath(), e.getMessage(), e);
107                         visitor.visitFile(ResourceStub.withPath(change.getRelatedResourcePath()));
108                     }
109                     break;
110                 case REMOVED:
111                     visitor.visitFile(ResourceStub.withPath(change.getRelatedResourcePath()));
112                     break;
113                 }
114             }
115         });
116     }
117 
118     @Override
119     public ResourceChangeHandlerRegistration registerResourceChangeHandler(ResourceChangeHandler changeHandler) {
120         resourceChangeHandlers.add(changeHandler);
121 
122         if (!isResourceMonitoringInitialized) {
123             isResourceMonitoringInitialized = true;
124             initializeResourceChangeMonitoring();
125         }
126 
127         return new SimpleChangeHandlerRegistration(changeHandler);
128     }
129 
130     public final void dispatchResourceChange(ResourceOriginChange change) {
131         for (final ResourceChangeHandler resourceChangeHandler : resourceChangeHandlers) {
132             resourceChangeHandler.onResourceChanged(change);
133         }
134     }
135 
136     /**
137      * Start monitoring underlying resource changes.
138      */
139     protected void initializeResourceChangeMonitoring() {}
140 
141     /**
142      * @see Resource#isFile()
143      */
144     protected abstract boolean isFile(P resource);
145 
146     /**
147      * @see Resource#isDirectory()
148      */
149     protected abstract boolean isDirectory(P resource);
150 
151     /**
152      * @see Resource#isEditable()
153      */
154     protected boolean isEditable(P resource) {
155         return false;
156     }
157 
158     /**
159      * @see Resource#getPath()
160      */
161     protected abstract String getPath(P resource);
162 
163     /**
164      * @see Resource#getName()
165      */
166     protected abstract String getName(P resource);
167 
168     /**
169      * @see Resource#getLastModified()
170      */
171     protected abstract long getLastModified(P resource);
172 
173     /**
174      * @see Resource#listChildren()
175      */
176     protected abstract List<P> listChildren(P resource);
177 
178     /**
179      * @see Resource#getParent()
180      */
181     protected abstract P getParent(P resource);
182 
183     /**
184      * @see Resource#openStream()
185      */
186     protected InputStream openStream(P resource) throws IOException {
187         if (resource.isDirectory()) {
188             throw new IllegalStateException("Can not open stream on directory " + resource);
189         }
190         final InputStream inputStream = doOpenStream(resource);
191         if (inputStream == null) {
192             throw new IllegalStateException("InputStream is null for " + resource);
193         }
194         return inputStream;
195     }
196 
197     protected abstract InputStream doOpenStream(P resource) throws IOException;
198 
199     /**
200      * @see Resource#openReader()
201      */
202     protected Reader openReader(P resource) throws IOException {
203         final InputStream in = openStream(resource);
204         final Charset charset = getCharsetFor(resource);
205         final Reader reader = new InputStreamReader(in, charset);
206         return new BufferedReader(reader);
207     }
208 
209     /**
210      * Returns the preferred {@link Charset} to read the given {@link Resource}.
211      */
212     protected abstract Charset getCharsetFor(P resource);
213 
214     /**
215      * Simply removes the traces of a {@link ResourceChangeHandler} from this origin.
216      */
217     class SimpleChangeHandlerRegistration implements ResourceChangeHandlerRegistration {
218         private final ResourceChangeHandler changeHandler;
219 
220         public SimpleChangeHandlerRegistration(ResourceChangeHandler changeHandler) {
221             this.changeHandler = changeHandler;
222         }
223 
224         @Override
225         public void unRegister() {
226             resourceChangeHandlers.remove(changeHandler);
227         }
228     }
229 }