Subversion Repositories SmartDukaan

Rev

Rev 34805 | 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
 
31828 amit.gupta 226
    public String post(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
227
                       Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
228
        String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
229
                : scheme.getValue() + hostName + ":" + port + "/" + uri;
230
        return this.post(url, params, headers);
231
    }
25011 amit.gupta 232
 
31828 amit.gupta 233
    public String post(String url, Map<String, String> params, Map<String, String> headers)
234
            throws ProfitMandiBusinessException, HttpHostConnectException {
235
        // UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
236
        List<NameValuePair> bodyParameters = new ArrayList<NameValuePair>();
237
        for (Map.Entry<String, String> entry : params.entrySet()) {
238
            bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
239
        }
25011 amit.gupta 240
 
31828 amit.gupta 241
        LOGGER.info("Body Parameters {}", params);
242
        HttpPost request = new HttpPost(url);
243
        for (Map.Entry<String, String> entry : headers.entrySet()) {
244
            request.setHeader(entry.getKey(), entry.getValue());
245
        }
25011 amit.gupta 246
 
31828 amit.gupta 247
        try {
248
            request.setEntity(new UrlEncodedFormEntity(bodyParameters));
249
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
250
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
251
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
252
        }
25011 amit.gupta 253
 
31828 amit.gupta 254
        return this.execute(request);
25011 amit.gupta 255
 
31828 amit.gupta 256
    }
25011 amit.gupta 257
 
31828 amit.gupta 258
    public String post(String url, Map<String, String> queryParams, Map<String, String> postParams, Map<String, String> headers)
259
            throws ProfitMandiBusinessException, HttpHostConnectException {
260
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
261
        if (queryParams != null) {
262
            Set<String> keys = queryParams.keySet();
263
            for (String key : keys) {
264
                builder.queryParam(key, queryParams.get(key));
265
            }
266
        }
267
        List<NameValuePair> bodyParameters = new ArrayList<>();
268
        for (Map.Entry<String, String> entry : postParams.entrySet()) {
269
            bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
270
        }
28653 amit.gupta 271
 
31828 amit.gupta 272
        HttpPost request = new HttpPost(builder.build().encode().toUri());
273
        for (Map.Entry<String, String> entry : headers.entrySet()) {
274
            request.setHeader(entry.getKey(), entry.getValue());
275
        }
28653 amit.gupta 276
 
31828 amit.gupta 277
        try {
278
            request.setEntity(new UrlEncodedFormEntity(bodyParameters));
279
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
280
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
281
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
282
        }
28653 amit.gupta 283
 
31828 amit.gupta 284
        return this.execute(request);
28653 amit.gupta 285
 
31828 amit.gupta 286
    }
25011 amit.gupta 287
 
31828 amit.gupta 288
    public String post(String url, String body, Map<String, String> headers)
289
            throws ProfitMandiBusinessException, HttpHostConnectException {
290
        HttpPost request = new HttpPost(url);
291
        for (Map.Entry<String, String> entry : headers.entrySet()) {
292
            request.setHeader(entry.getKey(), entry.getValue());
293
        }
25726 amit.gupta 294
 
31828 amit.gupta 295
        try {
296
            request.setEntity(new StringEntity(body));
297
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
298
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
299
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
300
        }
29834 tejbeer 301
 
31828 amit.gupta 302
        return this.execute(request);
29834 tejbeer 303
 
31828 amit.gupta 304
    }
29834 tejbeer 305
 
31828 amit.gupta 306
    public String postJson(String url, Object object, Map<String, String> headers)
307
            throws ProfitMandiBusinessException, HttpHostConnectException {
308
        String jsonString;
309
        try {
310
            if (object.getClass().equals(String.class)) {
311
                jsonString = (String) object;
312
            } else {
313
                jsonString = objectMapper.writeValueAsString(object);
314
            }
315
            LOGGER.info("JSON String - {}", jsonString);
316
        } catch (Exception e) {
317
            e.printStackTrace();
318
            throw new ProfitMandiBusinessException("Json Object", object.toString(), "Could not write as String");
319
        }
320
        StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
25011 amit.gupta 321
 
31828 amit.gupta 322
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
27179 amit.gupta 323
 
31828 amit.gupta 324
        HttpPost request = new HttpPost(builder.build().encode().toUri());
325
        for (Map.Entry<String, String> entry : headers.entrySet()) {
326
            request.setHeader(entry.getKey(), entry.getValue());
327
        }
328
        request.setEntity(requestEntity);
329
        return this.executeJson(request);
330
    }
331
 
332
    public String patchJson(String url, Object object, Map<String, String> headers)
333
            throws ProfitMandiBusinessException, HttpHostConnectException {
334
        String jsonString;
335
        try {
336
            if (object.getClass().equals(String.class)) {
337
                jsonString = (String) object;
338
            } else {
339
                jsonString = objectMapper.writeValueAsString(object);
340
            }
341
            LOGGER.info("JSON String - {}", jsonString);
342
        } catch (Exception e) {
343
            e.printStackTrace();
344
            throw new ProfitMandiBusinessException("Json Object", object.toString(), "Could not write as String");
345
        }
346
        StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
347
 
348
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
349
 
350
        HttpPatch request = new HttpPatch(builder.build().encode().toUri());
351
        for (Map.Entry<String, String> entry : headers.entrySet()) {
352
            request.setHeader(entry.getKey(), entry.getValue());
353
        }
354
        request.setEntity(requestEntity);
355
        return this.executeJson(request);
356
    }
357
 
358
    private String toString(InputStream inputStream) {
359
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
360
        StringBuilder responseString = new StringBuilder();
361
        String line = null;
362
        try {
363
            while ((line = reader.readLine()) != null) {
364
                responseString.append(line);
365
            }
366
            inputStream.close();
367
        } catch (IOException e) {
368
            throw new RuntimeException();
369
        }
370
        return responseString.toString();
371
    }
34805 ranu 372
 
373
    public byte[] postForBytes(String url, String payload, Map<String, String> headers) throws IOException {
374
        HttpPost post = new HttpPost(url);
375
        headers.forEach(post::setHeader);
376
 
377
        post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));
378
 
379
        try (CloseableHttpClient client = HttpClients.createDefault();
380
             CloseableHttpResponse response = client.execute(post)) {
381
 
382
            int statusCode = response.getStatusLine().getStatusCode();
383
            if (statusCode != 200) {
384
                throw new IOException("Failed : HTTP error code : " + statusCode);
385
            }
386
 
387
            return EntityUtils.toByteArray(response.getEntity());
388
        }
389
    }
390
 
21557 ashik.ali 391
}