Subversion Repositories SmartDukaan

Rev

Rev 34877 | 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());
158
        try {
159
            HttpResponse response = httpClient.execute(request);
160
            String responseString = this.toString(response.getEntity().getContent());
161
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
162
            LOGGER.info("Response String {}", responseString);
34877 ranu 163
            if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()  || response.getStatusLine().getStatusCode() == HttpStatus.CREATED.value() || response.getStatusLine().getStatusCode() == HttpStatus.ACCEPTED.value()) {
31828 amit.gupta 164
                return responseString;
165
            } else {
166
                LOGGER.info("Response String {} ", responseString);
167
                throw new ProfitMandiBusinessException("", "", "GE_1005");
168
            }
169
        } catch (HttpHostConnectException httpHostConnectException) {
170
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
171
            throw httpHostConnectException;
172
        } catch (ClientProtocolException e) {
173
            LOGGER.error("Client Error : ", e);
174
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
175
        } catch (IOException e) {
176
            LOGGER.error("IO Error : ", e);
177
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
178
        }
179
    }
25011 amit.gupta 180
 
31828 amit.gupta 181
    public MandiiResponse executeMandii(HttpUriRequest request)
182
            throws ProfitMandiBusinessException, HttpHostConnectException {
183
        LOGGER.info("Connecting to server at url {}", request.getURI());
184
        try {
185
            HttpResponse response = httpClient.execute(request);
186
            String responseString = this.toString(response.getEntity().getContent());
187
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
29834 tejbeer 188
 
31828 amit.gupta 189
            MandiiResponse mandiiResponse = new MandiiResponse();
190
            mandiiResponse.setResponseString(responseString);
191
            mandiiResponse.setStatusCode(response.getStatusLine().getStatusCode());
29834 tejbeer 192
 
31828 amit.gupta 193
            return mandiiResponse;
194
        } catch (HttpHostConnectException httpHostConnectException) {
195
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
196
            throw httpHostConnectException;
197
        } catch (ClientProtocolException e) {
198
            LOGGER.error("Client Error : ", e);
199
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
200
        } catch (IOException e) {
201
            LOGGER.error("IO Error : ", e);
202
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
203
        }
204
    }
29834 tejbeer 205
 
31828 amit.gupta 206
    public String executeJson(HttpUriRequest request) throws ProfitMandiBusinessException, HttpHostConnectException {
207
        LOGGER.info("Connecting to server at url {}", request.getURI());
208
        try {
209
            HttpResponse response = httpClient.execute(request);
210
            String responseString = this.toString(response.getEntity().getContent());
211
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
212
            LOGGER.info("Response String {}", responseString);
213
            return responseString;
214
        } catch (HttpHostConnectException httpHostConnectException) {
215
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
216
            throw httpHostConnectException;
217
        } catch (ClientProtocolException e) {
218
            LOGGER.error("Client Error : ", e);
219
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
220
        } catch (IOException e) {
221
            LOGGER.error("IO Error : ", e);
222
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
223
        }
224
    }
27179 amit.gupta 225
 
35623 amit 226
    public HttpResponse postResponse(String url, Map<String, String> params, Map<String, String> headers)
227
            throws ProfitMandiBusinessException, HttpHostConnectException {
228
        List<NameValuePair> bodyParameters = new ArrayList<>();
229
        if (params != null) {
230
            for (Map.Entry<String, String> entry : params.entrySet()) {
231
                bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
232
            }
233
        }
234
        HttpPost request = new HttpPost(url);
235
        if (headers != null) {
236
            for (Map.Entry<String, String> entry : headers.entrySet()) {
237
                request.setHeader(entry.getKey(), entry.getValue());
238
            }
239
        }
240
        try {
241
            request.setEntity(new UrlEncodedFormEntity(bodyParameters));
242
            LOGGER.info("Request uri is  {}", request.getURI().toString());
243
            HttpResponse response = httpClient.execute(request);
244
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
245
            if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
246
                return response;
247
            } else {
248
                throw new ProfitMandiBusinessException("", "", "GE_1005");
249
            }
250
        } catch (HttpHostConnectException httpHostConnectException) {
251
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
252
            throw httpHostConnectException;
253
        } catch (ClientProtocolException e) {
254
            LOGGER.error("Client Error : ", e);
255
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
256
        } catch (IOException e) {
257
            LOGGER.error("IO Error : ", e);
258
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
259
        }
260
    }
261
 
31828 amit.gupta 262
    public String post(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
263
                       Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
264
        String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
265
                : scheme.getValue() + hostName + ":" + port + "/" + uri;
266
        return this.post(url, params, headers);
267
    }
25011 amit.gupta 268
 
31828 amit.gupta 269
    public String post(String url, Map<String, String> params, Map<String, String> headers)
270
            throws ProfitMandiBusinessException, HttpHostConnectException {
271
        // UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
272
        List<NameValuePair> bodyParameters = new ArrayList<NameValuePair>();
273
        for (Map.Entry<String, String> entry : params.entrySet()) {
274
            bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
275
        }
25011 amit.gupta 276
 
31828 amit.gupta 277
        LOGGER.info("Body Parameters {}", params);
278
        HttpPost request = new HttpPost(url);
279
        for (Map.Entry<String, String> entry : headers.entrySet()) {
280
            request.setHeader(entry.getKey(), entry.getValue());
281
        }
25011 amit.gupta 282
 
31828 amit.gupta 283
        try {
284
            request.setEntity(new UrlEncodedFormEntity(bodyParameters));
285
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
286
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
287
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
288
        }
25011 amit.gupta 289
 
31828 amit.gupta 290
        return this.execute(request);
25011 amit.gupta 291
 
31828 amit.gupta 292
    }
25011 amit.gupta 293
 
31828 amit.gupta 294
    public String post(String url, Map<String, String> queryParams, Map<String, String> postParams, Map<String, String> headers)
295
            throws ProfitMandiBusinessException, HttpHostConnectException {
296
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
297
        if (queryParams != null) {
298
            Set<String> keys = queryParams.keySet();
299
            for (String key : keys) {
300
                builder.queryParam(key, queryParams.get(key));
301
            }
302
        }
303
        List<NameValuePair> bodyParameters = new ArrayList<>();
304
        for (Map.Entry<String, String> entry : postParams.entrySet()) {
305
            bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
306
        }
28653 amit.gupta 307
 
31828 amit.gupta 308
        HttpPost request = new HttpPost(builder.build().encode().toUri());
309
        for (Map.Entry<String, String> entry : headers.entrySet()) {
310
            request.setHeader(entry.getKey(), entry.getValue());
311
        }
28653 amit.gupta 312
 
31828 amit.gupta 313
        try {
314
            request.setEntity(new UrlEncodedFormEntity(bodyParameters));
315
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
316
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
317
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
318
        }
28653 amit.gupta 319
 
31828 amit.gupta 320
        return this.execute(request);
28653 amit.gupta 321
 
31828 amit.gupta 322
    }
25011 amit.gupta 323
 
31828 amit.gupta 324
    public String post(String url, String body, Map<String, String> headers)
325
            throws ProfitMandiBusinessException, HttpHostConnectException {
326
        HttpPost request = new HttpPost(url);
327
        for (Map.Entry<String, String> entry : headers.entrySet()) {
328
            request.setHeader(entry.getKey(), entry.getValue());
329
        }
25726 amit.gupta 330
 
31828 amit.gupta 331
        try {
332
            request.setEntity(new StringEntity(body));
333
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
334
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
335
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
336
        }
29834 tejbeer 337
 
31828 amit.gupta 338
        return this.execute(request);
29834 tejbeer 339
 
31828 amit.gupta 340
    }
29834 tejbeer 341
 
31828 amit.gupta 342
    public String postJson(String url, Object object, Map<String, String> headers)
343
            throws ProfitMandiBusinessException, HttpHostConnectException {
344
        String jsonString;
345
        try {
346
            if (object.getClass().equals(String.class)) {
347
                jsonString = (String) object;
348
            } else {
349
                jsonString = objectMapper.writeValueAsString(object);
350
            }
351
            LOGGER.info("JSON String - {}", jsonString);
352
        } catch (Exception e) {
353
            e.printStackTrace();
354
            throw new ProfitMandiBusinessException("Json Object", object.toString(), "Could not write as String");
355
        }
356
        StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
25011 amit.gupta 357
 
31828 amit.gupta 358
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
27179 amit.gupta 359
 
31828 amit.gupta 360
        HttpPost request = new HttpPost(builder.build().encode().toUri());
361
        for (Map.Entry<String, String> entry : headers.entrySet()) {
362
            request.setHeader(entry.getKey(), entry.getValue());
363
        }
364
        request.setEntity(requestEntity);
365
        return this.executeJson(request);
366
    }
367
 
368
    public String patchJson(String url, Object object, Map<String, String> headers)
369
            throws ProfitMandiBusinessException, HttpHostConnectException {
370
        String jsonString;
371
        try {
372
            if (object.getClass().equals(String.class)) {
373
                jsonString = (String) object;
374
            } else {
375
                jsonString = objectMapper.writeValueAsString(object);
376
            }
377
            LOGGER.info("JSON String - {}", jsonString);
378
        } catch (Exception e) {
379
            e.printStackTrace();
380
            throw new ProfitMandiBusinessException("Json Object", object.toString(), "Could not write as String");
381
        }
382
        StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
383
 
384
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
385
 
386
        HttpPatch request = new HttpPatch(builder.build().encode().toUri());
387
        for (Map.Entry<String, String> entry : headers.entrySet()) {
388
            request.setHeader(entry.getKey(), entry.getValue());
389
        }
390
        request.setEntity(requestEntity);
391
        return this.executeJson(request);
392
    }
393
 
394
    private String toString(InputStream inputStream) {
395
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
396
        StringBuilder responseString = new StringBuilder();
397
        String line = null;
398
        try {
399
            while ((line = reader.readLine()) != null) {
400
                responseString.append(line);
401
            }
402
            inputStream.close();
403
        } catch (IOException e) {
404
            throw new RuntimeException();
405
        }
406
        return responseString.toString();
407
    }
34805 ranu 408
 
409
    public byte[] postForBytes(String url, String payload, Map<String, String> headers) throws IOException {
410
        HttpPost post = new HttpPost(url);
411
        headers.forEach(post::setHeader);
412
 
413
        post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));
414
 
415
        try (CloseableHttpClient client = HttpClients.createDefault();
416
             CloseableHttpResponse response = client.execute(post)) {
417
 
418
            int statusCode = response.getStatusLine().getStatusCode();
419
            if (statusCode != 200) {
420
                throw new IOException("Failed : HTTP error code : " + statusCode);
421
            }
422
 
423
            return EntityUtils.toByteArray(response.getEntity());
424
        }
425
    }
426
 
21557 ashik.ali 427
}