Subversion Repositories SmartDukaan

Rev

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