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.transports.http.configuration.ConnectionType;
35 import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
36
37 abstract class SelfKeymasterOps {
38
39 protected final Map<Class<?>, Object> services = Collections.synchronizedMap(new HashMap<>());
40
41 private final JAXRSClientFactoryBean clientFactory;
42
43 protected HTTPClientPolicy httpClientPolicy;
44
45 protected SelfKeymasterOps(final JAXRSClientFactoryBean clientFactory) {
46 this.clientFactory = clientFactory;
47
48 httpClientPolicy = new HTTPClientPolicy();
49 httpClientPolicy.setConnection(ConnectionType.CLOSE);
50 }
51
52 @SuppressWarnings("unchecked")
53 public <T> T client(final Class<T> serviceClass, final Map<String, String> headers) {
54 T service;
55 if (services.containsKey(serviceClass)) {
56 service = (T) services.get(serviceClass);
57 } else {
58 synchronized (clientFactory) {
59 clientFactory.setServiceClass(serviceClass);
60 clientFactory.setHeaders(headers);
61 service = clientFactory.create(serviceClass);
62 }
63 services.put(serviceClass, service);
64
65 Client client = WebClient.client(service);
66 client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
67
68 ClientConfiguration config = WebClient.getConfig(client);
69 config.getInInterceptors().add(new GZIPInInterceptor());
70 config.getOutInterceptors().add(new GZIPOutInterceptor());
71
72 HTTPConduit httpConduit = (HTTPConduit) config.getConduit();
73 httpConduit.setClient(httpClientPolicy);
74 }
75
76 return service;
77 }
78
79 protected CompletionStageRxInvoker rx(final String path) {
80 synchronized (clientFactory) {
81 String original = clientFactory.getAddress();
82 clientFactory.setAddress(StringUtils.removeEnd(original, "/") + StringUtils.prependIfMissing(path, "/"));
83
84 try {
85 WebClient client = clientFactory.createWebClient().
86 type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
87 return client.rx();
88 } finally {
89 clientFactory.setAddress(original);
90 }
91 }
92 }
93 }