1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.rat.analysis.matchers;
20
21 import java.util.HashMap;
22 import java.util.Map;
23 import java.util.Objects;
24 import java.util.regex.Matcher;
25 import java.util.regex.Pattern;
26
27 import org.apache.commons.lang3.StringUtils;
28 import org.apache.rat.ConfigurationException;
29 import org.apache.rat.analysis.IHeaderMatcher;
30
31
32
33
34
35
36
37
38
39
40
41
42 public class SPDXMatcherFactory {
43
44
45
46
47 private static final Map<String, SPDXMatcherFactory.Match> matchers = new HashMap<>();
48
49
50
51
52 public static final SPDXMatcherFactory INSTANCE = new SPDXMatcherFactory();
53
54
55
56
57 private static Pattern groupSelector = Pattern.compile(".*SPDX-License-Identifier:\\s([A-Za-z0-9\\.\\-]+)");
58
59
60
61
62 private String lastLine;
63
64
65
66 private Match lastMatch;
67
68 private SPDXMatcherFactory() {
69 lastLine = null;
70 };
71
72
73
74
75
76
77 public IHeaderMatcher create(String spdxId) {
78 if (StringUtils.isBlank(spdxId)) {
79 throw new ConfigurationException("'spdx' type matcher requires a name");
80 }
81 Match matcher = matchers.get(spdxId);
82 if (matcher == null) {
83 matcher = new Match(spdxId);
84 matchers.put(spdxId, matcher);
85 }
86 return matcher;
87 }
88
89
90
91
92
93
94
95 private boolean check(String line, Match caller) {
96
97
98
99 if ((lastLine == null || !lastLine.equals(line)) && line.contains("SPDX-License-Identifier")) {
100 Matcher matcher = groupSelector.matcher(line);
101 if (matcher.find()) {
102 lastMatch = matchers.get(matcher.group(1));
103 } else {
104 lastMatch = null;
105 }
106 }
107
108 return (lastMatch != null) && caller.spdxId.equals(lastMatch.spdxId);
109 }
110
111 public class Match extends AbstractSimpleMatcher {
112
113 String spdxId;
114
115
116
117
118
119
120 Match(final String spdxId) {
121 super("SPDX:" + spdxId);
122 Objects.requireNonNull(spdxId, "SpdxId is required");
123 this.spdxId = spdxId;
124 }
125
126 @Override
127 protected boolean doMatch(String line) {
128 return SPDXMatcherFactory.this.check(line, this);
129 }
130
131 @Override
132 public void reset() {
133 super.reset();
134 SPDXMatcherFactory.this.lastMatch = null;
135
136 }
137 }
138 }