View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.rat.configuration;
20  
21  import java.lang.reflect.InvocationTargetException;
22  import java.util.Collection;
23  import java.util.Collections;
24  import java.util.HashMap;
25  import java.util.Map;
26  import java.util.Objects;
27  
28  import org.apache.commons.lang3.StringUtils;
29  import org.apache.commons.text.WordUtils;
30  import org.apache.rat.ConfigurationException;
31  import org.apache.rat.Defaults;
32  import org.apache.rat.configuration.builders.AbstractBuilder;
33  
34  /**
35   * A class to track the Matcher Builders as they are defined.  Matchers may be defined in multiple configuration files
36   * this method tracks them so that they can be referenced across the configuration files.
37   */
38  public final class MatcherBuilderTracker {
39  
40      /** The instance of the BuildTracker. */
41      public static MatcherBuilderTracker INSTANCE;
42  
43      private final Map<String, Class<? extends AbstractBuilder>> matcherBuilders;
44  
45      private static synchronized MatcherBuilderTracker instance() {
46          if (INSTANCE == null) {
47              INSTANCE = new MatcherBuilderTracker();
48              Defaults.init();
49          }
50          return INSTANCE;
51      }
52  
53      /**
54       * Adds a builder to the tracker.
55       * If the {@code name} is null then the builder class name simple is used with the "Builder" suffix removed.
56       * @param className the Class name for the builder.
57       * @param name the short name for the builder. 
58       */
59      public static void addBuilder(final String className, final String name) {
60          instance().addBuilderImpl(className, name);
61      }
62  
63      /**
64       * Get the matching builder for the name.
65       * @param name The name of the builder.
66       * @return the builder for that name. (not null)
67       */
68      public static AbstractBuilder getMatcherBuilder(final String name) {
69          Class<? extends AbstractBuilder> clazz = instance().matcherBuilders.get(name);
70          if (clazz == null) {
71              StringBuilder sb = new StringBuilder(System.lineSeparator()).append("Valid builders").append(System.lineSeparator());
72              instance().matcherBuilders.keySet().forEach(x -> sb.append(x).append(System.lineSeparator()));
73              sb.append("ERROR MSG").append(System.lineSeparator());
74              throw new ConfigurationException(sb.append("No matcher builder named ").append(name).toString());
75          }
76          try {
77              return clazz.getConstructor().newInstance();
78          } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException
79                  | IllegalArgumentException | InvocationTargetException e) {
80              throw new ConfigurationException(
81                      String.format("Can not instantiate matcher builder named %s (%s)", name, clazz.getName()), e);
82          }
83      }
84  
85      private MatcherBuilderTracker() {
86          matcherBuilders = new HashMap<>();
87      }
88      
89  
90      /**
91       * Gets a collection of classes that are recognized as builders.
92       * @return the collection of builder classes
93       */
94      public Collection<Class<? extends AbstractBuilder>> getClasses() {
95          return Collections.unmodifiableCollection(matcherBuilders.values());
96      }
97  
98      private void addBuilderImpl(final String className, final String name) {
99          Objects.requireNonNull(className, "className may not be null");
100         Class<?> clazz;
101         try {
102             clazz = getClass().getClassLoader().loadClass(className);
103         } catch (ClassNotFoundException e) {
104             throw new ConfigurationException(e);
105         }
106         if (AbstractBuilder.class.isAssignableFrom(clazz)) {
107             @SuppressWarnings("unchecked")
108             Class<? extends AbstractBuilder> candidate = (Class<? extends AbstractBuilder>) clazz;
109             String workingName = name;
110             if (StringUtils.isBlank(workingName)) {
111                 workingName = candidate.getSimpleName();
112                 if (!workingName.endsWith("Builder")) {
113                     throw new ConfigurationException(
114                             "name is required, or " + candidate.getName() + " must end with 'Builder'");
115                 }
116                 workingName = workingName.substring(0, workingName.lastIndexOf("Builder"));
117                 if (StringUtils.isBlank(workingName)) {
118                     throw new ConfigurationException("Last segment of " + candidate.getName()
119                             + " may not be 'Builder', but must end in 'Builder'");
120                 }
121                 workingName = WordUtils.uncapitalize(workingName);
122             }
123             matcherBuilders.put(workingName, candidate);
124         } else {
125             throw new ConfigurationException("Class " + clazz.getName() + " does not extend " + AbstractBuilder.class);
126         }
127     }
128 }