Subversion Repositories SmartDukaan

Rev

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