Subversion Repositories SmartDukaan

Rev

Rev 29834 | Rev 30383 | 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;
22215 ashik.ali 23
import org.apache.http.message.BasicNameValuePair;
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
 
23568 govind 40
	private static final Logger LOGGER = LogManager.getLogger(RestClient.class);
25011 amit.gupta 41
 
21557 ashik.ali 42
	private HttpClient httpClient;
25011 amit.gupta 43
 
30289 amit.gupta 44
 
25726 amit.gupta 45
	@Autowired
46
	ObjectMapper objectMapper;
47
 
23526 ashik.ali 48
	public RestClient() {
21557 ashik.ali 49
		this.httpClient = HttpClients.createDefault();
25244 amit.gupta 50
 
21557 ashik.ali 51
	}
25011 amit.gupta 52
 
25244 amit.gupta 53
	public RestClient(int connectionTimeoutMillis) {
25726 amit.gupta 54
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5 * 1000).build();
25244 amit.gupta 55
		this.httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
56
 
57
	}
58
 
25011 amit.gupta 59
	public String get(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
30289 amit.gupta 60
					  Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
25011 amit.gupta 61
		String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
62
				: scheme.getValue() + hostName + ":" + port + "/" + uri;
23561 ashik.ali 63
		return this.get(url, params, headers);
64
	}
25011 amit.gupta 65
 
23561 ashik.ali 66
	public String get(String url, Map<String, String> params, Map<String, String> headers)
25011 amit.gupta 67
			throws ProfitMandiBusinessException, HttpHostConnectException {
23526 ashik.ali 68
		UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
29834 tejbeer 69
		if (params != null) {
28653 amit.gupta 70
			Set<String> keys = params.keySet();
71
			for (String key : keys) {
72
				builder.queryParam(key, params.get(key));
73
			}
21557 ashik.ali 74
		}
22345 amit.gupta 75
		HttpGet request = new HttpGet(builder.build().encode().toUri());
30289 amit.gupta 76
		if (headers != null) {
77
			for (Map.Entry<String, String> entry : headers.entrySet()) {
78
				request.setHeader(entry.getKey(), entry.getValue());
79
			}
22215 ashik.ali 80
		}
81
		return this.execute(request);
82
	}
22233 amit.gupta 83
 
29834 tejbeer 84
	public MandiiResponse getMandii(String url, Map<String, String> params, Map<String, String> headers)
85
			throws ProfitMandiBusinessException, HttpHostConnectException {
86
		UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
87
		if (params != null) {
88
			Set<String> keys = params.keySet();
89
			for (String key : keys) {
90
				builder.queryParam(key, params.get(key));
91
			}
92
		}
93
		HttpGet request = new HttpGet(builder.build().encode().toUri());
94
		for (Map.Entry<String, String> entry : headers.entrySet()) {
95
			request.setHeader(entry.getKey(), entry.getValue());
96
		}
97
		return this.executeMandii(request);
98
	}
99
 
23526 ashik.ali 100
	public String get(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params)
25011 amit.gupta 101
			throws ProfitMandiBusinessException, HttpHostConnectException {
102
		String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
103
				: scheme.getValue() + hostName + ":" + port + "/" + uri;
23526 ashik.ali 104
		UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
25011 amit.gupta 105
		if (params != null) {
23509 amit.gupta 106
			Set<String> keys = params.keySet();
25011 amit.gupta 107
			for (String key : keys) {
23509 amit.gupta 108
				builder.queryParam(key, params.get(key));
109
			}
22233 amit.gupta 110
		}
22343 amit.gupta 111
		HttpGet request = new HttpGet(builder.build().encode().toUri());
22233 amit.gupta 112
		return this.execute(request);
113
	}
25011 amit.gupta 114
 
23612 amit.gupta 115
	public HttpResponse getResponse(String url, Map<String, String> params, Map<String, String> headers)
116
			throws ProfitMandiBusinessException, HttpHostConnectException {
117
		UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
30289 amit.gupta 118
		if (params != null) {
119
			for (Map.Entry<String, String> paramsEntry : params.entrySet()) {
120
				builder.queryParam(paramsEntry.getKey(), paramsEntry.getValue());
121
			}
122
 
23612 amit.gupta 123
		}
124
		HttpGet request = new HttpGet(builder.build().encode().toUri());
27179 amit.gupta 125
		if (headers != null) {
26078 amit.gupta 126
			for (Map.Entry<String, String> entry : headers.entrySet()) {
127
				request.setHeader(entry.getKey(), entry.getValue());
128
			}
23612 amit.gupta 129
		}
130
		try {
131
			LOGGER.info("Request uri is  {}", request.getURI().toString());
132
			HttpResponse response = httpClient.execute(request);
133
			LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
25011 amit.gupta 134
			if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
23612 amit.gupta 135
				return response;
25011 amit.gupta 136
			} else {
23612 amit.gupta 137
				throw new ProfitMandiBusinessException("", "", "GE_1005");
138
			}
25011 amit.gupta 139
		} catch (HttpHostConnectException httpHostConnectException) {
23612 amit.gupta 140
			LOGGER.error("Connection Timeout Exception", httpHostConnectException);
141
			throw httpHostConnectException;
142
		} catch (ClientProtocolException e) {
25011 amit.gupta 143
			LOGGER.error("Client Error : ", e);
23612 amit.gupta 144
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
145
		} catch (IOException e) {
146
			LOGGER.error("IO Error : ", e);
147
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
148
		}
149
	}
25011 amit.gupta 150
 
151
	public String execute(HttpUriRequest request) throws ProfitMandiBusinessException, HttpHostConnectException {
152
		LOGGER.info("Connecting to server at url {}", request.getURI());
21557 ashik.ali 153
		try {
154
			HttpResponse response = httpClient.execute(request);
155
			String responseString = this.toString(response.getEntity().getContent());
22877 amit.gupta 156
			LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
30289 amit.gupta 157
			LOGGER.info("Response String {}", responseString);
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());
30289 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,
30289 amit.gupta 222
					   Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
25011 amit.gupta 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
}