1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.syncope.common.keymaster.client.self;
20
21 import java.util.Collections;
22 import java.util.HashMap;
23 import java.util.Map;
24 import javax.ws.rs.client.CompletionStageRxInvoker;
25 import javax.ws.rs.core.MediaType;
26 import org.apache.commons.lang3.StringUtils;
27 import org.apache.cxf.jaxrs.client.Client;
28 import org.apache.cxf.jaxrs.client.ClientConfiguration;
29 import org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean;
30 import org.apache.cxf.jaxrs.client.WebClient;
31 import org.apache.cxf.transport.common.gzip.GZIPInInterceptor;
32 import org.apache.cxf.transport.common.gzip.GZIPOutInterceptor;
33 import org.apache.cxf.transport.http.HTTPConduit;
34 import org.apache.cxf.transport.http.asyncclient.AsyncHTTPConduit;
35 import org.apache.cxf.transports.http.configuration.ConnectionType;
36 import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
37
38 abstract class SelfKeymasterOps {
39
40 protected final Map<Class<?>, Object> services = Collections.synchronizedMap(new HashMap<>());
41
42 private final JAXRSClientFactoryBean clientFactory;
43
44 protected HTTPClientPolicy httpClientPolicy;
45
46 protected SelfKeymasterOps(final JAXRSClientFactoryBean clientFactory) {
47 this.clientFactory = clientFactory;
48
49 httpClientPolicy = new HTTPClientPolicy();
50 httpClientPolicy.setConnection(ConnectionType.CLOSE);
51 }
52
53 @SuppressWarnings("unchecked")
54 public <T> T client(final Class<T> serviceClass, final Map<String, String> headers) {
55 T service;
56 if (services.containsKey(serviceClass)) {
57 service = (T) services.get(serviceClass);
58 } else {
59 synchronized (clientFactory) {
60 clientFactory.setServiceClass(serviceClass);
61 clientFactory.setHeaders(headers);
62 service = clientFactory.create(serviceClass);
63 }
64 services.put(serviceClass, service);
65
66 Client client = WebClient.client(service);
67 client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
68
69 ClientConfiguration config = WebClient.getConfig(client);
70 config.getRequestContext().put(AsyncHTTPConduit.USE_ASYNC, Boolean.TRUE);
71 config.getInInterceptors().add(new GZIPInInterceptor());
72 config.getOutInterceptors().add(new GZIPOutInterceptor());
73
74 HTTPConduit httpConduit = (HTTPConduit) config.getConduit();
75 httpConduit.setClient(httpClientPolicy);
76 }
77
78 return service;
79 }
80
81 protected CompletionStageRxInvoker rx(final String path) {
82 synchronized (clientFactory) {
83 String original = clientFactory.getAddress();
84 clientFactory.setAddress(StringUtils.removeEnd(original, "/") + StringUtils.prependIfMissing(path, "/"));
85
86 try {
87 WebClient client = clientFactory.createWebClient().
88 type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
89 return client.rx();
90 } finally {
91 clientFactory.setAddress(original);
92 }
93 }
94 }
95 }