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.hc.client5.http.impl.async;
29
30 import java.util.Locale;
31 import java.util.concurrent.ConcurrentHashMap;
32 import java.util.concurrent.ConcurrentMap;
33
34 import org.apache.hc.core5.function.Supplier;
35 import org.apache.hc.core5.http.HttpRequest;
36 import org.apache.hc.core5.http.nio.AsyncPushConsumer;
37 import org.apache.hc.core5.http.protocol.UriPatternMatcher;
38 import org.apache.hc.core5.net.URIAuthority;
39 import org.apache.hc.core5.util.Args;
40
41 class AsyncPushConsumerRegistry {
42
43 private final UriPatternMatcher<Supplier<AsyncPushConsumer>> primary;
44 private final ConcurrentMap<String, UriPatternMatcher<Supplier<AsyncPushConsumer>>> hostMap;
45
46 public AsyncPushConsumerRegistry() {
47 this.primary = new UriPatternMatcher<>();
48 this.hostMap = new ConcurrentHashMap<>();
49 }
50
51 private UriPatternMatcher<Supplier<AsyncPushConsumer>> getPatternMatcher(final String hostname) {
52 if (hostname == null) {
53 return primary;
54 }
55 final UriPatternMatcher<Supplier<AsyncPushConsumer>> hostMatcher = hostMap.get(hostname);
56 if (hostMatcher != null) {
57 return hostMatcher;
58 }
59 return primary;
60 }
61
62 public AsyncPushConsumer get(final HttpRequest request) {
63 Args.notNull(request, "Request");
64 final URIAuthority authority = request.getAuthority();
65 final String key = authority != null ? authority.getHostName().toLowerCase(Locale.ROOT) : null;
66 final UriPatternMatcher<Supplier<AsyncPushConsumer>> patternMatcher = getPatternMatcher(key);
67 if (patternMatcher == null) {
68 return null;
69 }
70 String path = request.getPath();
71 final int i = path.indexOf('?');
72 if (i != -1) {
73 path = path.substring(0, i);
74 }
75 final Supplier<AsyncPushConsumer> supplier = patternMatcher.lookup(path);
76 return supplier != null ? supplier.get() : null;
77 }
78
79 public void register(final String hostname, final String uriPattern, final Supplier<AsyncPushConsumer> supplier) {
80 Args.notBlank(uriPattern, "URI pattern");
81 Args.notNull(supplier, "Supplier");
82 if (hostname == null) {
83 primary.register(uriPattern, supplier);
84 } else {
85 final String key = hostname.toLowerCase(Locale.ROOT);
86 UriPatternMatcher<Supplier<AsyncPushConsumer>> matcher = hostMap.get(key);
87 if (matcher == null) {
88 final UriPatternMatcher<Supplier<AsyncPushConsumer>> newMatcher = new UriPatternMatcher<>();
89 matcher = hostMap.putIfAbsent(key, newMatcher);
90 if (matcher == null) {
91 matcher = newMatcher;
92 }
93 }
94 matcher.register(uriPattern, supplier);
95 }
96 }
97
98 }