Subversion Repositories SmartDukaan

Rev

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