View Javadoc
1   /**
2    * This file Copyright (c) 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.classpathwatch;
35  
36  import java.io.IOException;
37  import java.net.URL;
38  import java.util.ArrayList;
39  import java.util.Collection;
40  import java.util.List;
41  import java.util.Set;
42  
43  import org.reflections.Reflections;
44  import org.reflections.scanners.ResourcesScanner;
45  import org.reflections.util.ClasspathHelper;
46  import org.reflections.util.ConfigurationBuilder;
47  import org.slf4j.Logger;
48  import org.slf4j.LoggerFactory;
49  
50  import com.google.common.base.Function;
51  import com.google.common.base.Predicate;
52  import com.google.common.base.Predicates;
53  import com.google.common.collect.Collections2;
54  
55  /**
56   * Scans the classpath for resources and checks for resource changes through their last-modified date.
57   */
58  public class ClasspathScanner implements Runnable {
59  
60      private static final Logger log = LoggerFactory.getLogger(ClasspathScanner.class);
61  
62      private final Predicate<String> resourcesFilter;
63      private final Predicate<? super URL> urlsFilter;
64  
65      private long lastScan;
66  
67      private List<Function<String, Void>> callbacks = new ArrayList<>();
68  
69      /**
70       * Constructor is protected, use {@link ClasspathScannerService} to get an instance.
71       *
72       * @param resourcesFilter used to dramatically decrease the amount of resources to check for changes (checking lastModified of several thousand resources *is* long)
73       * @param urlsFilter the URL exclusions filter for Reflections
74       */
75      ClasspathScanner(Predicate<String> resourcesFilter, Predicate<? super URL> urlsFilter) {
76          this.resourcesFilter = resourcesFilter;
77          this.urlsFilter = urlsFilter;
78          lastScan = System.currentTimeMillis(); // initial value, to avoid considering all resources as new on startup
79      }
80  
81      @Override
82      public void run() {
83          // 1. Scan classpath for resources
84          final long start = System.currentTimeMillis();
85  
86          final Collection<URL> classpathUrls = classpathUrls();
87          // e.g.
88          // file:/Users/<user>/.m2/repository/info/magnolia/magnolia-module-sample/1.0/magnolia-module-sample-1.0.jar (served by maven)
89          // file:/Users/<user>/<dev-directory>/magnolia-module-sample/target/classes/ (served by IDE)
90  
91          final Reflections reflections = new Reflections(new ConfigurationBuilder()
92                  .setScanners(new ResourcesScanner())
93                  .setUrls(classpathUrls)
94                  .filterInputsBy(resourcesFilter)
95                  );
96  
97          final Set<String> resources = reflections.getResources(Predicates.<String>alwaysTrue()); // predicate here is used for matching only the "simple name" of the resource; we do the pattern filtering upfront in ConfigurationBuilder anyway
98          long scanDone = System.currentTimeMillis();
99          log.debug("Took {}ms to find {} resources", scanDone - start, resources.size());
100 
101         // 2. Check for recent lastModified dates
102         for (String resource : resources) {
103             URL resourceUrl = getUrl(resource);
104             // TODO Only watch changes for resources served by the IDE (assume jars are not hot-swapped)?
105             long lastModified = getLastModified(resourceUrl);
106 
107             if (lastModified > lastScan) {
108                 log.debug("Found resource change at {}, triggering callback.", resource);
109                 for (Function<String, Void> callback : callbacks) {
110                     try {
111                         callback.apply(resource);
112                     } catch (Throwable t) {
113                         log.error("Caught exception while invoking callback:", t);
114                     }
115                 }
116                 // TODO find added/deleted files too?
117             }
118         }
119         log.debug("Took {}ms to check for recent changes", System.currentTimeMillis() - scanDone);
120         lastScan = System.currentTimeMillis();
121     }
122 
123     public void watchResourceChanges(Function<String, Void> callbackFunction) {
124         callbacks.add(callbackFunction);
125     }
126 
127     protected Collection<URL> classpathUrls() {
128         final Collection<URL> allURLs = ClasspathHelper.forClassLoader(ClasspathHelper.contextClassLoader());
129         return Collections2.filter(allURLs, urlsFilter);
130     }
131 
132     protected URL getUrl(String resourcePath) {
133         final URL url = ClasspathHelper.contextClassLoader().getResource(resourcePath);
134         if (url == null) {
135             throw new IllegalStateException("Can't find resource at " + resourcePath);
136         }
137         return url;
138     }
139 
140     protected long getLastModified(URL resourceUrl) {
141         try {
142             return resourceUrl.openConnection().getLastModified();
143         } catch (IOException e) {
144             throw new RuntimeException("Last modified time could not be retrieved for path " + resourceUrl.toExternalForm() + " : " + e, e);
145         }
146     }
147 
148 }