Subversion Repositories SmartDukaan

Rev

Rev 36295 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
21557 ashik.ali 1
package com.spice.profitmandi.common.web.client;
2
 
30289 amit.gupta 3
import com.fasterxml.jackson.databind.ObjectMapper;
4
import com.spice.profitmandi.common.ResponseCodeHolder;
5
import com.spice.profitmandi.common.enumuration.SchemeType;
6
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
7
import com.spice.profitmandi.common.model.MandiiResponse;
21557 ashik.ali 8
import org.apache.http.HttpResponse;
22215 ashik.ali 9
import org.apache.http.NameValuePair;
21557 ashik.ali 10
import org.apache.http.client.ClientProtocolException;
11
import org.apache.http.client.HttpClient;
25244 amit.gupta 12
import org.apache.http.client.config.RequestConfig;
22215 ashik.ali 13
import org.apache.http.client.entity.UrlEncodedFormEntity;
34805 ranu 14
import org.apache.http.client.methods.*;
23502 ashik.ali 15
import org.apache.http.conn.HttpHostConnectException;
16
import org.apache.http.entity.ContentType;
17
import org.apache.http.entity.StringEntity;
34805 ranu 18
import org.apache.http.impl.client.CloseableHttpClient;
25244 amit.gupta 19
import org.apache.http.impl.client.HttpClientBuilder;
21557 ashik.ali 20
import org.apache.http.impl.client.HttpClients;
30383 amit.gupta 21
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
22215 ashik.ali 22
import org.apache.http.message.BasicNameValuePair;
34805 ranu 23
import org.apache.http.util.EntityUtils;
25011 amit.gupta 24
import org.apache.logging.log4j.LogManager;
23568 govind 25
import org.apache.logging.log4j.Logger;
25726 amit.gupta 26
import org.springframework.beans.factory.annotation.Autowired;
21557 ashik.ali 27
import org.springframework.http.HttpStatus;
23526 ashik.ali 28
import org.springframework.stereotype.Component;
21557 ashik.ali 29
import org.springframework.web.util.UriComponentsBuilder;
30
 
30289 amit.gupta 31
import java.io.*;
32
import java.util.ArrayList;
33
import java.util.List;
34
import java.util.Map;
35
import java.util.Set;
21557 ashik.ali 36
 
23526 ashik.ali 37
@Component
21557 ashik.ali 38
public class RestClient {
25011 amit.gupta 39
 
31828 amit.gupta 40
    private static final Logger LOGGER = LogManager.getLogger(RestClient.class);
25011 amit.gupta 41
 
31828 amit.gupta 42
    private HttpClient httpClient;
25011 amit.gupta 43
 
30289 amit.gupta 44
 
31828 amit.gupta 45
    @Autowired
46
    ObjectMapper objectMapper;
25726 amit.gupta 47
 
31828 amit.gupta 48
    public RestClient() {
49
        PoolingHttpClientConnectionManager connManager
50
                = new PoolingHttpClientConnectionManager();
36416 amit 51
        connManager.setMaxTotal(20);
52
        connManager.setDefaultMaxPerRoute(8);
31828 amit.gupta 53
        httpClient = HttpClients.custom().disableCookieManagement().disableAuthCaching().disableConnectionState().
36416 amit 54
                disableAuthCaching().setConnectionManager(connManager)
55
                .setDefaultRequestConfig(HttpClientFactory.defaultRequestConfig())
56
                .build();
25244 amit.gupta 57
 
31828 amit.gupta 58
    }
25011 amit.gupta 59
 
31828 amit.gupta 60
    public RestClient(int connectionTimeoutMillis) {
36416 amit 61
        this.httpClient = HttpClientBuilder.create().disableCookieManagement()
62
                .setDefaultRequestConfig(HttpClientFactory.defaultRequestConfig()).build();
25244 amit.gupta 63
 
31828 amit.gupta 64
    }
25244 amit.gupta 65
 
31828 amit.gupta 66
    public String get(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
67
                      Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
68
        String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
69
                : scheme.getValue() + hostName + ":" + port + "/" + uri;
70
        return this.get(url, params, headers);
71
    }
25011 amit.gupta 72
 
31828 amit.gupta 73
    public String get(String url, Map<String, String> params, Map<String, String> headers)
74
            throws ProfitMandiBusinessException, HttpHostConnectException {
75
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
76
        if (params != null) {
77
            Set<String> keys = params.keySet();
78
            for (String key : keys) {
79
                builder.queryParam(key, params.get(key));
80
            }
81
        }
82
        HttpGet request = new HttpGet(builder.build().encode().toUri());
83
        if (headers != null) {
84
            for (Map.Entry<String, String> entry : headers.entrySet()) {
85
                request.setHeader(entry.getKey(), entry.getValue());
86
            }
87
        }
88
        return this.execute(request);
89
    }
22233 amit.gupta 90
 
31828 amit.gupta 91
    public MandiiResponse getMandii(String url, Map<String, String> params, Map<String, String> headers)
92
            throws ProfitMandiBusinessException, HttpHostConnectException {
93
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
94
        if (params != null) {
95
            Set<String> keys = params.keySet();
96
            for (String key : keys) {
97
                builder.queryParam(key, params.get(key));
98
            }
99
        }
100
        HttpGet request = new HttpGet(builder.build().encode().toUri());
101
        for (Map.Entry<String, String> entry : headers.entrySet()) {
102
            request.setHeader(entry.getKey(), entry.getValue());
103
        }
104
        return this.executeMandii(request);
105
    }
29834 tejbeer 106
 
31828 amit.gupta 107
    public String get(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params)
108
            throws ProfitMandiBusinessException, HttpHostConnectException {
109
        String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
110
                : scheme.getValue() + hostName + ":" + port + "/" + uri;
111
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
112
        if (params != null) {
113
            Set<String> keys = params.keySet();
114
            for (String key : keys) {
115
                builder.queryParam(key, params.get(key));
116
            }
117
        }
118
        HttpGet request = new HttpGet(builder.build().encode().toUri());
119
        return this.execute(request);
120
    }
25011 amit.gupta 121
 
31828 amit.gupta 122
    public HttpResponse getResponse(String url, Map<String, String> params, Map<String, String> headers)
123
            throws ProfitMandiBusinessException, HttpHostConnectException {
124
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
125
        if (params != null) {
126
            for (Map.Entry<String, String> paramsEntry : params.entrySet()) {
127
                builder.queryParam(paramsEntry.getKey(), paramsEntry.getValue());
128
            }
30289 amit.gupta 129
 
31828 amit.gupta 130
        }
131
        HttpGet request = new HttpGet(builder.build().encode().toUri());
132
        if (headers != null) {
133
            for (Map.Entry<String, String> entry : headers.entrySet()) {
134
                request.setHeader(entry.getKey(), entry.getValue());
135
            }
136
        }
137
        try {
138
            LOGGER.info("Request uri is  {}", request.getURI().toString());
139
            HttpResponse response = httpClient.execute(request);
140
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
141
            if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
142
                return response;
143
            } else {
144
                throw new ProfitMandiBusinessException("", "", "GE_1005");
145
            }
146
        } catch (HttpHostConnectException httpHostConnectException) {
147
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
148
            throw httpHostConnectException;
149
        } catch (ClientProtocolException e) {
150
            LOGGER.error("Client Error : ", e);
151
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
152
        } catch (IOException e) {
153
            LOGGER.error("IO Error : ", e);
154
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
155
        }
156
    }
25011 amit.gupta 157
 
31828 amit.gupta 158
    public String execute(HttpUriRequest request) throws ProfitMandiBusinessException, HttpHostConnectException {
159
        LOGGER.info("Connecting to server at url {}", request.getURI());
36295 amit 160
        HttpResponse response = null;
31828 amit.gupta 161
        try {
36295 amit 162
            response = httpClient.execute(request);
31828 amit.gupta 163
            String responseString = this.toString(response.getEntity().getContent());
164
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
165
            LOGGER.info("Response String {}", responseString);
34877 ranu 166
            if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()  || response.getStatusLine().getStatusCode() == HttpStatus.CREATED.value() || response.getStatusLine().getStatusCode() == HttpStatus.ACCEPTED.value()) {
31828 amit.gupta 167
                return responseString;
168
            } else {
169
                LOGGER.info("Response String {} ", responseString);
170
                throw new ProfitMandiBusinessException("", "", "GE_1005");
171
            }
172
        } catch (HttpHostConnectException httpHostConnectException) {
173
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
174
            throw httpHostConnectException;
175
        } catch (ClientProtocolException e) {
176
            LOGGER.error("Client Error : ", e);
177
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
178
        } catch (IOException e) {
179
            LOGGER.error("IO Error : ", e);
180
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
36295 amit 181
        } finally {
182
            if (response != null) EntityUtils.consumeQuietly(response.getEntity());
31828 amit.gupta 183
        }
184
    }
25011 amit.gupta 185
 
31828 amit.gupta 186
    public MandiiResponse executeMandii(HttpUriRequest request)
187
            throws ProfitMandiBusinessException, HttpHostConnectException {
188
        LOGGER.info("Connecting to server at url {}", request.getURI());
36295 amit 189
        HttpResponse response = null;
31828 amit.gupta 190
        try {
36295 amit 191
            response = httpClient.execute(request);
31828 amit.gupta 192
            String responseString = this.toString(response.getEntity().getContent());
193
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
29834 tejbeer 194
 
31828 amit.gupta 195
            MandiiResponse mandiiResponse = new MandiiResponse();
196
            mandiiResponse.setResponseString(responseString);
197
            mandiiResponse.setStatusCode(response.getStatusLine().getStatusCode());
29834 tejbeer 198
 
31828 amit.gupta 199
            return mandiiResponse;
200
        } catch (HttpHostConnectException httpHostConnectException) {
201
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
202
            throw httpHostConnectException;
203
        } catch (ClientProtocolException e) {
204
            LOGGER.error("Client Error : ", e);
205
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
206
        } catch (IOException e) {
207
            LOGGER.error("IO Error : ", e);
208
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
36295 amit 209
        } finally {
210
            if (response != null) EntityUtils.consumeQuietly(response.getEntity());
31828 amit.gupta 211
        }
212
    }
29834 tejbeer 213
 
31828 amit.gupta 214
    public String executeJson(HttpUriRequest request) throws ProfitMandiBusinessException, HttpHostConnectException {
215
        LOGGER.info("Connecting to server at url {}", request.getURI());
36295 amit 216
        HttpResponse response = null;
31828 amit.gupta 217
        try {
36295 amit 218
            response = httpClient.execute(request);
31828 amit.gupta 219
            String responseString = this.toString(response.getEntity().getContent());
220
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
221
            LOGGER.info("Response String {}", responseString);
222
            return responseString;
223
        } catch (HttpHostConnectException httpHostConnectException) {
224
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
225
            throw httpHostConnectException;
226
        } catch (ClientProtocolException e) {
227
            LOGGER.error("Client Error : ", e);
228
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
229
        } catch (IOException e) {
230
            LOGGER.error("IO Error : ", e);
231
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
36295 amit 232
        } finally {
233
            if (response != null) EntityUtils.consumeQuietly(response.getEntity());
31828 amit.gupta 234
        }
235
    }
27179 amit.gupta 236
 
35623 amit 237
    public HttpResponse postResponse(String url, Map<String, String> params, Map<String, String> headers)
238
            throws ProfitMandiBusinessException, HttpHostConnectException {
239
        List<NameValuePair> bodyParameters = new ArrayList<>();
240
        if (params != null) {
241
            for (Map.Entry<String, String> entry : params.entrySet()) {
242
                bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
243
            }
244
        }
245
        HttpPost request = new HttpPost(url);
246
        if (headers != null) {
247
            for (Map.Entry<String, String> entry : headers.entrySet()) {
248
                request.setHeader(entry.getKey(), entry.getValue());
249
            }
250
        }
251
        try {
252
            request.setEntity(new UrlEncodedFormEntity(bodyParameters));
253
            LOGGER.info("Request uri is  {}", request.getURI().toString());
254
            HttpResponse response = httpClient.execute(request);
255
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
256
            if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
257
                return response;
258
            } else {
259
                throw new ProfitMandiBusinessException("", "", "GE_1005");
260
            }
261
        } catch (HttpHostConnectException httpHostConnectException) {
262
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
263
            throw httpHostConnectException;
264
        } catch (ClientProtocolException e) {
265
            LOGGER.error("Client Error : ", e);
266
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
267
        } catch (IOException e) {
268
            LOGGER.error("IO Error : ", e);
269
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
270
        }
271
    }
272
 
31828 amit.gupta 273
    public String post(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
274
                       Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
275
        String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
276
                : scheme.getValue() + hostName + ":" + port + "/" + uri;
277
        return this.post(url, params, headers);
278
    }
25011 amit.gupta 279
 
31828 amit.gupta 280
    public String post(String url, Map<String, String> params, Map<String, String> headers)
281
            throws ProfitMandiBusinessException, HttpHostConnectException {
282
        // UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
283
        List<NameValuePair> bodyParameters = new ArrayList<NameValuePair>();
284
        for (Map.Entry<String, String> entry : params.entrySet()) {
285
            bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
286
        }
25011 amit.gupta 287
 
31828 amit.gupta 288
        LOGGER.info("Body Parameters {}", params);
289
        HttpPost request = new HttpPost(url);
290
        for (Map.Entry<String, String> entry : headers.entrySet()) {
291
            request.setHeader(entry.getKey(), entry.getValue());
292
        }
25011 amit.gupta 293
 
31828 amit.gupta 294
        try {
295
            request.setEntity(new UrlEncodedFormEntity(bodyParameters));
296
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
297
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
298
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
299
        }
25011 amit.gupta 300
 
31828 amit.gupta 301
        return this.execute(request);
25011 amit.gupta 302
 
31828 amit.gupta 303
    }
25011 amit.gupta 304
 
31828 amit.gupta 305
    public String post(String url, Map<String, String> queryParams, Map<String, String> postParams, Map<String, String> headers)
306
            throws ProfitMandiBusinessException, HttpHostConnectException {
307
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
308
        if (queryParams != null) {
309
            Set<String> keys = queryParams.keySet();
310
            for (String key : keys) {
311
                builder.queryParam(key, queryParams.get(key));
312
            }
313
        }
314
        List<NameValuePair> bodyParameters = new ArrayList<>();
315
        for (Map.Entry<String, String> entry : postParams.entrySet()) {
316
            bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
317
        }
28653 amit.gupta 318
 
31828 amit.gupta 319
        HttpPost request = new HttpPost(builder.build().encode().toUri());
320
        for (Map.Entry<String, String> entry : headers.entrySet()) {
321
            request.setHeader(entry.getKey(), entry.getValue());
322
        }
28653 amit.gupta 323
 
31828 amit.gupta 324
        try {
325
            request.setEntity(new UrlEncodedFormEntity(bodyParameters));
326
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
327
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
328
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
329
        }
28653 amit.gupta 330
 
31828 amit.gupta 331
        return this.execute(request);
28653 amit.gupta 332
 
31828 amit.gupta 333
    }
25011 amit.gupta 334
 
31828 amit.gupta 335
    public String post(String url, String body, Map<String, String> headers)
336
            throws ProfitMandiBusinessException, HttpHostConnectException {
337
        HttpPost request = new HttpPost(url);
338
        for (Map.Entry<String, String> entry : headers.entrySet()) {
339
            request.setHeader(entry.getKey(), entry.getValue());
340
        }
25726 amit.gupta 341
 
31828 amit.gupta 342
        try {
343
            request.setEntity(new StringEntity(body));
344
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
345
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
346
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
347
        }
29834 tejbeer 348
 
31828 amit.gupta 349
        return this.execute(request);
29834 tejbeer 350
 
31828 amit.gupta 351
    }
29834 tejbeer 352
 
31828 amit.gupta 353
    public String postJson(String url, Object object, Map<String, String> headers)
354
            throws ProfitMandiBusinessException, HttpHostConnectException {
355
        String jsonString;
356
        try {
357
            if (object.getClass().equals(String.class)) {
358
                jsonString = (String) object;
359
            } else {
360
                jsonString = objectMapper.writeValueAsString(object);
361
            }
362
            LOGGER.info("JSON String - {}", jsonString);
363
        } catch (Exception e) {
364
            e.printStackTrace();
365
            throw new ProfitMandiBusinessException("Json Object", object.toString(), "Could not write as String");
366
        }
367
        StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
25011 amit.gupta 368
 
31828 amit.gupta 369
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
27179 amit.gupta 370
 
31828 amit.gupta 371
        HttpPost request = new HttpPost(builder.build().encode().toUri());
372
        for (Map.Entry<String, String> entry : headers.entrySet()) {
373
            request.setHeader(entry.getKey(), entry.getValue());
374
        }
375
        request.setEntity(requestEntity);
376
        return this.executeJson(request);
377
    }
378
 
36200 ranu 379
    public MandiiResponse postWithResponse(String url, String body, Map<String, String> headers)
380
            throws ProfitMandiBusinessException, HttpHostConnectException {
381
        HttpPost request = new HttpPost(url);
382
        for (Map.Entry<String, String> entry : headers.entrySet()) {
383
            request.setHeader(entry.getKey(), entry.getValue());
384
        }
385
        try {
386
            request.setEntity(new StringEntity(body));
387
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
388
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
389
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
390
        }
391
        return this.executeMandii(request);
392
    }
393
 
31828 amit.gupta 394
    public String patchJson(String url, Object object, Map<String, String> headers)
395
            throws ProfitMandiBusinessException, HttpHostConnectException {
396
        String jsonString;
397
        try {
398
            if (object.getClass().equals(String.class)) {
399
                jsonString = (String) object;
400
            } else {
401
                jsonString = objectMapper.writeValueAsString(object);
402
            }
403
            LOGGER.info("JSON String - {}", jsonString);
404
        } catch (Exception e) {
405
            e.printStackTrace();
406
            throw new ProfitMandiBusinessException("Json Object", object.toString(), "Could not write as String");
407
        }
408
        StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
409
 
410
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
411
 
412
        HttpPatch request = new HttpPatch(builder.build().encode().toUri());
413
        for (Map.Entry<String, String> entry : headers.entrySet()) {
414
            request.setHeader(entry.getKey(), entry.getValue());
415
        }
416
        request.setEntity(requestEntity);
417
        return this.executeJson(request);
418
    }
419
 
420
    private String toString(InputStream inputStream) {
421
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
422
        StringBuilder responseString = new StringBuilder();
423
        String line = null;
424
        try {
425
            while ((line = reader.readLine()) != null) {
426
                responseString.append(line);
427
            }
428
            inputStream.close();
429
        } catch (IOException e) {
430
            throw new RuntimeException();
431
        }
432
        return responseString.toString();
433
    }
34805 ranu 434
 
435
    public byte[] postForBytes(String url, String payload, Map<String, String> headers) throws IOException {
436
        HttpPost post = new HttpPost(url);
437
        headers.forEach(post::setHeader);
438
 
439
        post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));
440
 
36416 amit 441
        try (CloseableHttpClient client = HttpClientFactory.apacheHttp();
34805 ranu 442
             CloseableHttpResponse response = client.execute(post)) {
443
 
444
            int statusCode = response.getStatusLine().getStatusCode();
445
            if (statusCode != 200) {
446
                throw new IOException("Failed : HTTP error code : " + statusCode);
447
            }
448
 
449
            return EntityUtils.toByteArray(response.getEntity());
450
        }
451
    }
452
 
21557 ashik.ali 453
}