Subversion Repositories SmartDukaan

Rev

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