1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.rat.configuration;
20
21 import java.io.File;
22 import java.lang.reflect.Constructor;
23 import java.lang.reflect.InvocationTargetException;
24 import java.net.MalformedURLException;
25 import java.net.URL;
26 import java.util.Arrays;
27
28 import org.apache.rat.ConfigurationException;
29
30
31
32
33
34 public enum Format {
35
36 XML(XMLConfigurationReader.class, "xml"),
37
38 TXT(null, "txt", "text");
39
40 private final String[] suffix;
41
42 private Constructor<MatcherReader> matcherReader;
43 private Constructor<LicenseReader> licenseReader;
44
45 @SuppressWarnings("unchecked")
46 Format(Class<?> reader, String... suffix) {
47 if (reader != null) {
48 try {
49 matcherReader = MatcherReader.class.isAssignableFrom(reader)
50 ? (Constructor<MatcherReader>) reader.getConstructor()
51 : null;
52 licenseReader = LicenseReader.class.isAssignableFrom(reader)
53 ? (Constructor<LicenseReader>) reader.getConstructor()
54 : null;
55 } catch (NoSuchMethodException | SecurityException e) {
56 throw new ConfigurationException("Error retrieving no argument constructor for " + reader.getName(), e);
57 }
58 }
59 this.suffix = suffix;
60 }
61
62
63
64
65 public MatcherReader matcherReader() {
66 try {
67 return matcherReader == null ? null : matcherReader.newInstance();
68 } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
69 | InvocationTargetException e) {
70 throw new ConfigurationException("Can not instantiate MatcherReader for " + this.name(), e);
71 }
72 }
73
74
75
76
77 public LicenseReader licenseReader() {
78 try {
79 return licenseReader == null ? null : licenseReader.newInstance();
80 } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
81 | InvocationTargetException e) {
82 throw new ConfigurationException("Can not instantiate LicenseReader for " + this.name(), e);
83 }
84 }
85
86
87
88
89
90
91 public static Format fromName(String name) {
92 String[] parts = name.split("\\.");
93 String suffix = parts[parts.length - 1];
94 for (Format f : Format.values()) {
95 if (Arrays.asList(f.suffix).contains(suffix)) {
96 return f;
97 }
98 }
99 throw new IllegalArgumentException(String.format("No such suffix: %s", suffix));
100 }
101
102
103
104
105
106
107 public static Format fromURL(URL url) {
108 return Format.fromName(url.getFile());
109 }
110
111
112
113
114
115
116
117 public static Format fromFile(File file) throws MalformedURLException {
118 return Format.fromURL(file.toURI().toURL());
119 }
120 }