Subversion Repositories SmartDukaan

Rev

Rev 30289 | Rev 30616 | 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 com.fasterxml.jackson.databind.ObjectMapper;
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.model.MandiiResponse;
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.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
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.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
public class RestClient {

        private static final Logger LOGGER = LogManager.getLogger(RestClient.class);

        private HttpClient httpClient;


        @Autowired
        ObjectMapper objectMapper;

        public RestClient() {
                PoolingHttpClientConnectionManager connManager
                                = new PoolingHttpClientConnectionManager();
                connManager.setMaxTotal(5);
                connManager.setDefaultMaxPerRoute(4);
                httpClient = HttpClients.custom().setConnectionManager(connManager).build();

        }

        public RestClient(int connectionTimeoutMillis) {
                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5 * 1000).build();
                this.httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();

        }

        public String get(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
                                          Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
                String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
                                : scheme.getValue() + hostName + ":" + port + "/" + uri;
                return this.get(url, params, headers);
        }

        public String get(String url, Map<String, String> params, Map<String, String> headers)
                        throws ProfitMandiBusinessException, HttpHostConnectException {
                UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
                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());
                if (headers != null) {
                        for (Map.Entry<String, String> entry : headers.entrySet()) {
                                request.setHeader(entry.getKey(), entry.getValue());
                        }
                }
                return this.execute(request);
        }

        public MandiiResponse getMandii(String url, Map<String, String> params, Map<String, String> headers)
                        throws ProfitMandiBusinessException, HttpHostConnectException {
                UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
                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());
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                        request.setHeader(entry.getKey(), entry.getValue());
                }
                return this.executeMandii(request);
        }

        public String get(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params)
                        throws ProfitMandiBusinessException, HttpHostConnectException {
                String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
                                : scheme.getValue() + hostName + ":" + port + "/" + uri;
                UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
                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 HttpResponse getResponse(String url, Map<String, String> params, Map<String, String> headers)
                        throws ProfitMandiBusinessException, HttpHostConnectException {
                UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
                if (params != null) {
                        for (Map.Entry<String, String> paramsEntry : params.entrySet()) {
                                builder.queryParam(paramsEntry.getKey(), paramsEntry.getValue());
                        }

                }
                HttpGet request = new HttpGet(builder.build().encode().toUri());
                if (headers != null) {
                        for (Map.Entry<String, String> entry : headers.entrySet()) {
                                request.setHeader(entry.getKey(), entry.getValue());
                        }
                }
                try {
                        LOGGER.info("Request uri is  {}", request.getURI().toString());
                        HttpResponse response = httpClient.execute(request);
                        LOGGER.info("Got response from server with responseCode {}", response.getStatusLine().getStatusCode());
                        if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
                                return response;
                        } 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 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());
                        LOGGER.info("Response String {}", responseString);
                        if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
                                return responseString;
                        } else {
                                LOGGER.info("Response String {} ", responseString);
                                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 MandiiResponse executeMandii(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());

                        MandiiResponse mandiiResponse = new MandiiResponse();
                        mandiiResponse.setResponseString(responseString);
                        mandiiResponse.setStatusCode(response.getStatusLine().getStatusCode());

                        return mandiiResponse;
                } 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 executeJson(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());
                        LOGGER.info("Response String {}", responseString);
                        return responseString;
                } 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(SchemeType scheme, String hostName, int port, String uri, Map<String, String> params,
                                           Map<String, String> headers) throws ProfitMandiBusinessException, HttpHostConnectException {
                String url = scheme.getValue() == null ? SchemeType.HTTP.toString()
                                : scheme.getValue() + hostName + ":" + port + "/" + uri;
                return this.post(url, params, headers);
        }

        public String post(String url, Map<String, String> params, Map<String, String> headers)
                        throws ProfitMandiBusinessException, HttpHostConnectException {
                // UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
                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(url);
                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 post(String url, String body, Map<String, String> headers)
                        throws ProfitMandiBusinessException, HttpHostConnectException {
                HttpPost request = new HttpPost(url);
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                        request.setHeader(entry.getKey(), entry.getValue());
                }

                try {
                        request.setEntity(new StringEntity(body));
                } catch (UnsupportedEncodingException unsupportedEncodingException) {
                        LOGGER.error("Encoding error : ", unsupportedEncodingException);
                        throw new RuntimeException(ResponseCodeHolder.getMessage("GE_1006"));
                }

                return this.execute(request);

        }

        public String postJson(String url, Object object, Map<String, String> headers)
                        throws ProfitMandiBusinessException, HttpHostConnectException {
                String jsonString;
                try {
                        if (object.getClass().equals(String.class)) {
                                jsonString = (String) object;
                        } else {
                                jsonString = objectMapper.writeValueAsString(object);
                        }
                        LOGGER.info("JSON String - {}", jsonString);
                } catch (Exception e) {
                        e.printStackTrace();
                        throw new ProfitMandiBusinessException("Json Object", object.toString(), "Could not write as String");
                }
                StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);

                UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);

                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.executeJson(request);
        }

        public String patchJson(String url, Object object, Map<String, String> headers)
                        throws ProfitMandiBusinessException, HttpHostConnectException {
                String jsonString;
                try {
                        if (object.getClass().equals(String.class)) {
                                jsonString = (String) object;
                        } else {
                                jsonString = objectMapper.writeValueAsString(object);
                        }
                        LOGGER.info("JSON String - {}", jsonString);
                } catch (Exception e) {
                        e.printStackTrace();
                        throw new ProfitMandiBusinessException("Json Object", object.toString(), "Could not write as String");
                }
                StringEntity requestEntity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);

                UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);

                HttpPatch request = new HttpPatch(builder.build().encode().toUri());
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                        request.setHeader(entry.getKey(), entry.getValue());
                }
                request.setEntity(requestEntity);
                return this.executeJson(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();
                } finally {

                }
                return responseString.toString();
        }
}