Subversion Repositories SmartDukaan

Rev

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