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