com.curso.listadapter.net.RESTClient.java Source code

Java tutorial

Introduction

Here is the source code for com.curso.listadapter.net.RESTClient.java

Source

/* *************************************************************************
 *
 *   Copyright (c)  2012 by Jaguar Labs.
 *   Confidential and Proprietary
 *   All Rights Reserved
 *
 *   This software is furnished under license and may be used and copied
 *   only in accordance with the terms of its license and with the
 *   inclusion of the above copyright notice. This software and any other
 *   copies thereof may not be provided or otherwise made available to any
 *   other party. No title to and/or ownership of the software is hereby
 *   transferred.
 *
 *   The information in this software is subject to change without notice and
 *   should not be construed as a commitment by JaguarLabs.
 *
 * @(#)$Id: $
 * Last Revised By   : $Author:efren campillo
 * Last Checked In   : $Date: $
 * Last Version      : $Revision:  feb 28 2014
 *
 * Original Author   : efren campillo  -- efren.campillo@jaguarlabs.com
 * Origin            : SEnE -- november 2 @ 11:00 (PST)
 * Notes             :
 *
 * *************************************************************************/

package com.curso.listadapter.net;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HttpsURLConnection;
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.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.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.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.util.Log;
import android.webkit.MimeTypeMap;

public class RESTClient {

    public static final String JSON = "application/json";
    public static final String URLENCODED = "application/x-www-form-urlencoded";

    private int RequestTimeOut = 60000;

    public static enum RequestMethod {
        GET, POST, PUT, DELETE
    }

    private ArrayList<NameValuePair> params;
    private ArrayList<NameValuePair> headers;
    public String post;
    private String url;

    private int responseCode;
    private String message;
    private String response;
    private String contentType;

    /**
     * default methods to manage the restclient
     * */
    public String getResponse() {
        return response;
    }

    public String getErrorMessage() {
        return message;
    }

    public int getResponseCode() {
        return responseCode;
    }

    public RESTClient(String url) {
        this.url = url;
        params = new ArrayList<NameValuePair>();
        headers = new ArrayList<NameValuePair>();
        contentType = JSON;
    }

    public void AddParam(String name, String value) {
        params.add(new BasicNameValuePair(name, value));
    }

    public void setParams(ArrayList<NameValuePair> params) {
        this.params = params;
    }

    public void AddHeader(String name, String value) {
        headers.add(new BasicNameValuePair(name, value));
    }

    public RESTClient setContentType(String content) {
        contentType = content;
        return this;
    }

    public String getUrl() {
        return url;
    }

    public RESTClient setUrl(String url) {
        this.url = url;
        return this;
    }

    public RESTClient setPost(String pPost) {
        this.post = pPost;
        return this;
    }

    /**
     * this set the miliseccond time out default
     * */
    public void setRequestTimeOut(int milliseconds) {
        if (milliseconds < 1000) {
            Log.d("requestTimeOut", "value very low for internet request it keeps in 30 seconds");
        } else {
            RequestTimeOut = milliseconds;
        }
    }

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";

    /**
     * upload multipart
     * this method receive the file to be uploaded
     * */
    @SuppressWarnings("deprecation")
    public String uploadMultiPart(Map<String, File> files) throws Exception {
        disableSSLCertificateChecking();
        Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        try {
            URL endpoint = new URL(url);
            conn = (HttpURLConnection) endpoint.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            dos = new DataOutputStream(conn.getOutputStream());
            String post = "";

            //WRITE ALL THE PARAMS
            for (NameValuePair p : params)
                post += writeMultipartParam(p);
            dos.flush();
            //END WRITE ALL THE PARAMS

            //BEGIN THE UPLOAD
            ArrayList<FileInputStream> inputStreams = new ArrayList<FileInputStream>();
            for (Entry<String, File> entry : files.entrySet()) {
                post += lineEnd;
                post += twoHyphens + boundary + lineEnd;
                String NameParamImage = entry.getKey();
                File file = entry.getValue();
                int bytesRead, bytesAvailable, bufferSize;
                byte[] buffer;
                int maxBufferSize = 1 * 1024 * 1024;
                FileInputStream fileInputStream = new FileInputStream(file);

                post += "Content-Disposition: attachment; name=\"" + NameParamImage + "\"; filename=\""
                        + file.getName() + "\"" + lineEnd;
                String mimetype = getMimeType(file.getName());
                post += "Content-Type: " + mimetype + lineEnd;
                post += "Content-Transfer-Encoding: binary" + lineEnd + lineEnd;

                dos.write(post.toString().getBytes("UTF-8"));

                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                while (bytesRead > 0) {
                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    inputStreams.add(fileInputStream);
                }

                Log.d("Test", post);
                dos.flush();
                post = "";
            }

            //END THE UPLOAD

            dos.writeBytes(lineEnd);

            dos.writeBytes(twoHyphens + boundary + twoHyphens);
            //            for(FileInputStream inputStream: inputStreams){
            //               inputStream.close();
            //            }
            dos.flush();
            dos.close();
            conn.connect();
            Log.d("upload", "finish flush:" + conn.getResponseCode());
        } catch (MalformedURLException ex) {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
        } catch (IOException ioe) {
            Log.e("Debug", "error: " + ioe.getMessage(), ioe);
        }
        try {
            String response_data = "";
            inStream = new DataInputStream(conn.getInputStream());
            String str;
            while ((str = inStream.readLine()) != null) {
                response_data += str;
            }
            inStream.close();
            return response_data;
        } catch (IOException ioex) {
            Log.e("Debug", "error: " + ioex.getMessage(), ioex);
        }
        return null;
    }

    private String writeMultipartParam(NameValuePair nameValue) {
        String result = "";
        result += twoHyphens + boundary + lineEnd;
        result += "Content-Disposition: form-data; name=\"" + nameValue.getName() + "\"" + lineEnd + lineEnd;
        result += nameValue.getValue() + lineEnd;
        return result;
    }

    public void writeFile(DataOutputStream dos, String NameParamImage, File file) {
        //BEGIN THE UPLOAD
        Log.d("Test", "(********) BEGINS THE WRITTING");
        if (file.exists()) {
            Log.d("Test", "(*****) FILE EXISTES");
        } else {
            Log.d("Test", "(*****) FILE DOES NOT EXIST");
        }
        try {
            FileInputStream fileInputStream;
            fileInputStream = new FileInputStream(file);
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
            Log.e("Test", "(*****) fileInputStream.available():" + fileInputStream.available());
            post += "Content-Disposition: attachment; name=\"" + NameParamImage + "\"; filename=\"" + file.getName()
                    + "\"" + lineEnd;
            String mimetype = getMimeType(file.getName());
            post += "Content-Type: " + mimetype + lineEnd;
            post += "Content-Transfer-Encoding: binary" + lineEnd + lineEnd;

            dos.writeBytes(post);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }
            fileInputStream.close();
            post += lineEnd;
            post += twoHyphens + boundary + twoHyphens;
            Log.i("Test", "(********) WRITING FILE ENDED");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Log.d("Test", "(********) EXITING FROM FILE WRITTING");
    }

    public static String getMimeType(String url) {
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);
        if (extension != null) {
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            type = mime.getMimeTypeFromExtension(extension);
        }
        return type;
    }

    /**
     * this method utoacepts all certificates in httpsurlconections
     * */
    @SuppressLint("TrulyRandom")
    private static void disableSSLCertificateChecking() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }
        } };
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    /**
     * exceute the post defined to the url defined
     *
     * */
    public void Execute(RequestMethod method) throws Exception {
        //Debug.log("Exceute","request:"+method.toString()+" in "+url);
        switch (method) {
        case GET: {
            // add parameters
            String combinedParams = "";
            if (!params.isEmpty()) {
                combinedParams += "?";
                for (NameValuePair p : params) {
                    String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(), "UTF-8");
                    if (combinedParams.length() > 1) {
                        combinedParams += "&" + paramString;
                    } else {
                        combinedParams += paramString;
                    }
                }
            }
            //      Debug.log("RestClient","GET  :"+url + combinedParams);
            HttpGet request = new HttpGet(url + combinedParams);
            request.setHeader("Content-Type", contentType);
            // add headers
            for (NameValuePair h : headers) {
                request.addHeader(h.getName(), h.getValue());
            }
            executeRequest(request, url);
            break;
        }
        case PUT:
        case POST: {
            HttpPost request = new HttpPost(url);
            request.setHeader("Content-type", "application/json");
            // add headers
            for (NameValuePair h : headers) {
                request.addHeader(h.getName(), h.getValue());
            }
            if (!params.isEmpty()) {
                JSONObject obj = new JSONObject();
                for (NameValuePair pair : params) {

                    try {
                        obj.put(pair.getName(), pair.getValue());

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
                post = obj.toString();
                if (post.contains("privado")) {
                    post = post.replace("\"false\"", "false");
                    post = post.replace("\"true\"", "true");
                }
                Log.d("Test", "RestClient HTTP method: POST");
                Log.d("Test", "RestClient Url:");
                Log.d("Test", url);
                Log.d("Test", "RestClient params:");
                Log.d("Test", post);
                request.setEntity(new ByteArrayEntity(post.toString().getBytes("UTF8")));
            }

            executeRequest(request, url);
            break;
        }
        case DELETE:
            HttpDelete request = new HttpDelete(url);
            executeRequest(request, url);
            break;
        }
    }

    /**
     * executing request from post in execute restclient
     *
     * */
    private void executeRequest(HttpUriRequest request, String url) throws Exception {
        HttpClient client = getNewHttpClient();//; new DefaultHttpClient(httpParams);
        HttpResponse httpResponse;
        try {
            httpResponse = client.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                response = convertStreamToString(instream);
                instream.close();
            }
        } catch (ClientProtocolException e) {
            client.getConnectionManager().shutdown();
            Log.d("RestClientExecption", "protocol error at:" + this.url);
            e.printStackTrace();
            throw new Exception();
        } catch (IOException e) {
            Log.d("RestClientExecption", "I/O error at:" + this.url);
            client.getConnectionManager().shutdown();
            e.printStackTrace();
            throw new Exception();
        }
    }

    /**
     *
     * convert the Stream from the request in a String readeable to the rest client
     *
     * */
    public static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    /**
     *
     * this private method obtains the httpclient that support https
     * and set the timeout in 30 secconds
     *
     *
     * */
    public HttpClient getNewHttpClient() {
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
            sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
            HttpConnectionParams.setConnectionTimeout(params, RequestTimeOut);
            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            registry.register(new Scheme("https", sf, 443));
            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
            return new DefaultHttpClient(ccm, params);
        } catch (Exception e) {
            return new DefaultHttpClient();
        }
    }

    private class MySSLSocketFactory extends SSLSocketFactory {
        SSLContext sslContext = SSLContext.getInstance("TLS");

        public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
                KeyStoreException, UnrecoverableKeyException {
            super(truststore);
            TrustManager tm = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            sslContext.init(null, new TrustManager[] { tm }, null);
        }

        @Override
        public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
                throws IOException, UnknownHostException {
            return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
        }

        @Override
        public Socket createSocket() throws IOException {
            return sslContext.getSocketFactory().createSocket();
        }
    }

}