Subversion Repositories SmartDukaan

Rev

Rev 25011 | Rev 25702 | 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;
25244 amit.gupta 22
import org.apache.http.conn.HttpClientConnectionManager;
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;
25244 amit.gupta 28
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
22215 ashik.ali 29
import org.apache.http.message.BasicNameValuePair;
25244 amit.gupta 30
import org.apache.http.params.BasicHttpParams;
31
import org.apache.http.params.HttpParams;
25011 amit.gupta 32
import org.apache.logging.log4j.LogManager;
23568 govind 33
import org.apache.logging.log4j.Logger;
21557 ashik.ali 34
import org.springframework.http.HttpStatus;
23526 ashik.ali 35
import org.springframework.stereotype.Component;
21557 ashik.ali 36
import org.springframework.web.util.UriComponentsBuilder;
37
 
38
import com.spice.profitmandi.common.ResponseCodeHolder;
39
import com.spice.profitmandi.common.enumuration.SchemeType;
40
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
23502 ashik.ali 41
import com.spice.profitmandi.common.util.StringUtils;
21557 ashik.ali 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
 
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) {
56
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5* 1000).build();
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());
25011 amit.gupta 105
		for (Map.Entry<String, String> entry : headers.entrySet()) {
23612 amit.gupta 106
			request.setHeader(entry.getKey(), entry.getValue());
107
		}
108
		try {
109
			LOGGER.info("Request uri is  {}", request.getURI().toString());
110
			HttpResponse response = httpClient.execute(request);
111
			LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
25011 amit.gupta 112
			if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
23612 amit.gupta 113
				return response;
25011 amit.gupta 114
			} else {
23612 amit.gupta 115
				throw new ProfitMandiBusinessException("", "", "GE_1005");
116
			}
25011 amit.gupta 117
		} catch (HttpHostConnectException httpHostConnectException) {
23612 amit.gupta 118
			LOGGER.error("Connection Timeout Exception", httpHostConnectException);
119
			throw httpHostConnectException;
120
		} catch (ClientProtocolException e) {
25011 amit.gupta 121
			LOGGER.error("Client Error : ", e);
23612 amit.gupta 122
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
123
		} catch (IOException e) {
124
			LOGGER.error("IO Error : ", e);
125
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
126
		}
127
	}
25011 amit.gupta 128
 
129
	public String execute(HttpUriRequest request) throws ProfitMandiBusinessException, HttpHostConnectException {
130
		LOGGER.info("Connecting to server at url {}", request.getURI());
21557 ashik.ali 131
		try {
132
			HttpResponse response = httpClient.execute(request);
133
			String responseString = this.toString(response.getEntity().getContent());
22877 amit.gupta 134
			LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
25011 amit.gupta 135
			if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
21557 ashik.ali 136
				return responseString;
25011 amit.gupta 137
			} else {
22215 ashik.ali 138
				throw new ProfitMandiBusinessException("", "", "GE_1005");
21557 ashik.ali 139
			}
25011 amit.gupta 140
		} catch (HttpHostConnectException httpHostConnectException) {
23502 ashik.ali 141
			LOGGER.error("Connection Timeout Exception", httpHostConnectException);
142
			throw httpHostConnectException;
21557 ashik.ali 143
		} catch (ClientProtocolException e) {
25011 amit.gupta 144
			LOGGER.error("Client Error : ", e);
22215 ashik.ali 145
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
21557 ashik.ali 146
		} catch (IOException e) {
22215 ashik.ali 147
			LOGGER.error("IO Error : ", e);
148
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
25011 amit.gupta 149
		}
21557 ashik.ali 150
	}
25011 amit.gupta 151
 
152
	public String post(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
153
			Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
154
		String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
155
				: scheme.getValue() + hostName + ":" + port + "/" + uri;
23561 ashik.ali 156
		return this.post(url, params, headers);
157
	}
25011 amit.gupta 158
 
23561 ashik.ali 159
	public String post(String url, Map<String, String> params, Map<String, String> headers)
25011 amit.gupta 160
			throws ProfitMandiBusinessException, HttpHostConnectException {
25244 amit.gupta 161
		// UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
22215 ashik.ali 162
		List<NameValuePair> bodyParameters = new ArrayList<NameValuePair>();
25011 amit.gupta 163
		for (Map.Entry<String, String> entry : params.entrySet()) {
22215 ashik.ali 164
			bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
165
		}
25011 amit.gupta 166
 
22215 ashik.ali 167
		LOGGER.info("Body Parameters {}", params);
25011 amit.gupta 168
		HttpPost request = new HttpPost(url);
169
		for (Map.Entry<String, String> entry : headers.entrySet()) {
22215 ashik.ali 170
			request.setHeader(entry.getKey(), entry.getValue());
171
		}
25011 amit.gupta 172
 
173
		try {
22215 ashik.ali 174
			request.setEntity(new UrlEncodedFormEntity(bodyParameters));
25011 amit.gupta 175
		} catch (UnsupportedEncodingException unsupportedEncodingException) {
22215 ashik.ali 176
			LOGGER.error("Encoding error : ", unsupportedEncodingException);
177
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
178
		}
25011 amit.gupta 179
 
22215 ashik.ali 180
		return this.execute(request);
25011 amit.gupta 181
 
22215 ashik.ali 182
	}
25011 amit.gupta 183
 
184
	public String postJson(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
185
			Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
186
		String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
187
				: scheme.getValue() + hostName + ":" + port + "/" + uri;
23561 ashik.ali 188
		return this.postJson(url, params, headers);
189
	}
25011 amit.gupta 190
 
23561 ashik.ali 191
	public String postJson(String url, Map<String, String> params, Map<String, String> headers)
25011 amit.gupta 192
			throws ProfitMandiBusinessException, HttpHostConnectException {
23526 ashik.ali 193
		UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
23502 ashik.ali 194
		List<NameValuePair> bodyParameters = new ArrayList<NameValuePair>();
25011 amit.gupta 195
		for (Map.Entry<String, String> entry : params.entrySet()) {
23502 ashik.ali 196
			bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
197
		}
25011 amit.gupta 198
 
23502 ashik.ali 199
		String jsonString = null;
200
		try {
201
			jsonString = StringUtils.toString(params);
202
		} catch (Exception e) {
203
			e.printStackTrace();
204
		}
25011 amit.gupta 205
 
23561 ashik.ali 206
		StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
25011 amit.gupta 207
 
23502 ashik.ali 208
		LOGGER.info("Body {}", jsonString);
209
		HttpPost request = new HttpPost(builder.build().encode().toUri());
25011 amit.gupta 210
		for (Map.Entry<String, String> entry : headers.entrySet()) {
23502 ashik.ali 211
			request.setHeader(entry.getKey(), entry.getValue());
212
		}
213
		request.setEntity(requestEntity);
214
		return this.execute(request);
215
	}
25011 amit.gupta 216
 
217
	private String toString(InputStream inputStream) {
21557 ashik.ali 218
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
219
		StringBuilder responseString = new StringBuilder();
220
		String line = null;
221
		try {
25011 amit.gupta 222
			while ((line = reader.readLine()) != null) {
21557 ashik.ali 223
				responseString.append(line);
224
			}
225
			inputStream.close();
226
		} catch (IOException e) {
227
			throw new RuntimeException();
228
		}
229
		return responseString.toString();
230
	}
231
}