View Javadoc
1   /*
2    * #%L
3    * wcm.io
4    * %%
5    * Copyright (C) 2015 wcm.io
6    * %%
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   *
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   * #L%
19   */
20  package io.wcm.devops.conga.tooling.maven.plugin.validation;
21  
22  import java.nio.charset.StandardCharsets;
23  
24  import org.apache.commons.lang3.StringUtils;
25  import org.apache.maven.plugin.MojoFailureException;
26  
27  import com.github.jknack.handlebars.Handlebars;
28  
29  import io.wcm.devops.conga.generator.handlebars.HandlebarsManager;
30  import io.wcm.devops.conga.generator.plugins.handlebars.escaping.NoneEscapingStrategy;
31  import io.wcm.devops.conga.resource.Resource;
32  import io.wcm.devops.conga.resource.ResourceCollection;
33  import io.wcm.devops.conga.tooling.maven.plugin.util.PathUtil;
34  
35  /**
36   * Validates Handlebars templates by compiling it.
37   */
38  public final class TemplateValidator implements DefinitionValidator<Void> {
39  
40    private static final String FILE_EXTENSION = "hbs";
41  
42    private final ResourceCollection templateDir;
43    private final HandlebarsManager handlebarsManager;
44  
45    /**
46     * @param templateDir Template directory
47     * @param handlebarsManager Handlebars Manager
48     */
49    public TemplateValidator(ResourceCollection templateDir, HandlebarsManager handlebarsManager) {
50      this.templateDir = templateDir;
51      this.handlebarsManager = handlebarsManager;
52    }
53  
54    @Override
55    @SuppressWarnings({
56        "PMD.PreserveStackTrace",
57        "java:S1075" // uses / by intention
58    })
59    public Void validate(Resource resource, String pathForLog) throws MojoFailureException {
60      if (StringUtils.equalsIgnoreCase(resource.getFileExtension(), FILE_EXTENSION)) {
61        String templatePath = StringUtils.substringAfter(PathUtil.unifySlashes(resource.getCanonicalPath()),
62            PathUtil.unifySlashes(templateDir.getCanonicalPath()) + "/");
63        Handlebars handlebars = handlebarsManager.get(NoneEscapingStrategy.NAME, StandardCharsets.UTF_8.name());
64        try {
65          handlebars.compile(templatePath);
66        }
67        /*CHECKSTYLE:OFF*/ catch (Exception ex) { /*CHECKSTYLE:ON*/
68          throw new MojoFailureException("Template " + pathForLog + " is invalid:\n" + ex.getMessage());
69        }
70      }
71      return null;
72    }
73  
74  }