Subversion Repositories SmartDukaan

Rev

Rev 26656 | Rev 28653 | 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);
21557 ashik.ali 71
		Set<String> keys = params.keySet();
25011 amit.gupta 72
		for (String key : keys) {
22341 amit.gupta 73
			builder.queryParam(key, params.get(key));
21557 ashik.ali 74
		}
22345 amit.gupta 75
		HttpGet request = new HttpGet(builder.build().encode().toUri());
25011 amit.gupta 76
		for (Map.Entry<String, String> entry : headers.entrySet()) {
22339 amit.gupta 77
			request.setHeader(entry.getKey(), entry.getValue());
22215 ashik.ali 78
		}
79
		return this.execute(request);
80
	}
22233 amit.gupta 81
 
23526 ashik.ali 82
	public String get(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params)
25011 amit.gupta 83
			throws ProfitMandiBusinessException, HttpHostConnectException {
84
		String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
85
				: scheme.getValue() + hostName + ":" + port + "/" + uri;
23526 ashik.ali 86
		UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
25011 amit.gupta 87
		if (params != null) {
23509 amit.gupta 88
			Set<String> keys = params.keySet();
25011 amit.gupta 89
			for (String key : keys) {
23509 amit.gupta 90
				builder.queryParam(key, params.get(key));
91
			}
22233 amit.gupta 92
		}
22343 amit.gupta 93
		HttpGet request = new HttpGet(builder.build().encode().toUri());
22233 amit.gupta 94
		return this.execute(request);
95
	}
25011 amit.gupta 96
 
23612 amit.gupta 97
	public HttpResponse getResponse(String url, Map<String, String> params, Map<String, String> headers)
98
			throws ProfitMandiBusinessException, HttpHostConnectException {
99
		UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
100
		Set<String> keys = params.keySet();
25011 amit.gupta 101
		for (String key : keys) {
23612 amit.gupta 102
			builder.queryParam(key, params.get(key));
103
		}
104
		HttpGet request = new HttpGet(builder.build().encode().toUri());
27179 amit.gupta 105
		if (headers != null) {
26078 amit.gupta 106
			for (Map.Entry<String, String> entry : headers.entrySet()) {
107
				request.setHeader(entry.getKey(), entry.getValue());
108
			}
23612 amit.gupta 109
		}
110
		try {
111
			LOGGER.info("Request uri is  {}", request.getURI().toString());
112
			HttpResponse response = httpClient.execute(request);
113
			LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
25011 amit.gupta 114
			if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
23612 amit.gupta 115
				return response;
25011 amit.gupta 116
			} else {
23612 amit.gupta 117
				throw new ProfitMandiBusinessException("", "", "GE_1005");
118
			}
25011 amit.gupta 119
		} catch (HttpHostConnectException httpHostConnectException) {
23612 amit.gupta 120
			LOGGER.error("Connection Timeout Exception", httpHostConnectException);
121
			throw httpHostConnectException;
122
		} catch (ClientProtocolException e) {
25011 amit.gupta 123
			LOGGER.error("Client Error : ", e);
23612 amit.gupta 124
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
125
		} catch (IOException e) {
126
			LOGGER.error("IO Error : ", e);
127
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
128
		}
129
	}
25011 amit.gupta 130
 
131
	public String execute(HttpUriRequest request) throws ProfitMandiBusinessException, HttpHostConnectException {
132
		LOGGER.info("Connecting to server at url {}", request.getURI());
21557 ashik.ali 133
		try {
134
			HttpResponse response = httpClient.execute(request);
135
			String responseString = this.toString(response.getEntity().getContent());
22877 amit.gupta 136
			LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
25011 amit.gupta 137
			if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
21557 ashik.ali 138
				return responseString;
25011 amit.gupta 139
			} else {
25726 amit.gupta 140
				LOGGER.info("Response String {} ", responseString);
22215 ashik.ali 141
				throw new ProfitMandiBusinessException("", "", "GE_1005");
21557 ashik.ali 142
			}
25011 amit.gupta 143
		} catch (HttpHostConnectException httpHostConnectException) {
23502 ashik.ali 144
			LOGGER.error("Connection Timeout Exception", httpHostConnectException);
145
			throw httpHostConnectException;
21557 ashik.ali 146
		} catch (ClientProtocolException e) {
25011 amit.gupta 147
			LOGGER.error("Client Error : ", e);
22215 ashik.ali 148
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
21557 ashik.ali 149
		} catch (IOException e) {
22215 ashik.ali 150
			LOGGER.error("IO Error : ", e);
151
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
25011 amit.gupta 152
		}
21557 ashik.ali 153
	}
25011 amit.gupta 154
 
27179 amit.gupta 155
	public String executeJson(HttpUriRequest request) throws ProfitMandiBusinessException, HttpHostConnectException {
156
		LOGGER.info("Connecting to server at url {}", request.getURI());
157
		try {
158
			HttpResponse response = httpClient.execute(request);
159
			String responseString = this.toString(response.getEntity().getContent());
160
			LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
161
			return responseString;
162
		} catch (HttpHostConnectException httpHostConnectException) {
163
			LOGGER.error("Connection Timeout Exception", httpHostConnectException);
164
			throw httpHostConnectException;
165
		} catch (ClientProtocolException e) {
166
			LOGGER.error("Client Error : ", e);
167
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
168
		} catch (IOException e) {
169
			LOGGER.error("IO Error : ", e);
170
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
171
		}
172
	}
173
 
25011 amit.gupta 174
	public String post(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
175
			Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
176
		String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
177
				: scheme.getValue() + hostName + ":" + port + "/" + uri;
23561 ashik.ali 178
		return this.post(url, params, headers);
179
	}
25011 amit.gupta 180
 
23561 ashik.ali 181
	public String post(String url, Map<String, String> params, Map<String, String> headers)
25011 amit.gupta 182
			throws ProfitMandiBusinessException, HttpHostConnectException {
25244 amit.gupta 183
		// UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
22215 ashik.ali 184
		List<NameValuePair> bodyParameters = new ArrayList<NameValuePair>();
25011 amit.gupta 185
		for (Map.Entry<String, String> entry : params.entrySet()) {
22215 ashik.ali 186
			bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
187
		}
25011 amit.gupta 188
 
22215 ashik.ali 189
		LOGGER.info("Body Parameters {}", params);
25011 amit.gupta 190
		HttpPost request = new HttpPost(url);
191
		for (Map.Entry<String, String> entry : headers.entrySet()) {
22215 ashik.ali 192
			request.setHeader(entry.getKey(), entry.getValue());
193
		}
25011 amit.gupta 194
 
195
		try {
22215 ashik.ali 196
			request.setEntity(new UrlEncodedFormEntity(bodyParameters));
25011 amit.gupta 197
		} catch (UnsupportedEncodingException unsupportedEncodingException) {
22215 ashik.ali 198
			LOGGER.error("Encoding error : ", unsupportedEncodingException);
199
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
200
		}
25011 amit.gupta 201
 
22215 ashik.ali 202
		return this.execute(request);
25011 amit.gupta 203
 
22215 ashik.ali 204
	}
25011 amit.gupta 205
 
25726 amit.gupta 206
	public String postJson(String url, Object object, Map<String, String> headers)
25011 amit.gupta 207
			throws ProfitMandiBusinessException, HttpHostConnectException {
25726 amit.gupta 208
		String jsonString;
23502 ashik.ali 209
		try {
25726 amit.gupta 210
			jsonString = objectMapper.writeValueAsString(object);
211
			LOGGER.info("JSON String - {}", jsonString);
27179 amit.gupta 212
		} catch (Exception e) {
23502 ashik.ali 213
			e.printStackTrace();
25726 amit.gupta 214
			throw new ProfitMandiBusinessException("Json Object", object.toString(), "Could not write as String");
23502 ashik.ali 215
		}
23561 ashik.ali 216
		StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
25011 amit.gupta 217
 
25726 amit.gupta 218
		UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
219
 
23502 ashik.ali 220
		HttpPost request = new HttpPost(builder.build().encode().toUri());
25011 amit.gupta 221
		for (Map.Entry<String, String> entry : headers.entrySet()) {
23502 ashik.ali 222
			request.setHeader(entry.getKey(), entry.getValue());
223
		}
224
		request.setEntity(requestEntity);
27179 amit.gupta 225
		return this.executeJson(request);
23502 ashik.ali 226
	}
25011 amit.gupta 227
 
228
	private String toString(InputStream inputStream) {
21557 ashik.ali 229
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
230
		StringBuilder responseString = new StringBuilder();
231
		String line = null;
232
		try {
25011 amit.gupta 233
			while ((line = reader.readLine()) != null) {
21557 ashik.ali 234
				responseString.append(line);
235
			}
236
			inputStream.close();
237
		} catch (IOException e) {
238
			throw new RuntimeException();
26656 amit.gupta 239
		} finally {
27179 amit.gupta 240
 
21557 ashik.ali 241
		}
242
		return responseString.toString();
243
	}
244
}