View Javadoc
1   /**
2    * This file Copyright (c) 2016-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.content.observer;
35  
36  import info.magnolia.cms.security.UserManager;
37  import info.magnolia.dirwatch.WatcherCallback;
38  import info.magnolia.objectfactory.Components;
39  import info.magnolia.registry.RegistrationException;
40  import info.magnolia.task.Task;
41  import info.magnolia.task.TasksManager;
42  import info.magnolia.task.definition.registry.TaskDefinitionRegistry;
43  import info.magnolia.content.task.definition.ContentImporterTaskDefinition;
44  
45  import java.io.File;
46  import java.io.IOException;
47  import java.nio.file.FileVisitResult;
48  import java.nio.file.Files;
49  import java.nio.file.Path;
50  import java.nio.file.SimpleFileVisitor;
51  import java.nio.file.attribute.BasicFileAttributes;
52  import java.util.Date;
53  import java.util.Map;
54  
55  import javax.inject.Inject;
56  
57  import org.apache.commons.lang3.StringUtils;
58  import org.slf4j.Logger;
59  import org.slf4j.LoggerFactory;
60  
61  import com.google.common.base.Predicate;
62  import com.google.common.collect.ImmutableMap;
63  
64  /**
65   * A {@link info.magnolia.dirwatch.WatcherCallback Watcher callback implementation} which is responsible for creating {@link Task tasks}
66   * and submitting them to {@link TasksManager}.
67   */
68  public class TaskCreatorWatcherCallback implements WatcherCallback {
69  
70      private static final Logger log = LoggerFactory.getLogger(TaskCreatorWatcherCallback.class);
71  
72      private final TasksManager tasksManager;
73      private final OnlyXmlFileFilter pathFilter;
74      private final TaskDefinitionRegistry taskDefinitionRegistry;
75  
76      @Inject
77      public TaskCreatorWatcherCallback(TasksManager tasksManager, TaskDefinitionRegistry taskDefinitionRegistry) {
78          this.tasksManager = tasksManager;
79          this.pathFilter = new OnlyXmlFileFilter();
80          this.taskDefinitionRegistry = taskDefinitionRegistry;
81      }
82  
83      /**
84       * @deprecated since 1.0.2, use {@link #TaskCreatorWatcherCallback(TasksManager, TaskDefinitionRegistry)} instead.
85       */
86      @Deprecated
87      public TaskCreatorWatcherCallback(TasksManager tasksManager) {
88          this(tasksManager, Components.getComponent(TaskDefinitionRegistry.class));
89      }
90  
91      @Override
92      public void added(Path path) {
93          // If a folder is added, then we should be traversing its content recursively to find files beneath
94          // Unfortunately we don't get events for those files directly, please see MAGNOLIA-6278 for more information.
95          if (Files.isDirectory(path)) {
96              try {
97                  Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
98                      @Override
99                      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
100                         if (pathFilter.apply(file)) {
101                             added(file);
102                         }
103                         return FileVisitResult.CONTINUE;
104                     }
105                 });
106             } catch (IOException e) {
107                 log.error("Failed to communicate file system resource changes recursively: {}", e.getMessage(), e);
108             }
109         }
110         addTask(path);
111     }
112 
113     @Override
114     public void removed(Path path) {
115         // do nothing here for now since we don't have a clear strategy.
116     }
117 
118     @Override
119     public void modified(Path path) {
120         addTask(path);
121     }
122 
123     /**
124      * Creates {@link Task} with required content such a repository, path, and modification date of
125      * content bootstrap request.
126      */
127     private void addTask(Path path) {
128         if (!pathFilter.apply(path)) {
129             return;
130         }
131         final String contentTask = "content";
132         try {
133             final ContentImporterTaskDefinition contentImporterTaskDefinition = (ContentImporterTaskDefinition) taskDefinitionRegistry.get(contentTask);
134             File changedFile = path.toFile();
135             if (changedFile.isFile()) {
136                 Task task = new Task();
137                 task.setName(contentImporterTaskDefinition.getName());
138                 task.setRequestor(UserManager.SYSTEM_USER);
139                 task.setStatus(Task.Status.Created);
140                 task.setActorIds(contentImporterTaskDefinition.getUsers());
141                 task.setGroupIds(contentImporterTaskDefinition.getGroups());
142                 task.setComment(changedFile.getName());
143 
144                 String repository = StringUtils.substringBefore(changedFile.getName(), ".");
145                 Map<String, Object> content = ImmutableMap.of(
146                         "repository", repository,
147                         "path", changedFile.getAbsolutePath(),
148                         "modificationDate", new Date());
149 
150                 task.setContent(content);
151                 tasksManager.addTask(task);
152                 log.info("File change detected at '{}', pulse task has been sent.", changedFile.getAbsolutePath());
153             }
154         } catch (RegistrationException e) {
155             log.error("Could not retrieve task definition for [{}] task. Content won't be bootstrapped.", contentTask, e);
156         }
157 
158     }
159 
160     /**
161      * Predicate accepts files only with XML extension.
162      */
163     private static class OnlyXmlFileFilter implements Predicate<Path> {
164         @Override
165         public boolean apply(Path path) {
166             return path.toString().toLowerCase().endsWith(".xml");
167         }
168     }
169 }