1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.apache.http.protocol;
29
30 import java.util.HashSet;
31 import java.util.LinkedHashMap;
32 import java.util.Map;
33 import java.util.Map.Entry;
34 import java.util.Set;
35
36 import org.apache.http.annotation.Contract;
37 import org.apache.http.annotation.ThreadingBehavior;
38 import org.apache.http.util.Args;
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56 @Contract(threading = ThreadingBehavior.SAFE)
57 public class UriPatternMatcher<T> {
58
59 private final Map<String, T> map;
60
61 public UriPatternMatcher() {
62 super();
63 this.map = new LinkedHashMap<String, T>();
64 }
65
66
67
68
69
70
71
72
73
74 public synchronized Set<Entry<String, T>> entrySet() {
75 return new HashSet<Entry<String, T>>(map.entrySet());
76 }
77
78
79
80
81
82
83
84 public synchronized void register(final String pattern, final T obj) {
85 Args.notNull(pattern, "URI request pattern");
86 this.map.put(pattern, obj);
87 }
88
89
90
91
92
93
94 public synchronized void unregister(final String pattern) {
95 if (pattern == null) {
96 return;
97 }
98 this.map.remove(pattern);
99 }
100
101
102
103
104 @Deprecated
105 public synchronized void setHandlers(final Map<String, T> map) {
106 Args.notNull(map, "Map of handlers");
107 this.map.clear();
108 this.map.putAll(map);
109 }
110
111
112
113
114 @Deprecated
115 public synchronized void setObjects(final Map<String, T> map) {
116 Args.notNull(map, "Map of handlers");
117 this.map.clear();
118 this.map.putAll(map);
119 }
120
121
122
123
124 @Deprecated
125 public synchronized Map<String, T> getObjects() {
126 return this.map;
127 }
128
129
130
131
132
133
134
135 public synchronized T lookup(final String path) {
136 Args.notNull(path, "Request path");
137
138 T obj = this.map.get(path);
139 if (obj == null) {
140
141 String bestMatch = null;
142 for (final String pattern : this.map.keySet()) {
143 if (matchUriRequestPattern(pattern, path)) {
144
145 if (bestMatch == null
146 || (bestMatch.length() < pattern.length())
147 || (bestMatch.length() == pattern.length() && pattern.endsWith("*"))) {
148 obj = this.map.get(pattern);
149 bestMatch = pattern;
150 }
151 }
152 }
153 }
154 return obj;
155 }
156
157
158
159
160
161
162
163
164
165 protected boolean matchUriRequestPattern(final String pattern, final String path) {
166 if (pattern.equals("*")) {
167 return true;
168 }
169 return
170 (pattern.endsWith("*") && path.startsWith(pattern.substring(0, pattern.length() - 1))) ||
171 (pattern.startsWith("*") && path.endsWith(pattern.substring(1, pattern.length())));
172 }
173
174 @Override
175 public String toString() {
176 return this.map.toString();
177 }
178
179 }