Subversion Repositories SmartDukaan

Rev

Rev 26078 | Rev 27179 | 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());
26078 amit.gupta 105
		if(headers != null) {
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
 
155
	public String post(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
156
			Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
157
		String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
158
				: scheme.getValue() + hostName + ":" + port + "/" + uri;
23561 ashik.ali 159
		return this.post(url, params, headers);
160
	}
25011 amit.gupta 161
 
23561 ashik.ali 162
	public String post(String url, Map<String, String> params, Map<String, String> headers)
25011 amit.gupta 163
			throws ProfitMandiBusinessException, HttpHostConnectException {
25244 amit.gupta 164
		// UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
22215 ashik.ali 165
		List<NameValuePair> bodyParameters = new ArrayList<NameValuePair>();
25011 amit.gupta 166
		for (Map.Entry<String, String> entry : params.entrySet()) {
22215 ashik.ali 167
			bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
168
		}
25011 amit.gupta 169
 
22215 ashik.ali 170
		LOGGER.info("Body Parameters {}", params);
25011 amit.gupta 171
		HttpPost request = new HttpPost(url);
172
		for (Map.Entry<String, String> entry : headers.entrySet()) {
22215 ashik.ali 173
			request.setHeader(entry.getKey(), entry.getValue());
174
		}
25011 amit.gupta 175
 
176
		try {
22215 ashik.ali 177
			request.setEntity(new UrlEncodedFormEntity(bodyParameters));
25011 amit.gupta 178
		} catch (UnsupportedEncodingException unsupportedEncodingException) {
22215 ashik.ali 179
			LOGGER.error("Encoding error : ", unsupportedEncodingException);
180
			throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
181
		}
25011 amit.gupta 182
 
22215 ashik.ali 183
		return this.execute(request);
25011 amit.gupta 184
 
22215 ashik.ali 185
	}
25011 amit.gupta 186
 
187
	public String postJson(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
188
			Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
189
		String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
190
				: scheme.getValue() + hostName + ":" + port + "/" + uri;
23561 ashik.ali 191
		return this.postJson(url, params, headers);
192
	}
25011 amit.gupta 193
 
25726 amit.gupta 194
 
195
	public String postJson(String url, Object object, Map<String, String> headers)
25011 amit.gupta 196
			throws ProfitMandiBusinessException, HttpHostConnectException {
25726 amit.gupta 197
		String jsonString;
23502 ashik.ali 198
		try {
25726 amit.gupta 199
			jsonString = objectMapper.writeValueAsString(object);
200
			LOGGER.info("JSON String - {}", jsonString);
201
		} catch(Exception e) {
23502 ashik.ali 202
			e.printStackTrace();
25726 amit.gupta 203
			throw new ProfitMandiBusinessException("Json Object", object.toString(), "Could not write as String");
23502 ashik.ali 204
		}
23561 ashik.ali 205
		StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
25011 amit.gupta 206
 
25726 amit.gupta 207
		UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
208
 
23502 ashik.ali 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();
26656 amit.gupta 228
		} finally {
229
 
21557 ashik.ali 230
		}
231
		return responseString.toString();
232
	}
233
}