Subversion Repositories SmartDukaan

Rev

Rev 30289 | Rev 30616 | 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
 
23568 govind 41
	private static final Logger LOGGER = LogManager.getLogger(RestClient.class);
25011 amit.gupta 42
 
21557 ashik.ali 43
	private HttpClient httpClient;
25011 amit.gupta 44
 
30289 amit.gupta 45
 
25726 amit.gupta 46
	@Autowired
47
	ObjectMapper objectMapper;
48
 
23526 ashik.ali 49
	public RestClient() {
30383 amit.gupta 50
		PoolingHttpClientConnectionManager connManager
51
				= new PoolingHttpClientConnectionManager();
52
		connManager.setMaxTotal(5);
53
		connManager.setDefaultMaxPerRoute(4);
54
		httpClient = HttpClients.custom().setConnectionManager(connManager).build();
25244 amit.gupta 55
 
21557 ashik.ali 56
	}
25011 amit.gupta 57
 
25244 amit.gupta 58
	public RestClient(int connectionTimeoutMillis) {
25726 amit.gupta 59
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5 * 1000).build();
25244 amit.gupta 60
		this.httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
61
 
62
	}
63
 
25011 amit.gupta 64
	public String get(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
30289 amit.gupta 65
					  Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
25011 amit.gupta 66
		String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
67
				: scheme.getValue() + hostName + ":" + port + "/" + uri;
23561 ashik.ali 68
		return this.get(url, params, headers);
69
	}
25011 amit.gupta 70
 
23561 ashik.ali 71
	public String get(String url, Map<String, String> params, Map<String, String> headers)
25011 amit.gupta 72
			throws ProfitMandiBusinessException, HttpHostConnectException {
23526 ashik.ali 73
		UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
29834 tejbeer 74
		if (params != null) {
28653 amit.gupta 75
			Set<String> keys = params.keySet();
76
			for (String key : keys) {
77
				builder.queryParam(key, params.get(key));
78
			}
21557 ashik.ali 79
		}
22345 amit.gupta 80
		HttpGet request = new HttpGet(builder.build().encode().toUri());
30289 amit.gupta 81
		if (headers != null) {
82
			for (Map.Entry<String, String> entry : headers.entrySet()) {
83
				request.setHeader(entry.getKey(), entry.getValue());
84
			}
22215 ashik.ali 85
		}
86
		return this.execute(request);
87
	}
22233 amit.gupta 88
 
29834 tejbeer 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
	}
104
 
23526 ashik.ali 105
	public String get(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params)
25011 amit.gupta 106
			throws ProfitMandiBusinessException, HttpHostConnectException {
107
		String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
108
				: scheme.getValue() + hostName + ":" + port + "/" + uri;
23526 ashik.ali 109
		UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
25011 amit.gupta 110
		if (params != null) {
23509 amit.gupta 111
			Set<String> keys = params.keySet();
25011 amit.gupta 112
			for (String key : keys) {
23509 amit.gupta 113
				builder.queryParam(key, params.get(key));
114
			}
22233 amit.gupta 115
		}
22343 amit.gupta 116
		HttpGet request = new HttpGet(builder.build().encode().toUri());
22233 amit.gupta 117
		return this.execute(request);
118
	}
25011 amit.gupta 119
 
23612 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);
30289 amit.gupta 123
		if (params != null) {
124
			for (Map.Entry<String, String> paramsEntry : params.entrySet()) {
125
				builder.queryParam(paramsEntry.getKey(), paramsEntry.getValue());
126
			}
127
 
23612 amit.gupta 128
		}
129
		HttpGet request = new HttpGet(builder.build().encode().toUri());
27179 amit.gupta 130
		if (headers != null) {
26078 amit.gupta 131
			for (Map.Entry<String, String> entry : headers.entrySet()) {
132
				request.setHeader(entry.getKey(), entry.getValue());
133
			}
23612 amit.gupta 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());
25011 amit.gupta 139
			if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
23612 amit.gupta 140
				return response;
25011 amit.gupta 141
			} else {
23612 amit.gupta 142
				throw new ProfitMandiBusinessException("", "", "GE_1005");
143
			}
25011 amit.gupta 144
		} catch (HttpHostConnectException httpHostConnectException) {
23612 amit.gupta 145
			LOGGER.error("Connection Timeout Exception", httpHostConnectException);
146
			throw httpHostConnectException;
147
		} catch (ClientProtocolException e) {
25011 amit.gupta 148
			LOGGER.error("Client Error : ", e);
23612 amit.gupta 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
 
156
	public String execute(HttpUriRequest request) throws ProfitMandiBusinessException, HttpHostConnectException {
157
		LOGGER.info("Connecting to server at url {}", request.getURI());
21557 ashik.ali 158
		try {
159
			HttpResponse response = httpClient.execute(request);
160
			String responseString = this.toString(response.getEntity().getContent());
22877 amit.gupta 161
			LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
30289 amit.gupta 162
			LOGGER.info("Response String {}", responseString);
25011 amit.gupta 163
			if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
21557 ashik.ali 164
				return responseString;
25011 amit.gupta 165
			} else {
25726 amit.gupta 166
				LOGGER.info("Response String {} ", responseString);
22215 ashik.ali 167
				throw new ProfitMandiBusinessException("", "", "GE_1005");
21557 ashik.ali 168
			}
25011 amit.gupta 169
		} catch (HttpHostConnectException httpHostConnectException) {
23502 ashik.ali 170
			LOGGER.error("Connection Timeout Exception", httpHostConnectException);
171
			throw httpHostConnectException;
21557 ashik.ali 172
		} catch (ClientProtocolException e) {
25011 amit.gupta 173
			LOGGER.error("Client Error : ", e);
22215 ashik.ali 174
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
21557 ashik.ali 175
		} catch (IOException e) {
22215 ashik.ali 176
			LOGGER.error("IO Error : ", e);
177
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
25011 amit.gupta 178
		}
21557 ashik.ali 179
	}
25011 amit.gupta 180
 
29834 tejbeer 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());
188
 
189
			MandiiResponse mandiiResponse = new MandiiResponse();
190
			mandiiResponse.setResponseString(responseString);
191
			mandiiResponse.setStatusCode(response.getStatusLine().getStatusCode());
192
 
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
	}
205
 
27179 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());
30289 amit.gupta 212
			LOGGER.info("Response String {}", responseString);
27179 amit.gupta 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
	}
225
 
25011 amit.gupta 226
	public String post(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
30289 amit.gupta 227
					   Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
25011 amit.gupta 228
		String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
229
				: scheme.getValue() + hostName + ":" + port + "/" + uri;
23561 ashik.ali 230
		return this.post(url, params, headers);
231
	}
25011 amit.gupta 232
 
23561 ashik.ali 233
	public String post(String url, Map<String, String> params, Map<String, String> headers)
25011 amit.gupta 234
			throws ProfitMandiBusinessException, HttpHostConnectException {
25244 amit.gupta 235
		// UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
22215 ashik.ali 236
		List<NameValuePair> bodyParameters = new ArrayList<NameValuePair>();
25011 amit.gupta 237
		for (Map.Entry<String, String> entry : params.entrySet()) {
22215 ashik.ali 238
			bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
239
		}
25011 amit.gupta 240
 
22215 ashik.ali 241
		LOGGER.info("Body Parameters {}", params);
25011 amit.gupta 242
		HttpPost request = new HttpPost(url);
243
		for (Map.Entry<String, String> entry : headers.entrySet()) {
22215 ashik.ali 244
			request.setHeader(entry.getKey(), entry.getValue());
245
		}
25011 amit.gupta 246
 
247
		try {
22215 ashik.ali 248
			request.setEntity(new UrlEncodedFormEntity(bodyParameters));
25011 amit.gupta 249
		} catch (UnsupportedEncodingException unsupportedEncodingException) {
22215 ashik.ali 250
			LOGGER.error("Encoding error : ", unsupportedEncodingException);
251
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
252
		}
25011 amit.gupta 253
 
22215 ashik.ali 254
		return this.execute(request);
25011 amit.gupta 255
 
22215 ashik.ali 256
	}
25011 amit.gupta 257
 
28653 amit.gupta 258
	public String post(String url, String body, Map<String, String> headers)
259
			throws ProfitMandiBusinessException, HttpHostConnectException {
260
		HttpPost request = new HttpPost(url);
261
		for (Map.Entry<String, String> entry : headers.entrySet()) {
262
			request.setHeader(entry.getKey(), entry.getValue());
263
		}
264
 
265
		try {
266
			request.setEntity(new StringEntity(body));
267
		} catch (UnsupportedEncodingException unsupportedEncodingException) {
268
			LOGGER.error("Encoding error : ", unsupportedEncodingException);
269
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
270
		}
271
 
272
		return this.execute(request);
273
 
274
	}
275
 
25726 amit.gupta 276
	public String postJson(String url, Object object, Map<String, String> headers)
25011 amit.gupta 277
			throws ProfitMandiBusinessException, HttpHostConnectException {
25726 amit.gupta 278
		String jsonString;
23502 ashik.ali 279
		try {
28653 amit.gupta 280
			if (object.getClass().equals(String.class)) {
281
				jsonString = (String) object;
282
			} else {
283
				jsonString = objectMapper.writeValueAsString(object);
284
			}
25726 amit.gupta 285
			LOGGER.info("JSON String - {}", jsonString);
27179 amit.gupta 286
		} catch (Exception e) {
23502 ashik.ali 287
			e.printStackTrace();
25726 amit.gupta 288
			throw new ProfitMandiBusinessException("Json Object", object.toString(), "Could not write as String");
23502 ashik.ali 289
		}
23561 ashik.ali 290
		StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
25011 amit.gupta 291
 
25726 amit.gupta 292
		UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
293
 
23502 ashik.ali 294
		HttpPost request = new HttpPost(builder.build().encode().toUri());
25011 amit.gupta 295
		for (Map.Entry<String, String> entry : headers.entrySet()) {
23502 ashik.ali 296
			request.setHeader(entry.getKey(), entry.getValue());
297
		}
298
		request.setEntity(requestEntity);
27179 amit.gupta 299
		return this.executeJson(request);
23502 ashik.ali 300
	}
29834 tejbeer 301
 
29710 amit.gupta 302
	public String patchJson(String url, Object object, Map<String, String> headers)
303
			throws ProfitMandiBusinessException, HttpHostConnectException {
304
		String jsonString;
305
		try {
306
			if (object.getClass().equals(String.class)) {
307
				jsonString = (String) object;
308
			} else {
309
				jsonString = objectMapper.writeValueAsString(object);
310
			}
311
			LOGGER.info("JSON String - {}", jsonString);
312
		} catch (Exception e) {
313
			e.printStackTrace();
314
			throw new ProfitMandiBusinessException("Json Object", object.toString(), "Could not write as String");
315
		}
316
		StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
29834 tejbeer 317
 
29710 amit.gupta 318
		UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
29834 tejbeer 319
 
29710 amit.gupta 320
		HttpPatch request = new HttpPatch(builder.build().encode().toUri());
321
		for (Map.Entry<String, String> entry : headers.entrySet()) {
322
			request.setHeader(entry.getKey(), entry.getValue());
323
		}
324
		request.setEntity(requestEntity);
325
		return this.executeJson(request);
326
	}
25011 amit.gupta 327
 
328
	private String toString(InputStream inputStream) {
21557 ashik.ali 329
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
330
		StringBuilder responseString = new StringBuilder();
331
		String line = null;
332
		try {
25011 amit.gupta 333
			while ((line = reader.readLine()) != null) {
21557 ashik.ali 334
				responseString.append(line);
335
			}
336
			inputStream.close();
337
		} catch (IOException e) {
338
			throw new RuntimeException();
26656 amit.gupta 339
		} finally {
27179 amit.gupta 340
 
21557 ashik.ali 341
		}
342
		return responseString.toString();
343
	}
344
}