Changeset 6638d33 in dispositivos_moviles for TibisayMovil/src


Ignore:
Timestamp:
Oct 14, 2013, 5:07:19 PM (11 years ago)
Author:
Antonio Araujo Brett <aaraujo@…>
Branches:
master
Children:
56b06e2
Parents:
308adc7
Message:

*- Revisión de la funcionalidad para descargar documento BDOC firmado desde un servidor web y lanzar la Activity correspondiente de Tibisay Móvil para verificar la(s) firma(s) electrónicas.

Location:
TibisayMovil/src/ve/gob/cenditel/tibisaymovil
Files:
1 added
1 edited

Legend:

Unmodified
Added
Removed
  • TibisayMovil/src/ve/gob/cenditel/tibisaymovil/BDOCVerifyResultActivity.java

    r308adc7 r6638d33  
    1212import java.net.URL;
    1313import java.net.URLConnection;
     14import java.security.KeyStore;
     15import java.security.cert.Certificate;
     16import java.security.cert.CertificateFactory;
    1417import java.util.ArrayList;
    1518
    1619import javax.net.ssl.HttpsURLConnection;
     20import javax.net.ssl.SSLContext;
     21import javax.net.ssl.TrustManagerFactory;
    1722
    1823
     
    2934import android.os.Looper;
    3035import android.app.Activity;
     36import android.app.AlertDialog;
    3137import android.app.Dialog;
    3238import android.app.ProgressDialog;
    3339import android.content.Context;
     40import android.content.DialogInterface;
    3441import android.content.Intent;
    3542import android.util.Log;
     
    6572    private String extractedDirFiles;
    6673   
     74    // cadena que mantiene la ruta para almacenar los archivos
     75    // descargados desde un servidor para verificar su firma
     76    private String downloadedDirFiles;
     77   
    6778    // ruta absoluta al archivo a verificar
    6879    private String fileToVerify;
     
    7990   
    8091        // Progress Dialog
    81     private ProgressDialog pDialog;
     92    private ProgressDialog mProgressDialog;
    8293   
    8394    // Progress dialog type (0 - for Horizontal progress bar)
    84     public static final int progress_bar_type = 0;
     95    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
     96   
     97    //String urlhttps = "https://tibisay.cenditel.gob.ve/trac/raw-attachment/wiki/WikiStart/actados.2.bdoc";
     98    String urlhttps = null;
    8599   
    86100        @Override
     
    190204                                  Toast.makeText(getApplicationContext(), "externalStorage: "+Environment.getExternalStorageDirectory().toString(), Toast.LENGTH_SHORT).show();
    191205                                 
     206                                  urlhttps = data.toString();
     207                                  new DownloadFileAsync().execute(data.toString(), "false");
    192208                                 
    193                                   new DownloadFileFromURL().execute(data.toString());
    194209                                  //new DownloadFileFromURL().execute("http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg");
    195210                                 
    196211                                  //Toast.makeText(getApplicationContext(), "****despues de execute()", Toast.LENGTH_SHORT).show();
    197212                                  // verificar el archivo
     213                                Toast.makeText(getApplicationContext(), "Ahora viene la verificación del archivo", Toast.LENGTH_SHORT).show();
    198214                          }
    199215                         
     
    208224                        mimeTypeFileToVerify = getMimeType(fileToVerify);
    209225                                       
    210                         Toast.makeText(getApplicationContext(), "fileToVerify: "+fileToVerify, Toast.LENGTH_SHORT).show();
     226                        Toast.makeText(getApplicationContext(), "BDOCVerifyResultActivity fileToVerify: "+fileToVerify, Toast.LENGTH_SHORT).show();
     227                        Toast.makeText(getApplicationContext(), "BDOCVerifyResultActivity fileToVerifyExtension: "+fileToVerifyExtension, Toast.LENGTH_SHORT).show();
    211228                       
    212229                        if (fileToVerifyExtension.equals("bdoc")){
     230                                Toast.makeText(getApplicationContext(), "BDOCVerifyResultActivity: -> doBdocVerification(fileToVerify)", Toast.LENGTH_SHORT).show();
    213231                                        // ejecutar la verificacion             
    214232                                        doBdocVerification(fileToVerify);
     
    287305        private void doBdocVerification(String absolutePathFileToVerify){
    288306               
     307                Toast.makeText(getApplicationContext(), "BDOCVerifyResultActivity: dentro doBdocVerification(fileToVerify)"+absolutePathFileToVerify, Toast.LENGTH_SHORT).show();
    289308                try {
    290309                        Log.d("doBdocVerification:", "Inicializando jdigidoc ...");
     
    372391                        getResources().getString(R.string.app_name) + "/" +
    373392                        getResources().getString(R.string.extracted_dir_files) + "/";                   
    374                         prepareDirectory();
     393                        prepareDirectory(extractedDirFiles);
    375394                       
    376395                        for (int i = 0; i < sdoc.countDataFiles(); i++){
     
    457476                        //showOneButtonDialog(e.getMessage());
    458477                       
    459                         Log.d("****exception:", e.getMessage());                                       
     478                        Log.d("****exception:", e.getMessage());
    460479                        e.printStackTrace();   
     480                        Toast.makeText(getApplicationContext(), "BDOCVerifyResultActivity: "+e.getMessage(), Toast.LENGTH_LONG).show();
    461481                }
    462482               
     
    711731     * @return boolean
    712732     */
    713     private boolean prepareDirectory()
     733    private boolean prepareDirectory(String dir)
    714734    {
    715735        try
    716736        {
    717             if (makedirs())
     737            if (makedirs(dir))
    718738            {
    719739                return true;
     
    733753     * @return boolean
    734754     */
    735     private boolean makedirs()
     755    private boolean makedirs(String dir)
    736756    {
    737         File tempdir = new File(extractedDirFiles);
     757        //File tempdir = new File(extractedDirFiles);
     758        File tempdir = new File(dir);
    738759        if (!tempdir.exists())
    739760            tempdir.mkdirs();
     
    825846    protected Dialog onCreateDialog(int id) {
    826847        switch (id) {
    827         case progress_bar_type: // we set this to 0
    828             pDialog = new ProgressDialog(this);
    829             pDialog.setMessage("Downloading file. Please wait...");
    830             pDialog.setIndeterminate(false);
    831             pDialog.setMax(100);
    832             pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    833             pDialog.setCancelable(true);
    834             pDialog.show();
    835             return pDialog;
     848        case DIALOG_DOWNLOAD_PROGRESS: // we set this to 0
     849                mProgressDialog = new ProgressDialog(this);
     850                mProgressDialog.setMessage("Descargando archivo. Por favor espere...");
     851                mProgressDialog.setIndeterminate(false);
     852                mProgressDialog.setMax(100);
     853                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
     854                mProgressDialog.setCancelable(true);
     855                mProgressDialog.show();
     856            return mProgressDialog;
    836857        default:
    837858            return null;
     
    840861       
    841862        // clase para descargar archivo
    842         private class DownloadFileFromURL extends AsyncTask<String, String, String> {
    843 
     863        private class DownloadFileAsync extends AsyncTask<String, String, ArrayList<String>> {
     864
     865                File rootDir = Environment.getExternalStorageDirectory();
    844866               
    845867                /**
     
    850872        protected void onPreExecute() {
    851873            super.onPreExecute();
    852             showDialog(progress_bar_type);
     874            showDialog(DIALOG_DOWNLOAD_PROGRESS);
    853875        }
    854876               
     
    858880         * */
    859881        @Override
    860         protected String doInBackground(String... f_url) {
     882        protected ArrayList<String> doInBackground(String... params) {
    861883           
    862884                // para solventar error:
     
    865887               
    866888                int count;
     889               
     890                Log.d("doInBackground", params[0]);
     891           
     892            // resultArray [0] -> 0 para ruta de archivo valida
     893            // resultArray [0] -> 1 ocurrio un error
     894            // resultArray [1] -> ruta del archivo descargado
     895            // resultArray [1] -> mensaje de la excepcion
     896            ArrayList<String> resultArray = new ArrayList<String>();
     897           
     898               
    867899           
    868900            String outputString = null;
    869901            try {
    870                 Toast.makeText(getApplicationContext(), "doInBackground", Toast.LENGTH_SHORT).show();
    871                 Log.d("doInBackground", "log");
    872                
    873                 URL url = new URL(f_url[0]);
    874                 //URLConnection conection = url.openConnection();
    875                 HttpURLConnection conection = (HttpURLConnection) url.openConnection();
    876                 conection.connect();
     902                URL url = new URL(params[0]);
     903               
     904                int lenghtOfFile = 0;
     905                InputStream input = null;
     906               
     907                if (url.getProtocol().equals("http")){
     908                        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
     909                        input = new BufferedInputStream(httpConnection.getInputStream());
     910                        lenghtOfFile = httpConnection.getContentLength();
     911                   
     912                }else{ // https
     913                       
     914                        // ejecutar la descarga despues de haber aceptado que el certificado
     915                        // no es conocido
     916                        if (params[1].equals("true")){
     917                                Log.d("***", "params[1].equals(true)");
     918                               
     919                                // descarga del certificado del servidor
     920                                CertificateFactory cf = CertificateFactory.getInstance("X.509");
     921                                InputStream caInput = new BufferedInputStream(new FileInputStream(rootDir+"/tibisay.cenditel.gob.ve.pem"));
     922                                //InputStream caInput = new BufferedInputStream(new FileInputStream(rootDir+"/tibisay.pem"));
     923                                Certificate ca;
     924                                try {
     925                                    ca = cf.generateCertificate(caInput);
     926                                    //Log.d("**ca:", ((X509Certificate) ca).getSubjectDN());
     927                                   
     928                                    //Log.d("*** try: ca.toString()", ca.toString());
     929                                } finally {
     930                                    caInput.close();
     931                                }
     932                                Log.d("***", "despues de Certificate ca");
     933                                // Create a KeyStore containing our trusted CAs
     934                                String keyStoreType = KeyStore.getDefaultType();
     935                                KeyStore keyStore = KeyStore.getInstance(keyStoreType);
     936                                keyStore.load(null, null);
     937                                keyStore.setCertificateEntry("ca", ca);
     938                                Log.d("***", "despues de crear KeyStore");
     939                               
     940                                // Create a TrustManager that trusts the CAs in our KeyStore
     941                                String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
     942                                TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
     943                                tmf.init(keyStore);
     944                                Log.d("***", "despues de crear TrustManager");
     945
     946                                // Create an SSLContext that uses our TrustManager
     947                                SSLContext context = SSLContext.getInstance("TLS");
     948                                context.init(null, tmf.getTrustManagers(), null);
     949                                Log.d("***", "despues de crear SSLContext");
     950                               
     951                                HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();
     952                                Log.d("***", "despues de crear httpsConnection");
     953                               
     954                                httpsConnection.setSSLSocketFactory(context.getSocketFactory());
     955                                Log.d("***", "despues de crear setSSLSocketFactory");
     956                               
     957                                //input = new BufferedInputStream(httpsConnection.getInputStream());
     958                                input = httpsConnection.getInputStream();
     959                               
     960                                Log.d("***", "despues de crear BufferedInputStream");
     961                               
     962                                lenghtOfFile = httpsConnection.getContentLength();
     963                                Log.d("***", "se acepto la excepcion");
     964                               
     965                        }else{                 
     966                                HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();
     967                                input = new BufferedInputStream(httpsConnection.getInputStream());
     968                                lenghtOfFile = httpsConnection.getContentLength();
     969                        }
     970                }
    877971               
    878972               
     973                // Crear directorio DownloadedFiles donde se almacenan los archivos descargados
     974                        // desde un servidor para verificar su firma
     975                        downloadedDirFiles = Environment.getExternalStorageDirectory() + "/" +
     976                        getResources().getString(R.string.app_name) + "/" +
     977                        getResources().getString(R.string.downloaded_dir_files) + "/";                 
     978                        prepareDirectory(downloadedDirFiles);
     979
     980                //int lenghtOfFile = conexion.getContentLength();
     981                Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
     982
     983                //InputStream input = new BufferedInputStream(url.openStream());               
     984                //InputStream input = new BufferedInputStream(conexion.getInputStream());
    879985               
    880                 // this will be useful so that you can show a tipical 0-100% progress bar
    881                 int lenghtOfFile = conection.getContentLength();
    882  
    883                 // download the file
    884                 //InputStream input = new BufferedInputStream(url.openStream(), 8192);
    885                 InputStream input = new BufferedInputStream(url.openStream());
    886  
     986                //OutputStream output = new FileOutputStream("/mnt/sdcard/TibisayMovil/ExtractedFiles/photo.jpg");
    887987               
    888                 File rootDir = Environment.getExternalStorageDirectory();
    889                 // Output stream
    890                 //OutputStream output = new FileOutputStream("/sdcard/downloaded.jpg");
    891                 OutputStream output = new FileOutputStream(new File(rootDir+"/TibisayMovil/", "descarga.bdoc"));
    892  
     988                //OutputStream output = new FileOutputStream(new File(rootDir+"/midescarga/", "foto.jpg"));
     989
     990                String urlString = url.toString();
     991                String[] values = urlString.split("/");
     992               
     993                //OutputStream output = new FileOutputStream(new File(downloadedDirFiles, "acta.2.bdoc"));
     994                OutputStream output = new FileOutputStream(new File(downloadedDirFiles, values[values.length-1]));
     995               
    893996                byte data[] = new byte[1024];
    894  
     997
    895998                long total = 0;
    896  
     999
    8971000                while ((count = input.read(data)) != -1) {
    8981001                    total += count;
    899                     // publishing the progress....
    900                     // After this onProgressUpdate will be called
    9011002                    publishProgress(""+(int)((total*100)/lenghtOfFile));
    902  
    903                     // writing data to file
    904                     //output.write(data, 0, count);
     1003                    output.write(data, 0, count);
    9051004                }
    906  
    907                 // flushing output
     1005
    9081006                output.flush();
    909  
    910                 // closing streams
     1007                               
    9111008                output.close();
    912                
    9131009                input.close();
    9141010               
     1011                resultArray.add("0");
     1012                resultArray.add(output.toString());
    9151013 
    9161014            } catch (Exception e) {
     
    9191017                outputString = e.getMessage();
    9201018               
     1019                resultArray.add("1");
     1020                resultArray.add(e.toString());
    9211021               
    9221022            }
    923  
     1023
    9241024            //return null;
    925             return outputString;
     1025            return resultArray;
    9261026           
    9271027        }
    9281028       
    929         /**
    930          * Updating progress bar
    931          * */
    9321029        protected void onProgressUpdate(String... progress) {
    933             // setting progress percentage
    934             pDialog.setProgress(Integer.parseInt(progress[0]));
    935         }
     1030            Log.d("ANDRO_ASYNC",progress[0]);
     1031            mProgressDialog.setProgress(Integer.parseInt(progress[0]));
     1032       }
     1033
     1034       @Override
     1035       protected void onPostExecute(ArrayList<String> result) {
     1036           dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
     1037           Toast.makeText(getApplicationContext(), "onPostExecute: "+ result.get(0), Toast.LENGTH_LONG).show();
     1038           
     1039           // ocurrio una excepcion
     1040           if (result.get(0).equals("1")){
     1041               
     1042                   Toast.makeText(getApplicationContext(), "onPostExecute: dentro del if" , Toast.LENGTH_LONG).show();
     1043               
     1044                // ocurrio un problema
     1045                AlertDialog.Builder builder = new AlertDialog.Builder(BDOCVerifyResultActivity.this);
     1046               
     1047               
     1048                builder.setMessage(result.get(1)).setTitle("Error al descargar el archivo");
     1049               
     1050                builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
     1051                   public void onClick(DialogInterface dialog, int id) {
     1052                       // User clicked OK button
     1053               
     1054                        Log.d("***", "DownloadFileAsync().execute(urlhttps, true)");
     1055                        Toast.makeText(getApplicationContext(), "DownloadFileAsync().execute(urlhttps, true)", Toast.LENGTH_LONG).show();
     1056                        // pasar como segundo argmento que se acepta que el sertivor es desconocido
     1057                        new DownloadFileAsync().execute(urlhttps, "true");
     1058                   }
     1059               });
     1060                builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
     1061                   public void onClick(DialogInterface dialog, int id) {
     1062                       // User cancelled the dialog
     1063                   }
     1064               });
     1065                AlertDialog dialog = builder.create();
     1066               dialog.show();
     1067               
     1068               
     1069               
     1070           }else{
     1071                   // no ocurrió excepcion
     1072                   Toast.makeText(getApplicationContext(), "Se descargo correctamente el archivo", Toast.LENGTH_LONG).show();
     1073               
     1074               
     1075               
     1076               
     1077           }
     1078           
     1079                 
     1080       }
     1081       
     1082
    9361083       
    937         /**
    938          * After completing background task
    939          * Dismiss the progress dialog
    940          * **/
    941         @Override
    942         protected void onPostExecute(String file_url) {
    943             // dismiss the dialog after the file was downloaded
    944             dismissDialog(progress_bar_type);
    945  
    946             // Displaying downloaded image into image view
    947             // Reading image path from sdcard
    948             //String filePath = Environment.getExternalStorageDirectory().toString() + "/TibisayMovil" +"/downloaded.bdoc";
    949             Toast.makeText(getApplicationContext(), "onPostExecute "  , Toast.LENGTH_SHORT).show();
    950             Toast.makeText(getApplicationContext(), file_url  , Toast.LENGTH_LONG).show();
    951             // setting downloaded into image view
    952             //my_image.setImageDrawable(Drawable.createFromPath(imagePath));
    953         }
    954        
    955                        
    956                
    957         }
    958        
    959 
    960 
    961                
    962        
     1084
     1085               
     1086       
     1087        } // fin de la clase DownloadFileAsync
    9631088}
    9641089
Note: See TracChangeset for help on using the changeset viewer.