· 4 years ago · Jan 27, 2021, 08:08 PM
1package com.baltinfo.radius.client;
2
3import com.baltinfo.radius.dadata.model.AddressResponse;
4import com.baltinfo.radius.dadata.model.AddressStandardResponse;
5import com.baltinfo.radius.utils.Result;
6import com.fasterxml.jackson.core.JsonProcessingException;
7import com.mashape.unirest.http.ObjectMapper;
8import com.mashape.unirest.http.Unirest;
9import com.mashape.unirest.http.exceptions.UnirestException;
10import org.apache.http.client.config.RequestConfig;
11import org.apache.http.conn.ssl.NoopHostnameVerifier;
12import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
13import org.apache.http.impl.client.CloseableHttpClient;
14import org.apache.http.impl.client.HttpClients;
15import org.apache.http.ssl.SSLContextBuilder;
16import org.slf4j.Logger;
17import org.slf4j.LoggerFactory;
18
19import javax.net.ssl.SSLContext;
20import java.io.IOException;
21import java.security.KeyManagementException;
22import java.security.KeyStoreException;
23import java.security.NoSuchAlgorithmException;
24import java.security.cert.X509Certificate;
25
26/**
27 * Клиент для вызова методов сервсиса dadata.ru
28 *
29 * @author Igor Lapenok
30 * @since 09.12.2019
31 */
32public class DadataClient {
33 private final Logger logger = LoggerFactory.getLogger(DadataClient.class);
34
35 private static final String PREFIX_TOKEN = "Token ";
36 private final String baseUrl;
37 private final String baseStandardUrl;
38 private final String apiKey;
39 private final String secretKey;
40 private final boolean demoMode;
41
42 public DadataClient(String baseUrl, String baseStandardUrl, String apiKey, String secretKey, int connectTimeout,
43 int connectionRequestTimeout, int socketTimeout, boolean demoMode) {
44 this.baseUrl = baseUrl;
45 this.baseStandardUrl = baseStandardUrl;
46 this.apiKey = apiKey;
47 this.secretKey = secretKey;
48 this.demoMode = demoMode;
49
50 Unirest.setObjectMapper(new ObjectMapper() {
51 private com.fasterxml.jackson.databind.ObjectMapper jacksonObjectMapper
52 = new com.fasterxml.jackson.databind.ObjectMapper();
53
54 public <T> T readValue(String value, Class<T> valueType) {
55 try {
56 return jacksonObjectMapper.readValue(value, valueType);
57 } catch (IOException e) {
58 throw new RuntimeException(e);
59 }
60 }
61
62 public String writeValue(Object value) {
63 try {
64 return jacksonObjectMapper.writeValueAsString(value);
65 } catch (JsonProcessingException e) {
66 throw new RuntimeException(e);
67 }
68 }
69 });
70 try {
71 CloseableHttpClient customHttpClient = getClient(connectTimeout, connectionRequestTimeout, socketTimeout);
72 Unirest.setHttpClient(customHttpClient);
73 } catch (Exception e) {
74 logger.error("Can't create dadata.ru rest client", e);
75 }
76 }
77
78 private CloseableHttpClient getClient(int connectTimeout, int connectionRequestTimeout, int socketTimeout)
79 throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
80
81 SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy() {
82 public boolean isTrusted(X509Certificate[] chain, String authType) {
83 return true;
84 }
85 }).build();
86
87 RequestConfig config = RequestConfig.custom()
88 .setConnectTimeout(connectTimeout)
89 .setConnectionRequestTimeout(connectionRequestTimeout)
90 .setSocketTimeout(socketTimeout)
91 .build();
92
93 return HttpClients.custom()
94 .setSSLContext(sslContext)
95 .setSSLHostnameVerifier(new NoopHostnameVerifier())
96 .setDefaultRequestConfig(config)
97 .build();
98 }
99
100 public Result<AddressResponse, String> getAddressByCoordinate(String lat, String lon) {
101 if (this.demoMode) {
102 logger.error("Service was running in demo mode! It don't return any value.");
103 return Result.error("Service was running in demo mode! It don't return any value.");
104 }
105 if (isNumeric(lat) && isNumeric(lon)) {
106 String url = baseUrl + "/geolocate/address";
107 try {
108 AddressResponse addressResponse = Unirest.get(url)
109 .queryString("lat", lat)
110 .queryString("lon", lon)
111 .header("Content-Type", "application/json")
112 .header("Authorization", PREFIX_TOKEN + apiKey)
113 .asObject(AddressResponse.class)
114 .getBody();
115 return Result.ok(addressResponse);
116 } catch (UnirestException e) {
117 logger.error("Error in call service dadata.ru url = {}", url, e);
118 return Result.error("Error in call service " + url);
119 }
120 } else {
121 logger.error("Invalid parameters value: lat = {}, lon = {}", lat, lon);
122 return Result.error("Invalid parameters value");
123 }
124 }
125
126 public Result<AddressStandardResponse[], String> getAddressStandard(String address) {
127 if (this.demoMode) {
128 logger.error("Service was running in demo mode! It don't return any value.");
129 return Result.error("Service was running in demo mode! It don't return any value.");
130 }
131 try {
132 AddressStandardResponse[] addressStandardResponses = Unirest.post(baseStandardUrl)
133 .header("Content-Type", "application/json")
134 .header("Authorization", PREFIX_TOKEN + apiKey)
135 .header("X-Secret", secretKey)
136 .body("[\"" + address + "\"]")
137 .asObject(AddressStandardResponse[].class)
138 .getBody();
139 return Result.ok(addressStandardResponses);
140 } catch (UnirestException e) {
141 logger.error("Error in call service dadata.ru url = {}", baseStandardUrl, e);
142 return Result.error("Error in call service " + baseStandardUrl);
143 }
144 }
145
146 private boolean isNumeric(String str) {
147 return str.matches("-?\\d+(\\.\\d+)?");
148 }
149}
150