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.file;
35  
36  import static info.magnolia.resourceloader.ResourceOriginChange.Type.*;
37  import static info.magnolia.resourceloader.ResourceOriginChange.resourceChange;
38  
39  import info.magnolia.dirwatch.WatcherCallback;
40  import info.magnolia.resourceloader.ResourceOriginChange;
41  
42  import java.io.IOException;
43  import java.nio.file.FileVisitOption;
44  import java.nio.file.FileVisitResult;
45  import java.nio.file.Files;
46  import java.nio.file.Path;
47  import java.nio.file.SimpleFileVisitor;
48  import java.nio.file.attribute.BasicFileAttributes;
49  import java.util.Collections;
50  
51  import org.slf4j.Logger;
52  import org.slf4j.LoggerFactory;
53  
54  import com.google.common.base.Predicate;
55  
56  /**
57   * A {@link WatcherCallback Watcher callback implementation} which dispatches the file system modification events to the {@link FileSystemResourceOrigin}.
58   */
59  class FileWatcherCallback implements WatcherCallback {
60  
61      private static final Logger log = LoggerFactory.getLogger(FileWatcherCallback.class);
62  
63      private final FileSystemResourceOrigin origin;
64      private final Predicate<Path> watchedPathFilter;
65  
66      FileWatcherCallback(FileSystemResourceOrigin origin, Predicate<Path> watchedPathFilter) {
67          this.origin = origin;
68          this.watchedPathFilter = watchedPathFilter;
69      }
70  
71      /**
72       * Contents of the added folders are recursively handled in the same fashion. This is done due to the fact
73       * that only a single event is generated by the file system when a file/folder is added.
74       *
75       * @see <a href="https://jira.magnolia-cms.com/browse/MAGNOLIA-6278">MAGNOLIA-6278</a>
76       */
77      @Override
78      public void added(Path path) {
79          dispatchResourceChange(path, ADDED, true);
80      }
81  
82      /**
83       * Resource modifications are handled non-recursively since:
84       * - the case of a mere file is essentially non-recursive
85       * - most of the folder modification events are generated in addition to content structure modification (file/sub-directory removed/added).
86       * and => do not need additional care (even can be ignored)
87       */
88      @Override
89      public void modified(Path path) {
90          dispatchResourceChange(path, MODIFIED, false);
91      }
92  
93      /**
94       * To be consistent with the logic of {@link #added(Path)} - contents of the removed folders have to be handled recursively as well.
95       * The bad thing is that by the time the folder deletion event is processed - its contents become non-resolvable
96       * and => cannot be easily traversed.
97       */
98      @Override
99      public void removed(Path path) {
100         dispatchResourceChange(path, REMOVED, false);
101     }
102 
103     /**
104      * Communicate file system resource changes to the {@link FileSystemResource file system resource origin}.
105      *
106      * @param handleDirectoryContents indicates whether directory contents should be communicated (recursively) as well
107      */
108     private void dispatchResourceChange(Path changedResourcePath, ResourceOriginChange.Type type, boolean handleDirectoryContents) {
109         if (!watchedPathFilter.apply(changedResourcePath)) {
110             return;
111         }
112 
113         final ResourceOriginChange.Builder resourceChange =
114                 resourceChange().
115                     ofType(type).
116                     at(origin.parseResourcePath(changedResourcePath)).
117                     inOrigin(origin);
118 
119         origin.dispatchResourceChange(resourceChange.build());
120 
121         if (handleDirectoryContents && Files.isDirectory(changedResourcePath)) {
122             try {
123                 Files.walkFileTree(changedResourcePath, Collections.singleton(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
124                     @Override
125                     public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
126                         if (watchedPathFilter.apply(file)) {
127                             origin.dispatchResourceChange(resourceChange.at(origin.parseResourcePath(file)).build());
128                         }
129                         return FileVisitResult.CONTINUE;
130                     }
131 
132                     @Override
133                     public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
134                         if (!watchedPathFilter.apply(dir)) {
135                             return FileVisitResult.SKIP_SUBTREE;
136                         }
137                         return FileVisitResult.CONTINUE;
138                     }
139 
140                     @Override
141                     public FileVisitResult visitFileFailed(Path file, IOException e) throws IOException {
142                         log.warn("Visiting failed for {}", file);
143                         return FileVisitResult.SKIP_SUBTREE;
144                     }
145 
146                 });
147             } catch (IOException e) {
148                 log.error("Failed to communicate file system resource changes recursively: {}", e.getMessage(), e);
149             }
150         }
151     }
152 }