Subversion Repositories SmartDukaan

Rev

Rev 34805 | 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.*;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
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.http.util.EntityUtils;
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().disableCookieManagement().disableAuthCaching().disableConnectionState().
                disableAuthCaching().setConnectionManager(connManager).build();

    }

    public RestClient(int connectionTimeoutMillis) {
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5 * 1000).build();
        this.httpClient = HttpClientBuilder.create().disableCookieManagement().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()  || response.getStatusLine().getStatusCode() == HttpStatus.CREATED.value() || response.getStatusLine().getStatusCode() == HttpStatus.ACCEPTED.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, Map<String, String> queryParams, Map<String, String> postParams, Map<String, String> headers)
            throws ProfitMandiBusinessException, HttpHostConnectException {
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        if (queryParams != null) {
            Set<String> keys = queryParams.keySet();
            for (String key : keys) {
                builder.queryParam(key, queryParams.get(key));
            }
        }
        List<NameValuePair> bodyParameters = new ArrayList<>();
        for (Map.Entry<String, String> entry : postParams.entrySet()) {
            bodyParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }

        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 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();
        }
        return responseString.toString();
    }

    public byte[] postForBytes(String url, String payload, Map<String, String> headers) throws IOException {
        HttpPost post = new HttpPost(url);
        headers.forEach(post::setHeader);

        post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));

        try (CloseableHttpClient client = HttpClients.createDefault();
             CloseableHttpResponse response = client.execute(post)) {

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new IOException("Failed : HTTP error code : " + statusCode);
            }

            return EntityUtils.toByteArray(response.getEntity());
        }
    }

}