source: dispositivos_moviles/TibisayMovil/src/ve/gob/cenditel/tibisaymovil/DownloaderActivity.java @ ba6bc7c

Last change on this file since ba6bc7c was ba6bc7c, checked in by Antonio Araujo Brett <aaraujo@…>, 11 years ago

Deshabilitados mensajes de depuración en clases.

  • Property mode set to 100644
File size: 24.0 KB
Line 
1package ve.gob.cenditel.tibisaymovil;
2
3
4import java.io.BufferedInputStream;
5import java.io.File;
6import java.io.FileInputStream;
7import java.io.FileOutputStream;
8import java.io.IOException;
9import java.io.InputStream;
10import java.io.OutputStream;
11import java.lang.reflect.Field;
12import java.net.HttpURLConnection;
13import java.net.URL;
14import java.security.KeyStore;
15import java.security.cert.Certificate;
16import java.security.cert.CertificateFactory;
17import java.util.ArrayList;
18
19import javax.net.ssl.HttpsURLConnection;
20import javax.net.ssl.SSLContext;
21import javax.net.ssl.TrustManagerFactory;
22
23
24import android.net.Uri;
25import android.os.AsyncTask;
26import android.os.Bundle;
27import android.os.Environment;
28import android.os.Looper;
29import android.app.Activity;
30import android.app.AlertDialog;
31import android.app.Dialog;
32import android.app.ProgressDialog;
33import android.content.DialogInterface;
34import android.content.Intent;
35import android.util.Log;
36import android.view.Menu;
37import android.view.Window;
38import android.webkit.MimeTypeMap;
39import android.widget.Toast;
40
41public class DownloaderActivity extends Activity {
42
43        // cadena que mantiene la ruta para almacenar los archivos
44    // extraidos de un contendor BDOC
45    private String extractedDirFiles;
46   
47    // cadena que mantiene la ruta para almacenar los archivos
48    // descargados desde un servidor para verificar su firma
49    private String downloadedDirFiles;
50   
51    // ruta absoluta al archivo a verificar
52    private String fileToVerify;
53   
54    // extension del archivo a verificar
55    private String fileToVerifyExtension;
56       
57    // cadena que mantiene la URL al descargar archivo con https
58    String urlhttps = null;
59       
60        // Progress Dialog
61    private ProgressDialog mProgressDialog;
62   
63    // Progress dialog type (0 - for Horizontal progress bar)
64    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
65
66   
67   
68        @Override
69        protected void onCreate(Bundle savedInstanceState) {
70               
71                //Estilando la barra de titulo
72                final boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
73                               
74                super.onCreate(savedInstanceState);
75                //setContentView(R.layout.activity_downloader);
76                setContentView(R.layout.activity_verify_result_bdoc);
77               
78                //Estilando Barra de titulo
79                if(customTitleSupported)
80                        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar);
81               
82                // ------------------------------------------------------------------------------------
83                // el siguiente segmento de codigo permite obtener los nombres de los archivos
84                // que estan en /res/raw
85                ArrayList<String> list = new ArrayList<String>();
86                Field[] fields = R.raw.class.getFields();
87               
88                for (int l=0; l < fields.length; l++) {
89                        try {
90                                Toast.makeText(getApplicationContext(), "DownloaderActivity: "+Integer.toString(l)+ " "+ Integer.toString(fields[l].getInt(null)), Toast.LENGTH_SHORT).show();
91                        } catch (IllegalArgumentException e) {
92                                // TODO Auto-generated catch block
93                                Toast.makeText(getApplicationContext(), "DownloaderActivity: IllegalArgumentException "+e.getMessage(), Toast.LENGTH_SHORT).show();
94                        } catch (IllegalAccessException e) {
95                                // TODO Auto-generated catch block
96                                Toast.makeText(getApplicationContext(), "DownloaderActivity: IllegalAccessException "+e.getMessage(), Toast.LENGTH_SHORT).show();
97                        }
98                }
99               
100                /*
101                for(Field f : fields)
102                try {
103                        Toast.makeText(getApplicationContext(), "DownloaderActivity: Fields.length: "+Integer.toString(fields.length), Toast.LENGTH_SHORT).show();
104                        Toast.makeText(getApplicationContext(), "DownloaderActivity: "+f.getName(), Toast.LENGTH_SHORT).show();
105                        //list.add(splitString[0]);
106                } catch (IllegalArgumentException e) {
107                        Toast.makeText(getApplicationContext(), "DownloaderActivity: IllegalArgumentException "+e.getMessage(), Toast.LENGTH_SHORT).show();
108                }
109                */
110                // ------------------------------------------------------------------------------------
111               
112               
113               
114                // chequear si intent tiene data
115        final android.content.Intent intent = getIntent();
116
117        final Bundle bundle = getIntent().getExtras();
118       
119              if (intent != null) {
120                  //Toast.makeText(getApplicationContext(), "DownloaderActivity: intent != null", Toast.LENGTH_SHORT).show();
121
122                  final android.net.Uri data = intent.getData ();
123                 
124                      if (data != null) {
125                          //Toast.makeText(getApplicationContext(), "data != null", Toast.LENGTH_SHORT).show();
126                         
127                          // verificar el tipo de scheme
128                          String scheme = data.getScheme();
129                           
130                          // verificacion de un archivo que esta en el dispositivo
131                          if (scheme.equals("file")) {
132                                  //Toast.makeText(getApplicationContext(), "file: "+data.getPath(), Toast.LENGTH_SHORT).show();
133                                 
134                                  // verificar el archivo
135                                  if (data.getPath().endsWith("bdoc")){
136                                          fileToVerify = data.getPath();
137                                         
138                                          // ejecutar la verificacion           
139                                          //doBdocVerification(data.getPath());
140                                                }else{
141                                                        //Toast.makeText(getApplicationContext(), "¡Por Implementar!", Toast.LENGTH_SHORT).show();
142                                                       
143                                                }
144                                 
145                          }
146                           
147                          // verificacion de un archivo que se debe descargar
148                          if (scheme.equals("https")) {
149                                  //Toast.makeText(getApplicationContext(), "scheme: "+data.toString(), Toast.LENGTH_SHORT).show();
150                                 
151                                  //Toast.makeText(getApplicationContext(), "externalStorage: "+Environment.getExternalStorageDirectory().toString(), Toast.LENGTH_SHORT).show();
152                                 
153                                  urlhttps = data.toString();
154                                  new DownloadFileAsync().execute(data.toString(), "false");
155                                 
156                                  //new DownloadFileFromURL().execute("http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg");
157                                 
158                                  //Toast.makeText(getApplicationContext(), "****despues de execute()", Toast.LENGTH_SHORT).show();
159                                  // verificar el archivo
160                                  //Toast.makeText(getApplicationContext(), "Ahora viene la verificación del archivo", Toast.LENGTH_SHORT).show();
161                          }
162                         
163                         
164                          return;
165                      }
166                     
167                      // verificacion de archivo desde la Activity principal
168                      if (bundle != null) {
169                        fileToVerify = bundle.getString("fileToVerify");
170                        fileToVerifyExtension = bundle.getString("fileExtension"); 
171                       
172                                       
173                        //Toast.makeText(getApplicationContext(), "fileToVerify bundle!=null: "+fileToVerify, Toast.LENGTH_SHORT).show();
174                       
175                        if (fileToVerifyExtension.equals("bdoc")){
176                                //Toast.makeText(getApplicationContext(), "verificacion de archivo desde la Activity principal", Toast.LENGTH_SHORT).show();
177                                        // ejecutar la verificacion             
178                                        //doBdocVerification(fileToVerify);
179                                }else{
180                                        //Toast.makeText(getApplicationContext(), "¡Por Implementar!", Toast.LENGTH_SHORT).show();
181                                       
182                                }
183                       
184                        //return;
185                      }
186                                 
187              }else{
188                  //Toast.makeText(getApplicationContext(), "intent == null", Toast.LENGTH_SHORT).show();
189              }
190               
191        }
192
193       
194        /**
195     * Prepara directorio
196     * @return boolean
197     */
198    private boolean prepareDirectory(String dir) 
199    {
200        try
201        {
202            if (makedirs(dir)) 
203            {
204                return true;
205            } else {
206                return false;
207            }
208        } catch (Exception e) 
209        {
210            e.printStackTrace();
211            //Toast.makeText(this, "Could not initiate File System.. Is Sdcard mounted properly?", Toast.LENGTH_LONG).show();
212            Toast.makeText(this, "No se pudo iniciar el sistema de archivos. ¿Está la SDCARD montada?", Toast.LENGTH_LONG).show();
213            return false;
214        }
215    }
216 
217    /**
218     * Crea directorio utilizando la variable tmpDir
219     * @return boolean
220     */
221    private boolean makedirs(String dir) 
222    {
223        //File tempdir = new File(extractedDirFiles);
224        File tempdir = new File(dir);
225        if (!tempdir.exists())
226            tempdir.mkdirs();
227 
228//        if (tempdir.isDirectory())
229//        {
230//            File[] files = tempdir.listFiles();
231//            for (File file : files)
232//            {
233//                if (!file.delete())
234//                {
235//                    System.out.println("Failed to delete " + file);
236//                }
237//            }
238//        }
239        return (tempdir.isDirectory());
240    }
241       
242       
243        /**
244     * Showing Dialog for downloading file
245     * */
246    @Override
247    protected Dialog onCreateDialog(int id) {
248        switch (id) {
249        case DIALOG_DOWNLOAD_PROGRESS: // we set this to 0
250                mProgressDialog = new ProgressDialog(this);
251                mProgressDialog.setMessage("Descargando archivo. Por favor espere...");
252                mProgressDialog.setIndeterminate(false);
253                mProgressDialog.setMax(100);
254                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
255                mProgressDialog.setCancelable(true);
256                mProgressDialog.show();
257            return mProgressDialog;
258        default:
259            return null;
260        }
261    }
262       
263   
264 // clase para descargar archivo
265        private class DownloadFileAsync extends AsyncTask<String, String, ArrayList<String>> {
266
267                File rootDir = Environment.getExternalStorageDirectory();
268               
269                /**
270         * Before starting background thread
271         * Show Progress Bar Dialog
272         * */
273        @Override
274        protected void onPreExecute() {
275            super.onPreExecute();
276            showDialog(DIALOG_DOWNLOAD_PROGRESS);
277        }
278               
279               
280        /**
281         * Downloading file in background thread
282         * */
283        @Override
284        protected ArrayList<String> doInBackground(String... params) {
285           
286                // para solventar error:
287                // Can't create handler inside thread that has not called Looper.prepare()
288                Looper.prepare();
289               
290                int count;
291               
292                Log.d("doInBackground", params[0]);
293           
294            // resultArray [0] -> 0 para ruta de archivo valida
295            // resultArray [0] -> 1 ocurrio un error
296            // resultArray [1] -> ruta del archivo descargado
297            // resultArray [1] -> mensaje de la excepcion
298            ArrayList<String> resultArray = new ArrayList<String>();
299            resultArray.clear();
300               
301           
302            String outputString = null;
303            try {
304                URL url = new URL(params[0]);
305               
306                int lenghtOfFile = 0;
307                InputStream input = null;
308               
309                if (url.getProtocol().equals("http")){
310                        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
311                        input = new BufferedInputStream(httpConnection.getInputStream());
312                        lenghtOfFile = httpConnection.getContentLength();
313                   
314                }else{ // https
315                       
316                        // ejecutar la descarga despues de haber aceptado que el certificado
317                        // no es conocido
318                        if (params[1].equals("true")){
319                                Log.d("***", "params[1].equals(true)");
320                               
321                                // descarga del certificado del servidor
322                               
323                                // crear certificate factory
324                                CertificateFactory cf = CertificateFactory.getInstance("X.509");
325                               
326                                // crear un KeyStore
327                                String keyStoreType = KeyStore.getDefaultType();
328                        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
329                        keyStore.load(null, null);
330                               
331                        // obtener vector de campos de /res/raw
332                                Field[] fields = R.raw.class.getFields();
333                               
334                                InputStream caInput = null; 
335                               
336                                // iterar sobre todos los certificados incluidos en /res/raw y cargarlos
337                                // en el KeyStore
338                                for (int l=0; l < fields.length; l++) {
339                                        try {
340                                                //Toast.makeText(getApplicationContext(), "DownloaderActivity: "+Integer.toString(l)+ " "+
341                                                //      Integer.toString(fields[l].getInt(null)), Toast.LENGTH_SHORT).show();
342
343                                                caInput = new BufferedInputStream(getResources().openRawResource(fields[l].getInt(null))); 
344
345                                        } catch (IllegalArgumentException e) {
346                                                // TODO Auto-generated catch block
347                                                Toast.makeText(getApplicationContext(), "DownloaderActivity: IllegalArgumentException "+e.getMessage(),                                         Toast.LENGTH_SHORT).show();
348                                        } catch (IllegalAccessException e) {
349                                                // TODO Auto-generated catch block
350                                                Toast.makeText(getApplicationContext(), "DownloaderActivity: IllegalAccessException "+e.getMessage(),                                   Toast.LENGTH_SHORT).show();
351                                        }
352                                                                         
353                            Certificate ca;
354                            try {
355                                ca = cf.generateCertificate(caInput);
356                                //Log.d("**ca:", ((X509Certificate) ca).getSubjectDN());
357                                           
358                                //Log.d("*** try: ca.toString()", ca.toString());
359                                } finally {
360                                    caInput.close();
361                                }
362                                        keyStore.setCertificateEntry("ca"+Integer.toString(l), ca);
363                                }// fin de la iteracion sobre /res/raw
364
365                                // Create a TrustManager that trusts the CAs in our KeyStore
366                                String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
367                                TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
368                                tmf.init(keyStore);
369                                Log.d("***", "despues de crear TrustManager");
370
371                                // Create an SSLContext that uses our TrustManager
372                                SSLContext context = SSLContext.getInstance("TLS");
373                                context.init(null, tmf.getTrustManagers(), null);
374                                Log.d("***", "despues de crear SSLContext");
375                               
376                                HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();
377                                Log.d("***", "despues de crear httpsConnection");
378                               
379                                httpsConnection.setSSLSocketFactory(context.getSocketFactory());
380                                Log.d("***", "despues de crear setSSLSocketFactory");
381                               
382                                //input = new BufferedInputStream(httpsConnection.getInputStream());
383                                input = httpsConnection.getInputStream();
384                               
385                                Log.d("***", "despues de crear BufferedInputStream");
386                               
387                                lenghtOfFile = httpsConnection.getContentLength();
388                                Log.d("***", "se acepto la excepcion");
389
390                               
391                                /*
392                                // descarga del certificado del servidor
393                                CertificateFactory cf = CertificateFactory.getInstance("X.509");
394                                InputStream caInput = new BufferedInputStream(getResources().openRawResource(R.raw.gestion));
395                                Certificate ca;
396                                try {
397                                    ca = cf.generateCertificate(caInput);
398                                    //Log.d("**ca:", ((X509Certificate) ca).getSubjectDN());
399                                   
400                                    //Log.d("*** try: ca.toString()", ca.toString());
401                                } finally {
402                                    caInput.close();
403                                }
404                                Log.d("***", "despues de Certificate ca");
405                               
406                                // Create a KeyStore containing our trusted CAs
407                                String keyStoreType = KeyStore.getDefaultType();
408                                KeyStore keyStore = KeyStore.getInstance(keyStoreType);
409                                keyStore.load(null, null);
410                                keyStore.setCertificateEntry("ca", ca);
411                                Log.d("***", "despues de crear KeyStore");
412                               
413                                // Create a TrustManager that trusts the CAs in our KeyStore
414                                String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
415                                TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
416                                tmf.init(keyStore);
417                                Log.d("***", "despues de crear TrustManager");
418
419                                // Create an SSLContext that uses our TrustManager
420                                SSLContext context = SSLContext.getInstance("TLS");
421                                context.init(null, tmf.getTrustManagers(), null);
422                                Log.d("***", "despues de crear SSLContext");
423                               
424                                HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();
425                                Log.d("***", "despues de crear httpsConnection");
426                               
427                                httpsConnection.setSSLSocketFactory(context.getSocketFactory());
428                                Log.d("***", "despues de crear setSSLSocketFactory");
429                               
430                                //input = new BufferedInputStream(httpsConnection.getInputStream());
431                                input = httpsConnection.getInputStream();
432                               
433                                Log.d("***", "despues de crear BufferedInputStream");
434                               
435                                lenghtOfFile = httpsConnection.getContentLength();
436                                Log.d("***", "se acepto la excepcion");
437                               
438                                */
439                               
440                        }else{                 
441                                HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();
442                                input = new BufferedInputStream(httpsConnection.getInputStream());
443                                lenghtOfFile = httpsConnection.getContentLength();
444                        }
445                }
446               
447               
448                // Crear directorio DownloadedFiles donde se almacenan los archivos descargados
449                        // desde un servidor para verificar su firma
450                        downloadedDirFiles = Environment.getExternalStorageDirectory() + "/" +
451                        getResources().getString(R.string.app_name) + "/" +
452                        getResources().getString(R.string.downloaded_dir_files) + "/";                 
453                        prepareDirectory(downloadedDirFiles);
454
455                //int lenghtOfFile = conexion.getContentLength();
456                Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
457
458                //InputStream input = new BufferedInputStream(url.openStream());               
459                //InputStream input = new BufferedInputStream(conexion.getInputStream());
460               
461                //OutputStream output = new FileOutputStream("/mnt/sdcard/TibisayMovil/ExtractedFiles/photo.jpg");
462               
463                //OutputStream output = new FileOutputStream(new File(rootDir+"/midescarga/", "foto.jpg"));
464
465                String urlString = url.toString();
466                String[] values = urlString.split("/");
467               
468                //OutputStream output = new FileOutputStream(new File(downloadedDirFiles, "acta.2.bdoc"));
469                OutputStream output = new FileOutputStream(new File(downloadedDirFiles, values[values.length-1]));
470               
471                byte data[] = new byte[1024];
472
473                long total = 0;
474
475                while ((count = input.read(data)) != -1) {
476                    total += count;
477                    publishProgress(""+(int)((total*100)/lenghtOfFile));
478                    output.write(data, 0, count);
479                }
480
481                output.flush();
482                               
483                output.close();
484                input.close();
485               
486                resultArray.add("0");
487                //resultArray.add(output.toString());
488                resultArray.add(downloadedDirFiles+values[values.length-1]);
489 
490            } catch (Exception e) {
491               
492                Log.e("Error: ", e.getMessage());
493                outputString = e.getMessage();
494               
495                resultArray.add("1");
496                resultArray.add(e.toString());
497               
498            }
499
500            //return null;
501            return resultArray;
502           
503        }
504       
505        protected void onProgressUpdate(String... progress) {
506            Log.d("ANDRO_ASYNC",progress[0]);
507            mProgressDialog.setProgress(Integer.parseInt(progress[0]));
508       }
509
510       @Override
511       protected void onPostExecute(ArrayList<String> result) {
512           dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
513           //Toast.makeText(getApplicationContext(), "onPostExecute: "+ result.get(0), Toast.LENGTH_LONG).show();
514           
515           // ocurrio una excepcion
516           if (result.get(0).equals("1")){
517               
518                   //Toast.makeText(getApplicationContext(), "onPostExecute: dentro del if" , Toast.LENGTH_LONG).show();
519               
520                        // ocurrio un problema
521                        AlertDialog.Builder builder = new AlertDialog.Builder(DownloaderActivity.this);
522                       
523                        String exception = "";
524                        boolean fileFound = true;
525                       
526                        if (result.get(1).contains("Trust anchor for certification path not found")){
527                                exception = "Intenta descargar un archivo de un servidor con certificado no confiable. ¿Desea continuar?.";
528                               
529                        }
530                        if (result.get(1).contains("java.io.FileNotFoundException")){
531                                String [] v = result.get(1).split("/");
532                                int length = v.length;
533                               
534                                exception = "No se encontró el archivo "+ v[length-1] +" en el servidor.";
535                                fileFound = false;                             
536                        }
537                       
538                        builder.setMessage(exception).setTitle("Error al descargar el archivo");
539                       
540                        if (fileFound){
541                       
542                                builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
543                        public void onClick(DialogInterface dialog, int id) {
544                            // User clicked OK button
545                   
546                                Log.d("***", "DownloadFileAsync().execute(urlhttps, true)");
547                                //Toast.makeText(getApplicationContext(), "DownloadFileAsync().execute("+urlhttps+", true)", Toast.LENGTH_LONG).show();
548                                // pasar como segundo argmento que se acepta que el sertivor es desconocido
549                                new DownloadFileAsync().execute(urlhttps, "true");
550                        }
551                                });
552                               
553                        }
554                       
555                        builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
556                   public void onClick(DialogInterface dialog, int id) {
557                       // User cancelled the dialog
558                           DownloaderActivity.this.finish();
559                   }
560                        });
561                        AlertDialog dialog = builder.create();
562                        dialog.show();
563
564           }else{
565                   // no ocurrió excepcion
566                   //Toast.makeText(getApplicationContext(), "Se descargo correctamente el archivo", Toast.LENGTH_LONG).show();
567                   
568                   //Toast.makeText(getApplicationContext(), "result.get(0): "+result.get(0), Toast.LENGTH_LONG).show();
569                   //Toast.makeText(getApplicationContext(), "result.get(1): "+result.get(1), Toast.LENGTH_LONG).show();
570                   //Toast.makeText(getApplicationContext(), "downloadedDirFiles: "+downloadedDirFiles, Toast.LENGTH_LONG).show();
571                   
572                   // lanzar activity para mostrar resultados de verificacion
573                           Intent intent = new Intent(DownloaderActivity.this, BDOCVerifyResultActivity.class);
574                           intent.putExtra("fileToVerify", result.get(1));
575                           //Toast.makeText(getApplicationContext(), "putExtra1: "+result.get(1), Toast.LENGTH_LONG).show();
576                               
577                           File f = new File(result.get(1));
578                           Uri selectedUri = Uri.fromFile(f);
579                           String fileExtension = MimeTypeMap.getFileExtensionFromUrl(selectedUri.toString());
580                           intent.putExtra("fileExtension", fileExtension);
581                           
582                           //Toast.makeText(getApplicationContext(), "putExtra2: "+fileExtension, Toast.LENGTH_LONG).show();
583                           
584                           startActivity(intent);   
585                           
586                           DownloaderActivity.this.finish();
587           }
588           
589                 
590       }
591       
592
593       
594
595               
596       
597        } // fin de la clase DownloadFileAsync
598   
599
600} // fin de DownloaderActivity
Note: See TracBrowser for help on using the repository browser.