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.config.source.yaml;
35  
36  import info.magnolia.config.registry.DefinitionMetadataBuilder;
37  import info.magnolia.resourceloader.Resource;
38  
39  import java.util.regex.Matcher;
40  import java.util.regex.Pattern;
41  
42  import org.apache.commons.io.FilenameUtils;
43  import org.apache.commons.lang3.StringUtils;
44  import org.slf4j.Logger;
45  import org.slf4j.LoggerFactory;
46  
47  /**
48   * Parse the config path for the metadata attributes, according to a regex pattern.
49   * <p>
50   * Relies preferably on named groups, e.g. <code>{@value #GROUP_MODULE}</code>, <code>{@value #GROUP_NAME}</code> or <code>{@value #GROUP_RELATIVE_PATH}</code>,
51   * otherwise will interpret first group as module name, and last group as definition name.
52   */
53  public class RegexBasedPathToMetadataInferrer implements PathToMetadataInferrer {
54  
55      private static final Logger log = LoggerFactory.getLogger(RegexBasedPathToMetadataInferrer.class);
56  
57      public static final String GROUP_MODULE = "module";
58      public static final String GROUP_NAME = "name";
59      public static final String GROUP_RELATIVE_PATH = "relPath";
60  
61      private final Pattern pathPattern;
62  
63      public RegexBasedPathToMetadataInferrer(Pattern pathPattern) {
64          this.pathPattern = pathPattern;
65      }
66  
67      @Override
68      public DefinitionMetadataBuilder populateFrom(DefinitionMetadataBuilder metadataBuilder, Resource resource) {
69          final String relativePath = resource.getPath();
70          final Matcher matcher = matcherFor(relativePath);
71          final String fallbackDefinitionName = fallbackDefinitionName(matcher, relativePath);
72          final String moduleName = moduleName(matcher, relativePath);
73          final String relativeLocation = relativeLocation(matcher, relativePath);
74          return metadataBuilder
75                  .name(fallbackDefinitionName)
76                  .module(moduleName)
77                  .relativeLocation(relativeLocation);
78      }
79  
80      protected String fallbackDefinitionName(Matcher matcher, String path) {
81          if (matcher.groupCount() < 1) {
82              // If we're here, matcher should match, unless it's an invalid pattern
83              final String nameWithoutExtension = FilenameUtils.getBaseName(path);
84              log.debug("Pattern {} does not have a capturing group to infer definition name from path {}; falling back to filename without extension: {}", pathPattern, path, nameWithoutExtension);
85              return nameWithoutExtension;
86          }
87  
88          try {
89              // We want to optionally support named groups in patterns. However, since
90              // Pattern.namedGroups() is not a part of public API - we cannot reliably tell
91              // whether the named group is present, the following logic - is a workaround
92              // (alternatively reflection could be used).
93              return matcher.group(GROUP_NAME);
94          } catch (IllegalArgumentException e) {
95              if (matcher.groupCount() > 1) {
96                  // pick last group
97                  return matcher.group(matcher.groupCount());
98              } else {
99                  return matcher.group(1);
100             }
101         }
102     }
103 
104     protected String moduleName(Matcher matcher, String path) {
105         if (matcher.groupCount() < 2) {
106             log.debug("Pattern {} does not have a capturing group to infer module name from path {}; falling back to default: {}", pathPattern, path, "yaml");
107             return "yaml";
108         }
109 
110         try {
111             // We want to optionally support named groups in patterns. However, since
112             // Pattern.namedGroups() is not a part of public API - we cannot reliably tell
113             // whether the named group is present, the following logic - is a workaround
114             // (alternatively reflection could be used).. Meh.
115             return matcher.group(GROUP_MODULE);
116         } catch (IllegalArgumentException e) {
117             // pick first group
118             return matcher.group(1);
119         }
120     }
121 
122     protected String relativeLocation(Matcher matcher, String path) {
123         // Just assemble a matcher group named <relPath> and the name (from the matcher as well, we don't want it to be overridden by def)
124         try {
125             // Using named groups in the pattern should be optional, but ....
126             // Yuck. Pattern.namedGroups() is not public... so it's this or reflection. Meh.
127             String group = matcher.group(GROUP_RELATIVE_PATH);
128             return StringUtils.isNotBlank(group) ? group + matcher.group(GROUP_NAME) : matcher.group(GROUP_NAME);
129         } catch (IllegalArgumentException e) {
130             if (matcher.groupCount() > 1) {
131                 // first group is module and last group is name, pick whatever's in between (name included, leading slash excluded if any)
132                 String subPath = path.substring(matcher.end(1), matcher.end(matcher.groupCount()));
133                 return StringUtils.strip(subPath, "/");
134             }
135             return FilenameUtils.removeExtension(StringUtils.removeStart(path, "/"));
136         }
137     }
138 
139     protected Matcher matcherFor(String relativePath) {
140         final Matcher matcher = pathPattern.matcher(relativePath);
141         if (!matcher.matches()) {
142             // FileResourceLoader should have rejected this file if it didn't match the pattern, so we shouldn't be here unless someone tried to force-register a file through code?
143             throw new IllegalStateException(String.format("%s doesn't match pattern %s, rejecting.", relativePath, pathPattern));
144         }
145         return matcher;
146     }
147 
148 }