Subversion Repositories SmartDukaan

Rev

Rev 27179 | Rev 29496 | 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;
22215 ashik.ali 20
import org.apache.http.client.methods.HttpPost;
21
import org.apache.http.client.methods.HttpUriRequest;
23502 ashik.ali 22
import org.apache.http.conn.HttpHostConnectException;
23
import org.apache.http.entity.ContentType;
24
import org.apache.http.entity.StringEntity;
25244 amit.gupta 25
import org.apache.http.impl.client.HttpClientBuilder;
21557 ashik.ali 26
import org.apache.http.impl.client.HttpClients;
22215 ashik.ali 27
import org.apache.http.message.BasicNameValuePair;
25011 amit.gupta 28
import org.apache.logging.log4j.LogManager;
23568 govind 29
import org.apache.logging.log4j.Logger;
25726 amit.gupta 30
import org.springframework.beans.factory.annotation.Autowired;
21557 ashik.ali 31
import org.springframework.http.HttpStatus;
23526 ashik.ali 32
import org.springframework.stereotype.Component;
21557 ashik.ali 33
import org.springframework.web.util.UriComponentsBuilder;
34
 
25726 amit.gupta 35
import com.fasterxml.jackson.databind.ObjectMapper;
21557 ashik.ali 36
import com.spice.profitmandi.common.ResponseCodeHolder;
37
import com.spice.profitmandi.common.enumuration.SchemeType;
38
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
39
 
23526 ashik.ali 40
@Component
21557 ashik.ali 41
public class RestClient {
25011 amit.gupta 42
 
23568 govind 43
	private static final Logger LOGGER = LogManager.getLogger(RestClient.class);
25011 amit.gupta 44
 
21557 ashik.ali 45
	private HttpClient httpClient;
25011 amit.gupta 46
 
25726 amit.gupta 47
	@Autowired
48
	ObjectMapper objectMapper;
49
 
23526 ashik.ali 50
	public RestClient() {
21557 ashik.ali 51
		this.httpClient = HttpClients.createDefault();
25244 amit.gupta 52
 
21557 ashik.ali 53
	}
25011 amit.gupta 54
 
25244 amit.gupta 55
	public RestClient(int connectionTimeoutMillis) {
25726 amit.gupta 56
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5 * 1000).build();
25244 amit.gupta 57
		this.httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
58
 
59
	}
60
 
25011 amit.gupta 61
	public String get(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
62
			Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
63
		String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
64
				: scheme.getValue() + hostName + ":" + port + "/" + uri;
23561 ashik.ali 65
		return this.get(url, params, headers);
66
	}
25011 amit.gupta 67
 
23561 ashik.ali 68
	public String get(String url, Map<String, String> params, Map<String, String> headers)
25011 amit.gupta 69
			throws ProfitMandiBusinessException, HttpHostConnectException {
23526 ashik.ali 70
		UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
28653 amit.gupta 71
		if(params!=null) {
72
			Set<String> keys = params.keySet();
73
			for (String key : keys) {
74
				builder.queryParam(key, params.get(key));
75
			}
21557 ashik.ali 76
		}
22345 amit.gupta 77
		HttpGet request = new HttpGet(builder.build().encode().toUri());
25011 amit.gupta 78
		for (Map.Entry<String, String> entry : headers.entrySet()) {
22339 amit.gupta 79
			request.setHeader(entry.getKey(), entry.getValue());
22215 ashik.ali 80
		}
81
		return this.execute(request);
82
	}
22233 amit.gupta 83
 
23526 ashik.ali 84
	public String get(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params)
25011 amit.gupta 85
			throws ProfitMandiBusinessException, HttpHostConnectException {
86
		String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
87
				: scheme.getValue() + hostName + ":" + port + "/" + uri;
23526 ashik.ali 88
		UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
25011 amit.gupta 89
		if (params != null) {
23509 amit.gupta 90
			Set<String> keys = params.keySet();
25011 amit.gupta 91
			for (String key : keys) {
23509 amit.gupta 92
				builder.queryParam(key, params.get(key));
93
			}
22233 amit.gupta 94
		}
22343 amit.gupta 95
		HttpGet request = new HttpGet(builder.build().encode().toUri());
22233 amit.gupta 96
		return this.execute(request);
97
	}
25011 amit.gupta 98
 
23612 amit.gupta 99
	public HttpResponse getResponse(String url, Map<String, String> params, Map<String, String> headers)
100
			throws ProfitMandiBusinessException, HttpHostConnectException {
101
		UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
102
		Set<String> keys = params.keySet();
25011 amit.gupta 103
		for (String key : keys) {
23612 amit.gupta 104
			builder.queryParam(key, params.get(key));
105
		}
106
		HttpGet request = new HttpGet(builder.build().encode().toUri());
27179 amit.gupta 107
		if (headers != null) {
26078 amit.gupta 108
			for (Map.Entry<String, String> entry : headers.entrySet()) {
109
				request.setHeader(entry.getKey(), entry.getValue());
110
			}
23612 amit.gupta 111
		}
112
		try {
113
			LOGGER.info("Request uri is  {}", request.getURI().toString());
114
			HttpResponse response = httpClient.execute(request);
115
			LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
25011 amit.gupta 116
			if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
23612 amit.gupta 117
				return response;
25011 amit.gupta 118
			} else {
23612 amit.gupta 119
				throw new ProfitMandiBusinessException("", "", "GE_1005");
120
			}
25011 amit.gupta 121
		} catch (HttpHostConnectException httpHostConnectException) {
23612 amit.gupta 122
			LOGGER.error("Connection Timeout Exception", httpHostConnectException);
123
			throw httpHostConnectException;
124
		} catch (ClientProtocolException e) {
25011 amit.gupta 125
			LOGGER.error("Client Error : ", e);
23612 amit.gupta 126
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
127
		} catch (IOException e) {
128
			LOGGER.error("IO Error : ", e);
129
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
130
		}
131
	}
25011 amit.gupta 132
 
133
	public String execute(HttpUriRequest request) throws ProfitMandiBusinessException, HttpHostConnectException {
134
		LOGGER.info("Connecting to server at url {}", request.getURI());
21557 ashik.ali 135
		try {
136
			HttpResponse response = httpClient.execute(request);
137
			String responseString = this.toString(response.getEntity().getContent());
22877 amit.gupta 138
			LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
25011 amit.gupta 139
			if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
21557 ashik.ali 140
				return responseString;
25011 amit.gupta 141
			} else {
25726 amit.gupta 142
				LOGGER.info("Response String {} ", responseString);
22215 ashik.ali 143
				throw new ProfitMandiBusinessException("", "", "GE_1005");
21557 ashik.ali 144
			}
25011 amit.gupta 145
		} catch (HttpHostConnectException httpHostConnectException) {
23502 ashik.ali 146
			LOGGER.error("Connection Timeout Exception", httpHostConnectException);
147
			throw httpHostConnectException;
21557 ashik.ali 148
		} catch (ClientProtocolException e) {
25011 amit.gupta 149
			LOGGER.error("Client Error : ", e);
22215 ashik.ali 150
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
21557 ashik.ali 151
		} catch (IOException e) {
22215 ashik.ali 152
			LOGGER.error("IO Error : ", e);
153
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
25011 amit.gupta 154
		}
21557 ashik.ali 155
	}
25011 amit.gupta 156
 
27179 amit.gupta 157
	public String executeJson(HttpUriRequest request) throws ProfitMandiBusinessException, HttpHostConnectException {
158
		LOGGER.info("Connecting to server at url {}", request.getURI());
159
		try {
160
			HttpResponse response = httpClient.execute(request);
161
			String responseString = this.toString(response.getEntity().getContent());
162
			LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
163
			return responseString;
164
		} catch (HttpHostConnectException httpHostConnectException) {
165
			LOGGER.error("Connection Timeout Exception", httpHostConnectException);
166
			throw httpHostConnectException;
167
		} catch (ClientProtocolException e) {
168
			LOGGER.error("Client Error : ", e);
169
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
170
		} catch (IOException e) {
171
			LOGGER.error("IO Error : ", e);
172
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
173
		}
174
	}
175
 
25011 amit.gupta 176
	public String post(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
177
			Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
178
		String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
179
				: scheme.getValue() + hostName + ":" + port + "/" + uri;
23561 ashik.ali 180
		return this.post(url, params, headers);
181
	}
25011 amit.gupta 182
 
23561 ashik.ali 183
	public String post(String url, Map<String, String> params, Map<String, String> headers)
25011 amit.gupta 184
			throws ProfitMandiBusinessException, HttpHostConnectException {
25244 amit.gupta 185
		// UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
22215 ashik.ali 186
		List<NameValuePair> bodyParameters = new ArrayList<NameValuePair>();
25011 amit.gupta 187
		for (Map.Entry<String, String> entry : params.entrySet()) {
22215 ashik.ali 188
			bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
189
		}
25011 amit.gupta 190
 
22215 ashik.ali 191
		LOGGER.info("Body Parameters {}", params);
25011 amit.gupta 192
		HttpPost request = new HttpPost(url);
193
		for (Map.Entry<String, String> entry : headers.entrySet()) {
22215 ashik.ali 194
			request.setHeader(entry.getKey(), entry.getValue());
195
		}
25011 amit.gupta 196
 
197
		try {
22215 ashik.ali 198
			request.setEntity(new UrlEncodedFormEntity(bodyParameters));
25011 amit.gupta 199
		} catch (UnsupportedEncodingException unsupportedEncodingException) {
22215 ashik.ali 200
			LOGGER.error("Encoding error : ", unsupportedEncodingException);
201
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
202
		}
25011 amit.gupta 203
 
22215 ashik.ali 204
		return this.execute(request);
25011 amit.gupta 205
 
22215 ashik.ali 206
	}
25011 amit.gupta 207
 
28653 amit.gupta 208
	public String post(String url, String body, Map<String, String> headers)
209
			throws ProfitMandiBusinessException, HttpHostConnectException {
210
		HttpPost request = new HttpPost(url);
211
		for (Map.Entry<String, String> entry : headers.entrySet()) {
212
			request.setHeader(entry.getKey(), entry.getValue());
213
		}
214
 
215
		try {
216
			request.setEntity(new StringEntity(body));
217
		} catch (UnsupportedEncodingException unsupportedEncodingException) {
218
			LOGGER.error("Encoding error : ", unsupportedEncodingException);
219
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
220
		}
221
 
222
		return this.execute(request);
223
 
224
	}
225
 
25726 amit.gupta 226
	public String postJson(String url, Object object, Map<String, String> headers)
25011 amit.gupta 227
			throws ProfitMandiBusinessException, HttpHostConnectException {
25726 amit.gupta 228
		String jsonString;
23502 ashik.ali 229
		try {
28653 amit.gupta 230
			if (object.getClass().equals(String.class)) {
231
				jsonString = (String) object;
232
			} else {
233
				jsonString = objectMapper.writeValueAsString(object);
234
			}
25726 amit.gupta 235
			LOGGER.info("JSON String - {}", jsonString);
27179 amit.gupta 236
		} catch (Exception e) {
23502 ashik.ali 237
			e.printStackTrace();
25726 amit.gupta 238
			throw new ProfitMandiBusinessException("Json Object", object.toString(), "Could not write as String");
23502 ashik.ali 239
		}
23561 ashik.ali 240
		StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
25011 amit.gupta 241
 
25726 amit.gupta 242
		UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
243
 
23502 ashik.ali 244
		HttpPost request = new HttpPost(builder.build().encode().toUri());
25011 amit.gupta 245
		for (Map.Entry<String, String> entry : headers.entrySet()) {
23502 ashik.ali 246
			request.setHeader(entry.getKey(), entry.getValue());
247
		}
248
		request.setEntity(requestEntity);
27179 amit.gupta 249
		return this.executeJson(request);
23502 ashik.ali 250
	}
25011 amit.gupta 251
 
252
	private String toString(InputStream inputStream) {
21557 ashik.ali 253
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
254
		StringBuilder responseString = new StringBuilder();
255
		String line = null;
256
		try {
25011 amit.gupta 257
			while ((line = reader.readLine()) != null) {
21557 ashik.ali 258
				responseString.append(line);
259
			}
260
			inputStream.close();
261
		} catch (IOException e) {
262
			throw new RuntimeException();
26656 amit.gupta 263
		} finally {
27179 amit.gupta 264
 
21557 ashik.ali 265
		}
266
		return responseString.toString();
267
	}
268
}