Subversion Repositories SmartDukaan

Rev

Rev 37321 | 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();
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
 
37321 amit 66
    /**
67
     * RestClient on a caller-supplied timeout profile from {@link HttpClientFactory}. Not a
68
     * Spring bean — construct it explicitly where a non-default timeout is justified, and pass
69
     * the ObjectMapper in, since field injection does not apply to hand-built instances.
70
     */
71
    public RestClient(RequestConfig requestConfig, ObjectMapper objectMapper) {
72
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
73
        connManager.setMaxTotal(20);
74
        connManager.setDefaultMaxPerRoute(8);
75
        this.httpClient = HttpClients.custom().disableCookieManagement().disableAuthCaching()
76
                .disableConnectionState().setConnectionManager(connManager)
77
                .setDefaultRequestConfig(requestConfig)
78
                .build();
79
        this.objectMapper = objectMapper;
80
    }
81
 
31828 amit.gupta 82
    public String get(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
83
                      Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
84
        String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
85
                : scheme.getValue() + hostName + ":" + port + "/" + uri;
86
        return this.get(url, params, headers);
87
    }
25011 amit.gupta 88
 
31828 amit.gupta 89
    public String get(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
        if (headers != null) {
100
            for (Map.Entry<String, String> entry : headers.entrySet()) {
101
                request.setHeader(entry.getKey(), entry.getValue());
102
            }
103
        }
104
        return this.execute(request);
105
    }
22233 amit.gupta 106
 
37388 vikas 107
    /**
108
     * GET that returns the response body whatever the status code, rather than throwing and discarding
109
     * it as {@link #get(String, Map, Map)} does.
110
     *
111
     * <p>Use this against APIs that report their errors in a JSON body: with {@code get} a rejected
112
     * request surfaces as an exception carrying no detail, so the reason for the failure is lost. This
113
     * is the GET counterpart of {@link #postJson(String, Object, Map)}.</p>
114
     */
115
    public String getJson(String url, Map<String, String> params, Map<String, String> headers)
116
            throws ProfitMandiBusinessException, HttpHostConnectException {
117
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
118
        if (params != null) {
119
            Set<String> keys = params.keySet();
120
            for (String key : keys) {
121
                builder.queryParam(key, params.get(key));
122
            }
123
        }
124
        HttpGet request = new HttpGet(builder.build().encode().toUri());
125
        if (headers != null) {
126
            for (Map.Entry<String, String> entry : headers.entrySet()) {
127
                request.setHeader(entry.getKey(), entry.getValue());
128
            }
129
        }
130
        return this.executeJson(request);
131
    }
132
 
31828 amit.gupta 133
    public MandiiResponse getMandii(String url, Map<String, String> params, Map<String, String> headers)
134
            throws ProfitMandiBusinessException, HttpHostConnectException {
135
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
136
        if (params != null) {
137
            Set<String> keys = params.keySet();
138
            for (String key : keys) {
139
                builder.queryParam(key, params.get(key));
140
            }
141
        }
142
        HttpGet request = new HttpGet(builder.build().encode().toUri());
143
        for (Map.Entry<String, String> entry : headers.entrySet()) {
144
            request.setHeader(entry.getKey(), entry.getValue());
145
        }
146
        return this.executeMandii(request);
147
    }
29834 tejbeer 148
 
31828 amit.gupta 149
    public String get(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params)
150
            throws ProfitMandiBusinessException, HttpHostConnectException {
151
        String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
152
                : scheme.getValue() + hostName + ":" + port + "/" + uri;
153
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
154
        if (params != null) {
155
            Set<String> keys = params.keySet();
156
            for (String key : keys) {
157
                builder.queryParam(key, params.get(key));
158
            }
159
        }
160
        HttpGet request = new HttpGet(builder.build().encode().toUri());
161
        return this.execute(request);
162
    }
25011 amit.gupta 163
 
31828 amit.gupta 164
    public HttpResponse getResponse(String url, Map<String, String> params, Map<String, String> headers)
165
            throws ProfitMandiBusinessException, HttpHostConnectException {
166
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
167
        if (params != null) {
168
            for (Map.Entry<String, String> paramsEntry : params.entrySet()) {
169
                builder.queryParam(paramsEntry.getKey(), paramsEntry.getValue());
170
            }
30289 amit.gupta 171
 
31828 amit.gupta 172
        }
173
        HttpGet request = new HttpGet(builder.build().encode().toUri());
174
        if (headers != null) {
175
            for (Map.Entry<String, String> entry : headers.entrySet()) {
176
                request.setHeader(entry.getKey(), entry.getValue());
177
            }
178
        }
179
        try {
180
            LOGGER.info("Request uri is  {}", request.getURI().toString());
181
            HttpResponse response = httpClient.execute(request);
182
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
183
            if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
184
                return response;
185
            } else {
186
                throw new ProfitMandiBusinessException("", "", "GE_1005");
187
            }
188
        } catch (HttpHostConnectException httpHostConnectException) {
189
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
190
            throw httpHostConnectException;
191
        } catch (ClientProtocolException e) {
192
            LOGGER.error("Client Error : ", e);
37321 amit 193
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"), e);
31828 amit.gupta 194
        } catch (IOException e) {
195
            LOGGER.error("IO Error : ", e);
37321 amit 196
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"), e);
31828 amit.gupta 197
        }
198
    }
25011 amit.gupta 199
 
31828 amit.gupta 200
    public String execute(HttpUriRequest request) throws ProfitMandiBusinessException, HttpHostConnectException {
201
        LOGGER.info("Connecting to server at url {}", request.getURI());
36295 amit 202
        HttpResponse response = null;
31828 amit.gupta 203
        try {
36295 amit 204
            response = httpClient.execute(request);
31828 amit.gupta 205
            String responseString = this.toString(response.getEntity().getContent());
206
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
207
            LOGGER.info("Response String {}", responseString);
34877 ranu 208
            if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()  || response.getStatusLine().getStatusCode() == HttpStatus.CREATED.value() || response.getStatusLine().getStatusCode() == HttpStatus.ACCEPTED.value()) {
31828 amit.gupta 209
                return responseString;
210
            } else {
211
                LOGGER.info("Response String {} ", responseString);
212
                throw new ProfitMandiBusinessException("", "", "GE_1005");
213
            }
214
        } catch (HttpHostConnectException httpHostConnectException) {
215
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
216
            throw httpHostConnectException;
217
        } catch (ClientProtocolException e) {
218
            LOGGER.error("Client Error : ", e);
37321 amit 219
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"), e);
31828 amit.gupta 220
        } catch (IOException e) {
221
            LOGGER.error("IO Error : ", e);
37321 amit 222
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"), e);
36295 amit 223
        } finally {
224
            if (response != null) EntityUtils.consumeQuietly(response.getEntity());
31828 amit.gupta 225
        }
226
    }
25011 amit.gupta 227
 
31828 amit.gupta 228
    public MandiiResponse executeMandii(HttpUriRequest request)
229
            throws ProfitMandiBusinessException, HttpHostConnectException {
230
        LOGGER.info("Connecting to server at url {}", request.getURI());
36295 amit 231
        HttpResponse response = null;
31828 amit.gupta 232
        try {
36295 amit 233
            response = httpClient.execute(request);
31828 amit.gupta 234
            String responseString = this.toString(response.getEntity().getContent());
235
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
29834 tejbeer 236
 
31828 amit.gupta 237
            MandiiResponse mandiiResponse = new MandiiResponse();
238
            mandiiResponse.setResponseString(responseString);
239
            mandiiResponse.setStatusCode(response.getStatusLine().getStatusCode());
29834 tejbeer 240
 
31828 amit.gupta 241
            return mandiiResponse;
242
        } catch (HttpHostConnectException httpHostConnectException) {
243
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
244
            throw httpHostConnectException;
245
        } catch (ClientProtocolException e) {
246
            LOGGER.error("Client Error : ", e);
37321 amit 247
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"), e);
31828 amit.gupta 248
        } catch (IOException e) {
249
            LOGGER.error("IO Error : ", e);
37321 amit 250
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"), e);
36295 amit 251
        } finally {
252
            if (response != null) EntityUtils.consumeQuietly(response.getEntity());
31828 amit.gupta 253
        }
254
    }
29834 tejbeer 255
 
31828 amit.gupta 256
    public String executeJson(HttpUriRequest request) throws ProfitMandiBusinessException, HttpHostConnectException {
257
        LOGGER.info("Connecting to server at url {}", request.getURI());
36295 amit 258
        HttpResponse response = null;
31828 amit.gupta 259
        try {
36295 amit 260
            response = httpClient.execute(request);
31828 amit.gupta 261
            String responseString = this.toString(response.getEntity().getContent());
262
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
263
            LOGGER.info("Response String {}", responseString);
264
            return responseString;
265
        } catch (HttpHostConnectException httpHostConnectException) {
266
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
267
            throw httpHostConnectException;
268
        } catch (ClientProtocolException e) {
269
            LOGGER.error("Client Error : ", e);
37321 amit 270
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"), e);
31828 amit.gupta 271
        } catch (IOException e) {
272
            LOGGER.error("IO Error : ", e);
37321 amit 273
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"), e);
36295 amit 274
        } finally {
275
            if (response != null) EntityUtils.consumeQuietly(response.getEntity());
31828 amit.gupta 276
        }
277
    }
27179 amit.gupta 278
 
35623 amit 279
    public HttpResponse postResponse(String url, Map<String, String> params, Map<String, String> headers)
280
            throws ProfitMandiBusinessException, HttpHostConnectException {
281
        List<NameValuePair> bodyParameters = new ArrayList<>();
282
        if (params != null) {
283
            for (Map.Entry<String, String> entry : params.entrySet()) {
284
                bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
285
            }
286
        }
287
        HttpPost request = new HttpPost(url);
288
        if (headers != null) {
289
            for (Map.Entry<String, String> entry : headers.entrySet()) {
290
                request.setHeader(entry.getKey(), entry.getValue());
291
            }
292
        }
293
        try {
294
            request.setEntity(new UrlEncodedFormEntity(bodyParameters));
295
            LOGGER.info("Request uri is  {}", request.getURI().toString());
296
            HttpResponse response = httpClient.execute(request);
297
            LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
298
            if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
299
                return response;
300
            } else {
301
                throw new ProfitMandiBusinessException("", "", "GE_1005");
302
            }
303
        } catch (HttpHostConnectException httpHostConnectException) {
304
            LOGGER.error("Connection Timeout Exception", httpHostConnectException);
305
            throw httpHostConnectException;
306
        } catch (ClientProtocolException e) {
307
            LOGGER.error("Client Error : ", e);
37321 amit 308
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"), e);
35623 amit 309
        } catch (IOException e) {
310
            LOGGER.error("IO Error : ", e);
37321 amit 311
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"), e);
35623 amit 312
        }
313
    }
314
 
31828 amit.gupta 315
    public String post(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
316
                       Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
317
        String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
318
                : scheme.getValue() + hostName + ":" + port + "/" + uri;
319
        return this.post(url, params, headers);
320
    }
25011 amit.gupta 321
 
31828 amit.gupta 322
    public String post(String url, Map<String, String> params, Map<String, String> headers)
323
            throws ProfitMandiBusinessException, HttpHostConnectException {
324
        // UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
325
        List<NameValuePair> bodyParameters = new ArrayList<NameValuePair>();
326
        for (Map.Entry<String, String> entry : params.entrySet()) {
327
            bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
328
        }
25011 amit.gupta 329
 
31828 amit.gupta 330
        LOGGER.info("Body Parameters {}", params);
331
        HttpPost request = new HttpPost(url);
332
        for (Map.Entry<String, String> entry : headers.entrySet()) {
333
            request.setHeader(entry.getKey(), entry.getValue());
334
        }
25011 amit.gupta 335
 
31828 amit.gupta 336
        try {
337
            request.setEntity(new UrlEncodedFormEntity(bodyParameters));
338
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
339
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
340
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
341
        }
25011 amit.gupta 342
 
31828 amit.gupta 343
        return this.execute(request);
25011 amit.gupta 344
 
31828 amit.gupta 345
    }
25011 amit.gupta 346
 
31828 amit.gupta 347
    public String post(String url, Map<String, String> queryParams, Map<String, String> postParams, Map<String, String> headers)
348
            throws ProfitMandiBusinessException, HttpHostConnectException {
349
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
350
        if (queryParams != null) {
351
            Set<String> keys = queryParams.keySet();
352
            for (String key : keys) {
353
                builder.queryParam(key, queryParams.get(key));
354
            }
355
        }
356
        List<NameValuePair> bodyParameters = new ArrayList<>();
357
        for (Map.Entry<String, String> entry : postParams.entrySet()) {
358
            bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
359
        }
28653 amit.gupta 360
 
31828 amit.gupta 361
        HttpPost request = new HttpPost(builder.build().encode().toUri());
362
        for (Map.Entry<String, String> entry : headers.entrySet()) {
363
            request.setHeader(entry.getKey(), entry.getValue());
364
        }
28653 amit.gupta 365
 
31828 amit.gupta 366
        try {
367
            request.setEntity(new UrlEncodedFormEntity(bodyParameters));
368
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
369
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
370
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
371
        }
28653 amit.gupta 372
 
31828 amit.gupta 373
        return this.execute(request);
28653 amit.gupta 374
 
31828 amit.gupta 375
    }
25011 amit.gupta 376
 
31828 amit.gupta 377
    public String post(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
        }
25726 amit.gupta 383
 
31828 amit.gupta 384
        try {
385
            request.setEntity(new StringEntity(body));
386
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
387
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
388
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
389
        }
29834 tejbeer 390
 
31828 amit.gupta 391
        return this.execute(request);
29834 tejbeer 392
 
31828 amit.gupta 393
    }
29834 tejbeer 394
 
31828 amit.gupta 395
    public String postJson(String url, Object object, Map<String, String> headers)
396
            throws ProfitMandiBusinessException, HttpHostConnectException {
397
        String jsonString;
398
        try {
399
            if (object.getClass().equals(String.class)) {
400
                jsonString = (String) object;
401
            } else {
402
                jsonString = objectMapper.writeValueAsString(object);
403
            }
404
            LOGGER.info("JSON String - {}", jsonString);
405
        } catch (Exception e) {
406
            e.printStackTrace();
407
            throw new ProfitMandiBusinessException("Json Object", object.toString(), "Could not write as String");
408
        }
409
        StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
25011 amit.gupta 410
 
31828 amit.gupta 411
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
27179 amit.gupta 412
 
31828 amit.gupta 413
        HttpPost request = new HttpPost(builder.build().encode().toUri());
414
        for (Map.Entry<String, String> entry : headers.entrySet()) {
415
            request.setHeader(entry.getKey(), entry.getValue());
416
        }
417
        request.setEntity(requestEntity);
418
        return this.executeJson(request);
419
    }
420
 
36200 ranu 421
    public MandiiResponse postWithResponse(String url, String body, Map<String, String> headers)
422
            throws ProfitMandiBusinessException, HttpHostConnectException {
423
        HttpPost request = new HttpPost(url);
424
        for (Map.Entry<String, String> entry : headers.entrySet()) {
425
            request.setHeader(entry.getKey(), entry.getValue());
426
        }
427
        try {
428
            request.setEntity(new StringEntity(body));
429
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
430
            LOGGER.error("Encoding error : ", unsupportedEncodingException);
431
            throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
432
        }
433
        return this.executeMandii(request);
434
    }
435
 
31828 amit.gupta 436
    public String patchJson(String url, Object object, Map<String, String> headers)
437
            throws ProfitMandiBusinessException, HttpHostConnectException {
438
        String jsonString;
439
        try {
440
            if (object.getClass().equals(String.class)) {
441
                jsonString = (String) object;
442
            } else {
443
                jsonString = objectMapper.writeValueAsString(object);
444
            }
445
            LOGGER.info("JSON String - {}", jsonString);
446
        } catch (Exception e) {
447
            e.printStackTrace();
448
            throw new ProfitMandiBusinessException("Json Object", object.toString(), "Could not write as String");
449
        }
450
        StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
451
 
452
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
453
 
454
        HttpPatch request = new HttpPatch(builder.build().encode().toUri());
455
        for (Map.Entry<String, String> entry : headers.entrySet()) {
456
            request.setHeader(entry.getKey(), entry.getValue());
457
        }
458
        request.setEntity(requestEntity);
459
        return this.executeJson(request);
460
    }
461
 
462
    private String toString(InputStream inputStream) {
463
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
464
        StringBuilder responseString = new StringBuilder();
465
        String line = null;
466
        try {
467
            while ((line = reader.readLine()) != null) {
468
                responseString.append(line);
469
            }
470
            inputStream.close();
471
        } catch (IOException e) {
472
            throw new RuntimeException();
473
        }
474
        return responseString.toString();
475
    }
34805 ranu 476
 
477
    public byte[] postForBytes(String url, String payload, Map<String, String> headers) throws IOException {
478
        HttpPost post = new HttpPost(url);
479
        headers.forEach(post::setHeader);
480
 
481
        post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));
482
 
36416 amit 483
        try (CloseableHttpClient client = HttpClientFactory.apacheHttp();
34805 ranu 484
             CloseableHttpResponse response = client.execute(post)) {
485
 
486
            int statusCode = response.getStatusLine().getStatusCode();
487
            if (statusCode != 200) {
488
                throw new IOException("Failed : HTTP error code : " + statusCode);
489
            }
490
 
491
            return EntityUtils.toByteArray(response.getEntity());
492
        }
493
    }
494
 
21557 ashik.ali 495
}