Subversion Repositories SmartDukaan

Rev

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