1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.esigate.impl;
16
17 import java.util.regex.Matcher;
18 import java.util.regex.Pattern;
19
20 import org.apache.commons.lang3.StringUtils;
21 import org.apache.commons.lang3.builder.ToStringBuilder;
22 import org.esigate.ConfigurationException;
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 public final class UriMapping {
42 private static final Pattern MAPPING_PATTERN = Pattern
43 .compile("((http://|https://)[^/:]*(:([0-9]*))?)?(/[^*]*)?(\\*?)([^*]*)");
44 private final String host;
45 private final String path;
46 private final String extension;
47 private final int weight;
48
49
50
51
52
53
54
55
56 private UriMapping(String host, String path, String extension) {
57 this.host = host;
58 this.path = path;
59 this.extension = extension;
60 int targetWeight = 0;
61 if (this.host != null) {
62 targetWeight += 1000;
63 }
64 if (this.path != null) {
65 targetWeight += this.path.length() * 10;
66 }
67 if (this.extension != null) {
68 targetWeight += this.extension.length();
69 }
70 this.weight = targetWeight;
71 }
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88 public static UriMapping create(String mapping) {
89 Matcher matcher = MAPPING_PATTERN.matcher(mapping);
90 if (!matcher.matches()) {
91 throw new ConfigurationException("Unrecognized URI pattern: " + mapping);
92 }
93 String host = StringUtils.trimToNull(matcher.group(1));
94 String path = StringUtils.trimToNull(matcher.group(5));
95
96 if (path != null && !path.startsWith("/")) {
97 throw new ConfigurationException("Unrecognized URI pattern: " + mapping
98 + " Mapping path should start with / was: " + path);
99 }
100 String extension = StringUtils.trimToNull(matcher.group(7));
101 if (extension != null && !extension.startsWith(".")) {
102 throw new ConfigurationException("Unrecognized URI pattern: " + mapping
103 + " Mapping extension should start with . was: " + extension);
104 }
105 return new UriMapping(host, path, extension);
106 }
107
108
109
110
111
112
113
114
115
116 public boolean matches(String schemeParam, String hostParam, String uriParam) {
117
118 if (this.host != null && !this.host.equalsIgnoreCase(schemeParam + "://" + hostParam)) {
119 return false;
120 }
121
122 if (this.extension != null && !uriParam.endsWith(this.extension)) {
123 return false;
124 }
125
126 if (this.path != null && !uriParam.startsWith(this.path)) {
127 return false;
128 }
129 return true;
130 }
131
132
133
134
135
136
137 public int getWeight() {
138 return this.weight;
139 }
140
141
142
143
144
145
146 public String getExtension() {
147 return this.extension;
148 }
149
150
151
152
153
154
155 public String getPath() {
156 return this.path;
157 }
158
159
160
161
162
163
164 public String getHost() {
165 return this.host;
166 }
167
168 @Override
169 public String toString() {
170 return ToStringBuilder.reflectionToString(this);
171 }
172 }