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 package org.apache.hc.client5.http.impl.auth;
28
29 import java.util.Map;
30 import java.util.concurrent.ConcurrentHashMap;
31
32 import org.apache.hc.client5.http.auth.AuthScope;
33 import org.apache.hc.client5.http.auth.Credentials;
34 import org.apache.hc.client5.http.auth.CredentialsStore;
35 import org.apache.hc.core5.annotation.Contract;
36 import org.apache.hc.core5.annotation.ThreadingBehavior;
37 import org.apache.hc.core5.http.protocol.HttpContext;
38 import org.apache.hc.core5.util.Args;
39
40
41
42
43
44
45 @Contract(threading = ThreadingBehavior.SAFE)
46 public class BasicCredentialsProvider implements CredentialsStore {
47
48 private final ConcurrentHashMap<AuthScope, Credentials> credMap;
49
50
51
52
53 public BasicCredentialsProvider() {
54 super();
55 this.credMap = new ConcurrentHashMap<>();
56 }
57
58 @Override
59 public void setCredentials(
60 final AuthScope authScope,
61 final Credentials credentials) {
62 Args.notNull(authScope, "Authentication scope");
63 credMap.put(authScope, credentials);
64 }
65
66
67
68
69
70
71
72
73
74 private static Credentials matchCredentials(
75 final Map<AuthScope, Credentials> map,
76 final AuthScope authScope) {
77
78 Credentials creds = map.get(authScope);
79 if (creds == null) {
80
81
82 int bestMatchFactor = -1;
83 AuthScope bestMatch = null;
84 for (final AuthScope current: map.keySet()) {
85 final int factor = authScope.match(current);
86 if (factor > bestMatchFactor) {
87 bestMatchFactor = factor;
88 bestMatch = current;
89 }
90 }
91 if (bestMatch != null) {
92 creds = map.get(bestMatch);
93 }
94 }
95 return creds;
96 }
97
98 @Override
99 public Credentials getCredentials(final AuthScope authScope,
100 final HttpContext httpContext) {
101 Args.notNull(authScope, "Authentication scope");
102 return matchCredentials(this.credMap, authScope);
103 }
104
105 @Override
106 public void clear() {
107 this.credMap.clear();
108 }
109
110 @Override
111 public String toString() {
112 return credMap.toString();
113 }
114
115 }