Package com.gateway.util

Source Code of com.gateway.util.ApiClient

package com.gateway.util;

import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.codehaus.groovy.grails.web.json.JSONArray;
import org.codehaus.groovy.grails.web.json.JSONObject;

import com.newrelic.api.agent.NewRelic;

/**
* @author Andres Funes
*
*/
public class ApiClient
{
  public static Map<String, Object> doPost(String url, Map<String, Object> bodyMap, Integer connectionTimeout, Integer soTimeout)
  {
    Map<String, Object> resp = postJSON(url, MapUtil.mapToString(bodyMap), connectionTimeout, soTimeout);
    if (!resp.containsKey("exception"))
      resp.put("response", MapUtil.jsonObjectToMap(new JSONObject((String) resp.get("response"))));
    return resp;
  }
 
  /*
   * @Agregado para postear sin JSON
   */
  public static Map<String, Object> doPost(String url, Integer connectionTimeout, Integer soTimeout)
  {
    Map<String, Object> resp = postNoJSON(url, connectionTimeout, soTimeout);
    if (!resp.containsKey("exception"))
      resp.put("response", MapUtil.jsonObjectToMap(new JSONObject((String) resp.get("response"))));
    return resp;
  }

  /**
   * @deprecated Use doPost
   */
  @Deprecated
  public static Map<String, Object> post(String url, String body, Integer connectionTimeout, Integer soTimeout)
  {
    return postJSON(url, body, connectionTimeout, soTimeout);
  }

  private static Map<String, Object> postJSON(String url, String body, Integer connectionTimeout, Integer soTimeout)
  {
    Map<String, Object> map;
    try
    {
      HttpPost httppost = new HttpPost(url);
      if (body != null)
      {
        httppost.setHeader("Content-Type", "application/json;charset=UTF-8");
        httppost.setEntity(new StringEntity(body, "UTF-8"));
      }
      map = executeMethod(httppost, url, body, connectionTimeout, soTimeout);
    }
    catch (UnsupportedEncodingException e)
    {
      map = new HashMap<String, Object>();
      map.put("exception", e);
    }
    return map;
  }
 
  /*
   * @ agregado para postear sin reqBody
   */
  private static Map<String, Object> postNoJSON(String url, String body, Integer connectionTimeout, Integer soTimeout){
    Map<String, Object> map;
    try
    {
      HttpPost httppost = new HttpPost(url);
      if (body != null)
      {
        httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        httppost.setEntity(new StringEntity(body, "UTF-8"));
      }
      map = executeMethod(httppost, url, body, connectionTimeout, soTimeout);
    }
    catch (UnsupportedEncodingException e)
    {
      map = new HashMap<String, Object>();
      map.put("exception", e);
    }
    return map;
  }

  public static Map<String, Object> doPut(String url, Map<String, Object> bodyMap, Integer connectionTimeout, Integer soTimeout)
  {
    Map<String, Object> resp = putJSON(url, MapUtil.mapToString(bodyMap), connectionTimeout, soTimeout);
    if (!resp.containsKey("exception"))
      resp.put("response", MapUtil.jsonObjectToMap(new JSONObject((String) resp.get("response"))));
    return resp;
  }

  /**
   * @deprecated Use doPut
   */
  @Deprecated
  public static Map<String, Object> put(String url, String body, Integer connectionTimeout, Integer soTimeout)
  {
    return putJSON(url, body, connectionTimeout, soTimeout);
  }

  private static Map<String, Object> putJSON(String url, String body, Integer connectionTimeout, Integer soTimeout)
  {
    Map<String, Object> map;
    try
    {
      HttpPut httpput = new HttpPut(url);
      if (body != null)
      {
        httpput.setHeader("Content-Type", "application/json;charset=UTF-8");
        httpput.setEntity(new StringEntity(body, "UTF-8"));
      }
      map = executeMethod(httpput, url, body, connectionTimeout, soTimeout);
    }
    catch (UnsupportedEncodingException e)
    {
      map = new HashMap<String, Object>();
      map.put("exception", e);
    }
    return map;
  }

  public static Map<String, Object> doGet(String url, Integer connectionTimeout, Integer soTimeout)
  {
    Map<String, Object> resp = getJSON(url, connectionTimeout, soTimeout);
    if (!resp.containsKey("exception"))
      resp.put("response", MapUtil.jsonObjectToMap(new JSONObject((String) resp.get("response"))));
    return resp;
  }

  public static Map<String, Object> doSearchAll(String url, Integer connectionTimeout, Integer soTimeout)
  {
    Map<String, Object> resp = getJSON(url, connectionTimeout, soTimeout);
    if (!resp.containsKey("exception"))
      resp.put("response", MapUtil.jsonArrayToList(new JSONArray((String) resp.get("response"))));
    return resp;
  }

  /**
   * @deprecated Use doGet
   */
  @Deprecated
  public static Map<String, Object> get(String url, Integer connectionTimeout, Integer soTimeout)
  {
    return getJSON(url, connectionTimeout, soTimeout);
  }

  private static Map<String, Object> getJSON(String url, Integer connectionTimeout, Integer soTimeout)
  {
    return executeMethod(new HttpGet(url), url, null, connectionTimeout, soTimeout);
  }

  public static Map<String, Object> doDelete(String url, Integer connectionTimeout, Integer soTimeout)
  {
    Map<String, Object> resp = deleteJSON(url, connectionTimeout, soTimeout);
    if (!resp.containsKey("exception"))
      resp.put("response", MapUtil.jsonObjectToMap(new JSONObject((String) resp.get("response"))));
    return resp;
  }

  /**
   * @deprecated Use doDelete
   */
  @Deprecated
  public static Map<String, Object> delete(String url, Integer connectionTimeout, Integer soTimeout)
  {
    return deleteJSON(url, connectionTimeout, soTimeout);
  }
 
  private static Map<String, Object> deleteJSON(String url, Integer connectionTimeout, Integer soTimeout)
  {
    return executeMethod(new HttpDelete(url), url, null, connectionTimeout, soTimeout);
  }

  private static Map<String, Object> executeMethod(HttpUriRequest httpUriRequest, String url, String body, Integer connectionTimeout, Integer soTimeout)
  {
    HashMap<String, Object> map = new HashMap<String, Object>();
    try
    {
      HttpClient client = getHttpClient(url, connectionTimeout, soTimeout);
      httpUriRequest.setHeader("Accept", "application/json");
      if (url.contains("/Cards/card/search"))
        url = truncData(url);
      long t1 = System.currentTimeMillis();
      HttpResponse response = client.execute(httpUriRequest);
      long t2 = System.currentTimeMillis();
      NewRelic.addCustomParameter(System.currentTimeMillis()+"--"+url, (t2 - t1) + " ms");
      HttpEntity resEntity = response.getEntity();
      String contentCharSet = EntityUtils.getContentCharSet(resEntity);
      map.put("status", response.getStatusLine().getStatusCode());
      map.put("response", contentCharSet != null ? new String(EntityUtils.toByteArray(resEntity), contentCharSet) : new String(EntityUtils.toByteArray(resEntity)));
    }
    catch (Exception e)
    {
      map.put("exception", e);
    }
    return map;
  }

  private static String truncData(String url)
  {
    return url.substring(0, url.indexOf("/card/search/") + 19);
  }

  private static HttpClient getHttpClient(String url, Integer connectionTimeout, Integer soTimeout) throws NoSuchAlgorithmException, KeyManagementException
  {
    Scheme httpsScheme = null;
    if (url.startsWith("https"))
    {
      SSLContext sslContext = SSLContext.getInstance("SSL");
      sslContext.init(null, new TrustManager[] { new X509TrustManager() {
              public X509Certificate[] getAcceptedIssuers()
              {
                return null;
              }
        public void checkClientTrusted(X509Certificate[] chain,  String authType) throws CertificateException
        {
        }
        public void checkServerTrusted(X509Certificate[] chain,  String authType) throws CertificateException
        {
        }
      }}, new SecureRandom());
      SSLSocketFactory sf = new SSLSocketFactory(sslContext, new AllowAllHostnameVerifier());
      httpsScheme = new Scheme("https", 443, sf);
    }
    else
      httpsScheme = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);
    HttpParams params = getHttpParams(connectionTimeout, soTimeout);
    ClientConnectionManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    return new DefaultHttpClient(cm, params);
  }

  private static HttpParams getHttpParams(Integer connectionTimeout, Integer soTimeout)
  {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
    HttpConnectionParams.setSoTimeout(params, soTimeout);
    return params;
  }
}
TOP

Related Classes of com.gateway.util.ApiClient

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.