View Javadoc
1   /**
2    * This file Copyright (c) 2014-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.config.source.yaml;
35  
36  import info.magnolia.config.registry.DefinitionMetadataBuilder;
37  import info.magnolia.config.registry.Registry;
38  import info.magnolia.config.source.ConfigurationSource;
39  import info.magnolia.config.source.ConfigurationSourceType;
40  import info.magnolia.config.source.ConfigurationSourceTypes;
41  import info.magnolia.resourceloader.Resource;
42  import info.magnolia.resourceloader.ResourceOrigin;
43  import info.magnolia.resourceloader.ResourceVisitor;
44  import info.magnolia.resourceloader.util.Functions;
45  import info.magnolia.resourceloader.util.PredicatedResourceVisitor;
46  import info.magnolia.resourceloader.util.VoidFunction;
47  
48  import java.io.IOException;
49  import java.util.regex.Matcher;
50  import java.util.regex.Pattern;
51  
52  import org.slf4j.Logger;
53  import org.slf4j.LoggerFactory;
54  
55  /**
56   * Configuration source for any text-resource based configuration files.
57   *
58   * @param <T> type the source will provide
59   */
60  public abstract class AbstractFileResourceConfigurationSource<T> implements ConfigurationSource {
61  
62      private static final Logger log = LoggerFactory.getLogger(AbstractFileResourceConfigurationSource.class);
63  
64      private final ResourceOrigin origin;
65      private final Pattern pathPattern;
66      private final Registry<T> registry;
67      private final PathToMetadataInferrer pathToMetadataInferrer;
68  
69      /**
70       * @param pathPattern a regular expression pattern used to determine whether a file should be considered by the source or not. If the pattern contains a group, it will be used to determine the name of the given object, if not explicitly configured.
71       */
72      public AbstractFileResourceConfigurationSource(ResourceOrigin origin, Registry<T> registry, Pattern pathPattern) throws IOException {
73          this.origin = origin;
74          this.registry = registry;
75          this.pathPattern = pathPattern;
76          this.pathToMetadataInferrer = new RegexBasedPathToMetadataInferrer(this.pathPattern);
77      }
78  
79      @Override
80      public ConfigurationSourceType type() {
81          return ConfigurationSourceTypes.file;
82      }
83  
84      @Override
85      public void start() throws IOException {
86          log.info("Setting up {} to load {} definitions from resources", getClass().getSimpleName(), getRootType().getSimpleName());
87          final LoadAndRegisterFunction loadAndRegisterFunction = new LoadAndRegisterFunction();
88          final ResourceVisitor visitor = PredicatedResourceVisitor.onAllMatchingFiles(Functions.pathMatches(pathPattern), loadAndRegisterFunction);
89          origin.traverseWith(visitor);
90          origin.watchForChanges(visitor);
91      }
92  
93      // TODO either we pass only Resource, or String and InputStream
94      public abstract void loadAndRegister(Resource resource);
95  
96      protected Registry<T> getRegistry() {
97          return registry;
98      }
99  
100     protected final Class<T> getRootType() {
101         return registry.type().baseClass();
102     }
103 
104     protected DefinitionMetadataBuilder createMetadata(Resource resource) {
105         final DefinitionMetadataBuilder metadataBuilder = registry.newMetadataBuilder()
106                 .type(getRegistry().type())
107                         //.source(this??)
108                 .location(resource.getPath()); // TO BE CHANGED BY WHATEVER MORE MEANINGFUL LOCATION WE'RE ABOUT TO HAVE
109 
110         return pathToMetadataInferrer.populateFrom(metadataBuilder, resource);
111     }
112 
113     private class LoadAndRegisterFunction extends VoidFunction<Resource> {
114         @Override
115         public void doWith(Resource resource) {
116             // TODO Temp/generics this
117             //if (!(resource instanceof FileSystemResource)) {
118             //    throw new IllegalStateException("GAAAH");
119             //}
120             if (resource.isDirectory()) {
121                 log.debug("Ignoring event on directory {}", resource);
122                 return;
123             }
124 
125             final Matcher matcher = pathPattern.matcher(resource.getPath());
126             if (!matcher.matches()) { // TODO this is currently here because FS observation triggers events for all files regardless of pattern. Find better place.
127                 log.debug("Ignoring event on {} (no match for {})", resource, pathPattern);
128                 return;
129             }
130 
131             log.debug("Loading {} ({})", resource, resource.getPath());
132             loadAndRegister(resource);
133         }
134     }
135 }