Rev 23502 | Rev 23526 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed
package com.spice.profitmandi.common.web.client;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Set;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.methods.HttpUriRequest;import org.apache.http.conn.HttpHostConnectException;import org.apache.http.entity.ContentType;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicNameValuePair;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.HttpStatus;import org.springframework.web.util.UriComponentsBuilder;import com.spice.profitmandi.common.ResponseCodeHolder;import com.spice.profitmandi.common.enumuration.SchemeType;import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;import com.spice.profitmandi.common.util.StringUtils;public class RestClient {private static final Logger LOGGER = LoggerFactory.getLogger(RestClient.class);private HttpClient httpClient;private SchemeType scheme;private String hostName;private int port;private final String url;//private HttpHeaders headers;public RestClient(SchemeType scheme, String hostName, int port){this.scheme = scheme;this.hostName = hostName;this.port = port;this.url = scheme.getValue() == null ? SchemeType.HTTP.toString() : scheme.getValue() + hostName + ":" + port + "/";//this.headers = new HttpHeaders();this.httpClient = HttpClients.createDefault();//headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);}public SchemeType getScheme() {return scheme;}public String getHostName() {return hostName;}public int getPort() {return port;}public String getUrl() {return url;}public String get(String uri, Map<String, String> params, Map<String, String> headers)throws ProfitMandiBusinessException, HttpHostConnectException{UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url + uri);Set<String> keys = params.keySet();for(String key : keys){builder.queryParam(key, params.get(key));}HttpGet request = new HttpGet(builder.build().encode().toUri());for(Map.Entry<String, String> entry : headers.entrySet()){request.setHeader(entry.getKey(), entry.getValue());}return this.execute(request);}public String get(String uri, Map<String, String> params)throws ProfitMandiBusinessException, HttpHostConnectException{UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url + uri);if(params != null) {Set<String> keys = params.keySet();for(String key : keys){builder.queryParam(key, params.get(key));}}HttpGet request = new HttpGet(builder.build().encode().toUri());return this.execute(request);}public String execute(HttpUriRequest request)throws ProfitMandiBusinessException, HttpHostConnectException{LOGGER.info("Connecting to server at url {}",request.getURI());try {HttpResponse response = httpClient.execute(request);String responseString = this.toString(response.getEntity().getContent());LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());if(response.getStatusLine().getStatusCode() == HttpStatus.OK.value()){return responseString;}else{throw new ProfitMandiBusinessException("", "", "GE_1005");}}catch(HttpHostConnectException httpHostConnectException) {LOGGER.error("Connection Timeout Exception", httpHostConnectException);throw httpHostConnectException;} catch (ClientProtocolException e) {LOGGER.error("Client Error : ",e);throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));} catch (IOException e) {LOGGER.error("IO Error : ", e);throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));}}public String post(String uri, Map<String, String> params, Map<String, String> headers)throws ProfitMandiBusinessException, HttpHostConnectException{UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url + uri);List<NameValuePair> bodyParameters = new ArrayList<NameValuePair>();for(Map.Entry<String, String> entry : params.entrySet()){bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));}LOGGER.info("Body Parameters {}", params);HttpPost request = new HttpPost(builder.build().encode().toUri());for(Map.Entry<String, String> entry : headers.entrySet()){request.setHeader(entry.getKey(), entry.getValue());}try{request.setEntity(new UrlEncodedFormEntity(bodyParameters));}catch (UnsupportedEncodingException unsupportedEncodingException) {LOGGER.error("Encoding error : ", unsupportedEncodingException);throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));}return this.execute(request);}public String postJson(String uri, Map<String, String> params, Map<String, String> headers)throws ProfitMandiBusinessException, HttpHostConnectException{UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url + uri);List<NameValuePair> bodyParameters = new ArrayList<NameValuePair>();for(Map.Entry<String, String> entry : params.entrySet()){bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));}String jsonString = null;try {jsonString = StringUtils.toString(params);} catch (Exception e) {e.printStackTrace();}StringEntity requestEntity = new StringEntity(jsonString,ContentType.APPLICATION_JSON);LOGGER.info("Body {}", jsonString);HttpPost request = new HttpPost(builder.build().encode().toUri());for(Map.Entry<String, String> entry : headers.entrySet()){request.setHeader(entry.getKey(), entry.getValue());}request.setEntity(requestEntity);return this.execute(request);}private String toString(InputStream inputStream){BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));StringBuilder responseString = new StringBuilder();String line = null;try {while((line = reader.readLine()) != null){responseString.append(line);}inputStream.close();} catch (IOException e) {throw new RuntimeException();}return responseString.toString();}}