Subversion Repositories SmartDukaan

Rev

Rev 31828 | Rev 34805 | 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;
21557 ashik.ali 14
import org.apache.http.client.methods.HttpGet;
29710 amit.gupta 15
import org.apache.http.client.methods.HttpPatch;
22215 ashik.ali 16
import org.apache.http.client.methods.HttpPost;
17
import org.apache.http.client.methods.HttpUriRequest;
23502 ashik.ali 18
import org.apache.http.conn.HttpHostConnectException;
19
import org.apache.http.entity.ContentType;
20
import org.apache.http.entity.StringEntity;
25244 amit.gupta 21
import org.apache.http.impl.client.HttpClientBuilder;
21557 ashik.ali 22
import org.apache.http.impl.client.HttpClients;
30383 amit.gupta 23
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
22215 ashik.ali 24
import org.apache.http.message.BasicNameValuePair;
25011 amit.gupta 25
import org.apache.logging.log4j.LogManager;
23568 govind 26
import org.apache.logging.log4j.Logger;
25726 amit.gupta 27
import org.springframework.beans.factory.annotation.Autowired;
21557 ashik.ali 28
import org.springframework.http.HttpStatus;
23526 ashik.ali 29
import org.springframework.stereotype.Component;
21557 ashik.ali 30
import org.springframework.web.util.UriComponentsBuilder;
31
 
30289 amit.gupta 32
import java.io.*;
33
import java.util.ArrayList;
34
import java.util.List;
35
import java.util.Map;
36
import java.util.Set;
21557 ashik.ali 37
 
23526 ashik.ali 38
@Component
21557 ashik.ali 39
public class RestClient {
25011 amit.gupta 40
 
31828 amit.gupta 41
    private static final Logger LOGGER = LogManager.getLogger(RestClient.class);
25011 amit.gupta 42
 
31828 amit.gupta 43
    private HttpClient httpClient;
25011 amit.gupta 44
 
30289 amit.gupta 45
 
31828 amit.gupta 46
    @Autowired
47
    ObjectMapper objectMapper;
25726 amit.gupta 48
 
31828 amit.gupta 49
    public RestClient() {
50
        PoolingHttpClientConnectionManager connManager
51
                = new PoolingHttpClientConnectionManager();
52
        connManager.setMaxTotal(5);
53
        connManager.setDefaultMaxPerRoute(4);
54
        httpClient = HttpClients.custom().disableCookieManagement().disableAuthCaching().disableConnectionState().
55
                disableAuthCaching().setConnectionManager(connManager).build();
25244 amit.gupta 56
 
31828 amit.gupta 57
    }
25011 amit.gupta 58
 
31828 amit.gupta 59
    public RestClient(int connectionTimeoutMillis) {
60
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5 * 1000).build();
61
        this.httpClient = HttpClientBuilder.create().disableCookieManagement().setDefaultRequestConfig(requestConfig).build();
25244 amit.gupta 62
 
31828 amit.gupta 63
    }
25244 amit.gupta 64
 
31828 amit.gupta 65
    public String get(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
66
                      Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
67
        String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
68
                : scheme.getValue() + hostName + ":" + port + "/" + uri;
69
        return this.get(url, params, headers);
70
    }
25011 amit.gupta 71
 
31828 amit.gupta 72
    public String get(String url, Map<String, String> params, Map<String, String> headers)
73
            throws ProfitMandiBusinessException, HttpHostConnectException {
74
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
75
        if (params != null) {
76
            Set<String> keys = params.keySet();
77
            for (String key : keys) {
78
                builder.queryParam(key, params.get(key));
79
            }
80
        }
81
        HttpGet request = new HttpGet(builder.build().encode().toUri());
82
        if (headers != null) {
83
            for (Map.Entry<String, String> entry : headers.entrySet()) {
84
                request.setHeader(entry.getKey(), entry.getValue());
85
            }
86
        }
87
        return this.execute(request);
88
    }
22233 amit.gupta 89
 
31828 amit.gupta 90
    public MandiiResponse getMandii(String url, Map<String, String> params, Map<String, String> headers)
91
            throws ProfitMandiBusinessException, HttpHostConnectException {
92
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
93
        if (params != null) {
94
            Set<String> keys = params.keySet();
95
            for (String key : keys) {
96
                builder.queryParam(key, params.get(key));
97
            }
98
        }
99
        HttpGet request = new HttpGet(builder.build().encode().toUri());
100
        for (Map.Entry<String, String> entry : headers.entrySet()) {
101
            request.setHeader(entry.getKey(), entry.getValue());
102
        }
103
        return this.executeMandii(request);
104
    }
29834 tejbeer 105
 
31828 amit.gupta 106
    public String get(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params)
107
            throws ProfitMandiBusinessException, HttpHostConnectException {
108
        String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
109
                : scheme.getValue() + hostName + ":" + port + "/" + uri;
110
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
111
        if (params != null) {
112
            Set<String> keys = params.keySet();
113
            for (String key : keys) {
114
                builder.queryParam(key, params.get(key));
115
            }
116
        }
117
        HttpGet request = new HttpGet(builder.build().encode().toUri());
118
        return this.execute(request);
119
    }
25011 amit.gupta 120
 
31828 amit.gupta 121
    public HttpResponse getResponse(String url, Map<String, String> params, Map<String, String> headers)
122
            throws ProfitMandiBusinessException, HttpHostConnectException {
123
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
124
        if (params != null) {
125
            for (Map.Entry<String, String> paramsEntry : params.entrySet()) {
126
                builder.queryParam(paramsEntry.getKey(), paramsEntry.getValue());
127
            }
30289 amit.gupta 128
 
31828 amit.gupta 129
        }
130
        HttpGet request = new HttpGet(builder.build().encode().toUri());
131
        if (headers != null) {
132
            for (Map.Entry<String, String> entry : headers.entrySet()) {
133
                request.setHeader(entry.getKey(), entry.getValue());
134
            }
135
        }
136
        try {
137
            LOGGER.info("Request uri is  {}", request.getURI().toString());
138
            HttpResponse response = httpClient.execute(request);
139
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
140
            if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
141
                return response;
142
            } else {
143
                throw new ProfitMandiBusinessException("", "", "GE_1005");
144
            }
145
        } catch (HttpHostConnectException httpHostConnectException) {
146
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
147
            throw httpHostConnectException;
148
        } catch (ClientProtocolException e) {
149
            LOGGER.error("Client Error : ", e);
150
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
151
        } catch (IOException e) {
152
            LOGGER.error("IO Error : ", e);
153
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
154
        }
155
    }
25011 amit.gupta 156
 
31828 amit.gupta 157
    public String execute(HttpUriRequest request) throws ProfitMandiBusinessException, HttpHostConnectException {
158
        LOGGER.info("Connecting to server at url {}", request.getURI());
159
        try {
160
            HttpResponse response = httpClient.execute(request);
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);
164
            if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
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"));
179
        }
180
    }
25011 amit.gupta 181
 
31828 amit.gupta 182
    public MandiiResponse executeMandii(HttpUriRequest request)
183
            throws ProfitMandiBusinessException, HttpHostConnectException {
184
        LOGGER.info("Connecting to server at url {}", request.getURI());
185
        try {
186
            HttpResponse response = httpClient.execute(request);
187
            String responseString = this.toString(response.getEntity().getContent());
188
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
29834 tejbeer 189
 
31828 amit.gupta 190
            MandiiResponse mandiiResponse = new MandiiResponse();
191
            mandiiResponse.setResponseString(responseString);
192
            mandiiResponse.setStatusCode(response.getStatusLine().getStatusCode());
29834 tejbeer 193
 
31828 amit.gupta 194
            return mandiiResponse;
195
        } catch (HttpHostConnectException httpHostConnectException) {
196
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
197
            throw httpHostConnectException;
198
        } catch (ClientProtocolException e) {
199
            LOGGER.error("Client Error : ", e);
200
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
201
        } catch (IOException e) {
202
            LOGGER.error("IO Error : ", e);
203
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
204
        }
205
    }
29834 tejbeer 206
 
31828 amit.gupta 207
    public String executeJson(HttpUriRequest request) throws ProfitMandiBusinessException, HttpHostConnectException {
208
        LOGGER.info("Connecting to server at url {}", request.getURI());
209
        try {
210
            HttpResponse response = httpClient.execute(request);
211
            String responseString = this.toString(response.getEntity().getContent());
212
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
213
            LOGGER.info("Response String {}", responseString);
214
            return responseString;
215
        } catch (HttpHostConnectException httpHostConnectException) {
216
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
217
            throw httpHostConnectException;
218
        } catch (ClientProtocolException e) {
219
            LOGGER.error("Client Error : ", e);
220
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
221
        } catch (IOException e) {
222
            LOGGER.error("IO Error : ", e);
223
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
224
        }
225
    }
27179 amit.gupta 226
 
31828 amit.gupta 227
    public String post(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
228
                       Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
229
        String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
230
                : scheme.getValue() + hostName + ":" + port + "/" + uri;
231
        return this.post(url, params, headers);
232
    }
25011 amit.gupta 233
 
31828 amit.gupta 234
    public String post(String url, Map<String, String> params, Map<String, String> headers)
235
            throws ProfitMandiBusinessException, HttpHostConnectException {
236
        // UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
237
        List<NameValuePair> bodyParameters = new ArrayList<NameValuePair>();
238
        for (Map.Entry<String, String> entry : params.entrySet()) {
239
            bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
240
        }
25011 amit.gupta 241
 
31828 amit.gupta 242
        LOGGER.info("Body Parameters {}", params);
243
        HttpPost request = new HttpPost(url);
244
        for (Map.Entry<String, String> entry : headers.entrySet()) {
245
            request.setHeader(entry.getKey(), entry.getValue());
246
        }
25011 amit.gupta 247
 
31828 amit.gupta 248
        try {
249
            request.setEntity(new UrlEncodedFormEntity(bodyParameters));
250
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
251
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
252
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
253
        }
25011 amit.gupta 254
 
31828 amit.gupta 255
        return this.execute(request);
25011 amit.gupta 256
 
31828 amit.gupta 257
    }
25011 amit.gupta 258
 
31828 amit.gupta 259
    public String post(String url, Map<String, String> queryParams, Map<String, String> postParams, Map<String, String> headers)
260
            throws ProfitMandiBusinessException, HttpHostConnectException {
261
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
262
        if (queryParams != null) {
263
            Set<String> keys = queryParams.keySet();
264
            for (String key : keys) {
265
                builder.queryParam(key, queryParams.get(key));
266
            }
267
        }
268
        List<NameValuePair> bodyParameters = new ArrayList<>();
269
        for (Map.Entry<String, String> entry : postParams.entrySet()) {
270
            bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
271
        }
28653 amit.gupta 272
 
31828 amit.gupta 273
        HttpPost request = new HttpPost(builder.build().encode().toUri());
274
        for (Map.Entry<String, String> entry : headers.entrySet()) {
275
            request.setHeader(entry.getKey(), entry.getValue());
276
        }
28653 amit.gupta 277
 
31828 amit.gupta 278
        try {
279
            request.setEntity(new UrlEncodedFormEntity(bodyParameters));
280
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
281
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
282
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
283
        }
28653 amit.gupta 284
 
31828 amit.gupta 285
        return this.execute(request);
28653 amit.gupta 286
 
31828 amit.gupta 287
    }
25011 amit.gupta 288
 
31828 amit.gupta 289
    public String post(String url, String body, Map<String, String> headers)
290
            throws ProfitMandiBusinessException, HttpHostConnectException {
291
        HttpPost request = new HttpPost(url);
292
        for (Map.Entry<String, String> entry : headers.entrySet()) {
293
            request.setHeader(entry.getKey(), entry.getValue());
294
        }
25726 amit.gupta 295
 
31828 amit.gupta 296
        try {
297
            request.setEntity(new StringEntity(body));
298
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
299
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
300
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
301
        }
29834 tejbeer 302
 
31828 amit.gupta 303
        return this.execute(request);
29834 tejbeer 304
 
31828 amit.gupta 305
    }
29834 tejbeer 306
 
31828 amit.gupta 307
    public String postJson(String url, Object object, Map<String, String> headers)
308
            throws ProfitMandiBusinessException, HttpHostConnectException {
309
        String jsonString;
310
        try {
311
            if (object.getClass().equals(String.class)) {
312
                jsonString = (String) object;
313
            } else {
314
                jsonString = objectMapper.writeValueAsString(object);
315
            }
316
            LOGGER.info("JSON String - {}", jsonString);
317
        } catch (Exception e) {
318
            e.printStackTrace();
319
            throw new ProfitMandiBusinessException("Json Object", object.toString(), "Could not write as String");
320
        }
321
        StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
25011 amit.gupta 322
 
31828 amit.gupta 323
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
27179 amit.gupta 324
 
31828 amit.gupta 325
        HttpPost request = new HttpPost(builder.build().encode().toUri());
326
        for (Map.Entry<String, String> entry : headers.entrySet()) {
327
            request.setHeader(entry.getKey(), entry.getValue());
328
        }
329
        request.setEntity(requestEntity);
330
        return this.executeJson(request);
331
    }
332
 
333
    public String patchJson(String url, Object object, Map<String, String> headers)
334
            throws ProfitMandiBusinessException, HttpHostConnectException {
335
        String jsonString;
336
        try {
337
            if (object.getClass().equals(String.class)) {
338
                jsonString = (String) object;
339
            } else {
340
                jsonString = objectMapper.writeValueAsString(object);
341
            }
342
            LOGGER.info("JSON String - {}", jsonString);
343
        } catch (Exception e) {
344
            e.printStackTrace();
345
            throw new ProfitMandiBusinessException("Json Object", object.toString(), "Could not write as String");
346
        }
347
        StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
348
 
349
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
350
 
351
        HttpPatch request = new HttpPatch(builder.build().encode().toUri());
352
        for (Map.Entry<String, String> entry : headers.entrySet()) {
353
            request.setHeader(entry.getKey(), entry.getValue());
354
        }
355
        request.setEntity(requestEntity);
356
        return this.executeJson(request);
357
    }
358
 
359
    private String toString(InputStream inputStream) {
360
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
361
        StringBuilder responseString = new StringBuilder();
362
        String line = null;
363
        try {
364
            while ((line = reader.readLine()) != null) {
365
                responseString.append(line);
366
            }
367
            inputStream.close();
368
        } catch (IOException e) {
369
            throw new RuntimeException();
370
        }
371
        return responseString.toString();
372
    }
21557 ashik.ali 373
}