|
5 | 5 | import com.github.scribejava.core.extractors.TokenExtractor; |
6 | 6 | import com.github.scribejava.core.model.OAuth2AccessToken; |
7 | 7 |
|
| 8 | +import java.util.concurrent.ConcurrentHashMap; |
| 9 | +import java.util.concurrent.ConcurrentMap; |
| 10 | + |
8 | 11 | public class KeycloakApi extends DefaultApi20 { |
9 | 12 |
|
10 | | - private String baseUrl = "http://localhost:8080"; |
11 | | - private String realm = "master"; |
| 13 | + private final String baseUrlWithRealm; |
12 | 14 |
|
13 | | - public void setBaseUrl(String baseUrl) { |
14 | | - this.baseUrl = baseUrl + (baseUrl.endsWith("/")? "" : "/"); |
15 | | - } |
| 15 | + private static final ConcurrentMap<String, KeycloakApi> INSTANCES = new ConcurrentHashMap<>(); |
16 | 16 |
|
17 | | - public void setRealm(String realm) { |
18 | | - this.realm = realm; |
| 17 | + protected KeycloakApi(String baseUrlWithRealm) { |
| 18 | + this.baseUrlWithRealm = baseUrlWithRealm; |
19 | 19 | } |
20 | 20 |
|
21 | | - protected KeycloakApi() { |
| 21 | + public static KeycloakApi instance() { |
| 22 | + return instance("http://localhost:8080/", "master"); |
22 | 23 | } |
23 | 24 |
|
24 | | - private static class InstanceHolder { |
25 | | - private static final KeycloakApi INSTANCE = new KeycloakApi(); |
| 25 | + public static KeycloakApi instance(String baseUrl, String realm) { |
| 26 | + final String defaultBaseUrlWithRealm = composeBaseUrlWithRealm(baseUrl, realm); |
| 27 | + |
| 28 | + //java8: switch to ConcurrentMap::computeIfAbsent |
| 29 | + KeycloakApi api = INSTANCES.get(defaultBaseUrlWithRealm); |
| 30 | + if (api == null) { |
| 31 | + api = new KeycloakApi(defaultBaseUrlWithRealm); |
| 32 | + INSTANCES.putIfAbsent(defaultBaseUrlWithRealm, api); |
| 33 | + } |
| 34 | + return api; |
26 | 35 | } |
27 | 36 |
|
28 | | - public static KeycloakApi instance() { |
29 | | - return KeycloakApi.InstanceHolder.INSTANCE; |
| 37 | + protected static String composeBaseUrlWithRealm(String baseUrl, String realm) { |
| 38 | + return baseUrl + (baseUrl.endsWith("/") ? "" : "/") + "auth/realms/" + realm; |
30 | 39 | } |
31 | 40 |
|
32 | 41 | @Override |
33 | 42 | public String getAccessTokenEndpoint() { |
34 | | - return baseUrl + "auth/realms/" + realm + "/protocol/openid-connect/token"; |
| 43 | + return baseUrlWithRealm + "/protocol/openid-connect/token"; |
35 | 44 | } |
36 | 45 |
|
37 | 46 | @Override |
38 | 47 | protected String getAuthorizationBaseUrl() { |
39 | | - return baseUrl + "auth/realms/" + realm + "/protocol/openid-connect/auth"; |
| 48 | + return baseUrlWithRealm + "/protocol/openid-connect/auth"; |
40 | 49 | } |
41 | 50 |
|
42 | 51 | @Override |
|
0 commit comments