Subversion Repositories SmartDukaan

Rev

Rev 28653 | Rev 29710 | 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());
29496 amit.gupta 163
			LOGGER.info("Response String", responseString);
27179 amit.gupta 164
			return responseString;
165
		} catch (HttpHostConnectException httpHostConnectException) {
166
			LOGGER.error("Connection Timeout Exception", httpHostConnectException);
167
			throw httpHostConnectException;
168
		} catch (ClientProtocolException e) {
169
			LOGGER.error("Client Error : ", e);
170
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
171
		} catch (IOException e) {
172
			LOGGER.error("IO Error : ", e);
173
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
174
		}
175
	}
176
 
25011 amit.gupta 177
	public String post(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
178
			Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
179
		String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
180
				: scheme.getValue() + hostName + ":" + port + "/" + uri;
23561 ashik.ali 181
		return this.post(url, params, headers);
182
	}
25011 amit.gupta 183
 
23561 ashik.ali 184
	public String post(String url, Map<String, String> params, Map<String, String> headers)
25011 amit.gupta 185
			throws ProfitMandiBusinessException, HttpHostConnectException {
25244 amit.gupta 186
		// UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
22215 ashik.ali 187
		List<NameValuePair> bodyParameters = new ArrayList<NameValuePair>();
25011 amit.gupta 188
		for (Map.Entry<String, String> entry : params.entrySet()) {
22215 ashik.ali 189
			bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
190
		}
25011 amit.gupta 191
 
22215 ashik.ali 192
		LOGGER.info("Body Parameters {}", params);
25011 amit.gupta 193
		HttpPost request = new HttpPost(url);
194
		for (Map.Entry<String, String> entry : headers.entrySet()) {
22215 ashik.ali 195
			request.setHeader(entry.getKey(), entry.getValue());
196
		}
25011 amit.gupta 197
 
198
		try {
22215 ashik.ali 199
			request.setEntity(new UrlEncodedFormEntity(bodyParameters));
25011 amit.gupta 200
		} catch (UnsupportedEncodingException unsupportedEncodingException) {
22215 ashik.ali 201
			LOGGER.error("Encoding error : ", unsupportedEncodingException);
202
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
203
		}
25011 amit.gupta 204
 
22215 ashik.ali 205
		return this.execute(request);
25011 amit.gupta 206
 
22215 ashik.ali 207
	}
25011 amit.gupta 208
 
28653 amit.gupta 209
	public String post(String url, String body, Map<String, String> headers)
210
			throws ProfitMandiBusinessException, HttpHostConnectException {
211
		HttpPost request = new HttpPost(url);
212
		for (Map.Entry<String, String> entry : headers.entrySet()) {
213
			request.setHeader(entry.getKey(), entry.getValue());
214
		}
215
 
216
		try {
217
			request.setEntity(new StringEntity(body));
218
		} catch (UnsupportedEncodingException unsupportedEncodingException) {
219
			LOGGER.error("Encoding error : ", unsupportedEncodingException);
220
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
221
		}
222
 
223
		return this.execute(request);
224
 
225
	}
226
 
25726 amit.gupta 227
	public String postJson(String url, Object object, Map<String, String> headers)
25011 amit.gupta 228
			throws ProfitMandiBusinessException, HttpHostConnectException {
25726 amit.gupta 229
		String jsonString;
23502 ashik.ali 230
		try {
28653 amit.gupta 231
			if (object.getClass().equals(String.class)) {
232
				jsonString = (String) object;
233
			} else {
234
				jsonString = objectMapper.writeValueAsString(object);
235
			}
25726 amit.gupta 236
			LOGGER.info("JSON String - {}", jsonString);
27179 amit.gupta 237
		} catch (Exception e) {
23502 ashik.ali 238
			e.printStackTrace();
25726 amit.gupta 239
			throw new ProfitMandiBusinessException("Json Object", object.toString(), "Could not write as String");
23502 ashik.ali 240
		}
23561 ashik.ali 241
		StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
25011 amit.gupta 242
 
25726 amit.gupta 243
		UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
244
 
23502 ashik.ali 245
		HttpPost request = new HttpPost(builder.build().encode().toUri());
25011 amit.gupta 246
		for (Map.Entry<String, String> entry : headers.entrySet()) {
23502 ashik.ali 247
			request.setHeader(entry.getKey(), entry.getValue());
248
		}
249
		request.setEntity(requestEntity);
27179 amit.gupta 250
		return this.executeJson(request);
23502 ashik.ali 251
	}
25011 amit.gupta 252
 
253
	private String toString(InputStream inputStream) {
21557 ashik.ali 254
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
255
		StringBuilder responseString = new StringBuilder();
256
		String line = null;
257
		try {
25011 amit.gupta 258
			while ((line = reader.readLine()) != null) {
21557 ashik.ali 259
				responseString.append(line);
260
			}
261
			inputStream.close();
262
		} catch (IOException e) {
263
			throw new RuntimeException();
26656 amit.gupta 264
		} finally {
27179 amit.gupta 265
 
21557 ashik.ali 266
		}
267
		return responseString.toString();
268
	}
269
}