source: dispositivos_moviles/TibisayMovil/src/ve/gob/cenditel/tibisaymovil/FileToDecryptActivity.java @ 37c4d43

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

*- Implementada funcionalidad de descifrar un archivo. Agregadas actividades para realizar operación de descifrado y mostrar resultados del archivo descifrado.

  • Property mode set to 100644
File size: 20.1 KB
Line 
1package ve.gob.cenditel.tibisaymovil;
2
3import java.io.File;
4import java.text.SimpleDateFormat;
5import java.util.ArrayList;
6import java.util.Collections;
7import java.util.Date;
8
9import ve.gob.cenditel.tibisaymovil.R;
10import android.app.Activity;
11import android.app.AlertDialog;
12import android.content.DialogInterface;
13import android.content.Intent;
14import android.graphics.drawable.Drawable;
15import android.net.Uri;
16import android.os.Bundle;
17import android.os.Environment;
18import android.util.Log;
19import android.view.LayoutInflater;
20import android.view.View;
21import android.view.ViewGroup;
22import android.view.View.OnClickListener;
23import android.view.Window;
24import android.webkit.MimeTypeMap;
25import android.widget.AdapterView;
26import android.widget.ArrayAdapter;
27import android.widget.BaseAdapter;
28import android.widget.ImageView;
29import android.widget.LinearLayout;
30import android.widget.ListView;
31import android.widget.RadioButton;
32import android.widget.TextView;
33import android.widget.AdapterView.OnItemClickListener;
34import android.widget.Toast;
35
36public class FileToDecryptActivity extends Activity implements OnItemClickListener, OnClickListener {
37
38        private File cwd;
39    private File selected;
40    private FileBrowserView viewHolder;
41    private FileListAdapter listAdapter;
42    private String filterMImeType = "application/*";
43   
44    // cadena que mantiene la ruta del archivo a compartir
45    private String fileToDecrypt = null;
46
47        @Override
48        protected void onCreate(Bundle savedInstanceState) {
49                //Estilando la barra de titulo
50                final boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
51
52                super.onCreate(savedInstanceState);
53               
54                this.viewHolder = new FileBrowserView();       
55
56        if (savedInstanceState != null) {
57                if(savedInstanceState.getString("selected") != null)
58                        this.selected = new File(savedInstanceState.getString("selected"));
59
60            if (this.selected != null) {
61               
62                FileToDecryptActivity.this.updateButton
63                (FileToDecryptActivity.this.viewHolder.accept,true);
64
65            }
66           
67            this.cwd = new File(savedInstanceState.getString("cwd"));
68            this.viewHolder.fileList.setAdapter(this.listAdapter = new FileListAdapter(this.cwd.getAbsolutePath(), filterMImeType));
69           
70        } else {
71            this.selected = null;
72            this.viewHolder.fileList.setAdapter(this.listAdapter = new FileListAdapter());
73        }
74       
75       
76        boolean enabled = false;
77        if (this.selected != null)
78                enabled = this.viewHolder.accept.isEnabled();
79       
80        FileToDecryptActivity.this.updateButton
81        (FileToDecryptActivity.this.viewHolder.accept,enabled);
82       
83        //Estilando Barra de titulo
84                if(customTitleSupported)
85                        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar);
86        }
87
88       
89    /**
90     * Provides the data to be shown in the file browser ListView.
91     *
92     * @author José M. Prieto (jmprieto@emergya.com)
93     */
94    private class FileListAdapter extends BaseAdapter {
95
96        private final ArrayList<File> directories;
97        private final ArrayList<File> files;
98
99        private FileListAdapter() {
100            this("/",filterMImeType);
101        }
102
103        private FileListAdapter(String location) {
104            this(location, "");
105        }
106       
107        private FileListAdapter(String location, String filterMimeType) {
108               
109            directories = new ArrayList<File>();
110            files = new ArrayList<File>();
111           
112            //Obtiene etiqueta que se colocará antes del path que visualizará el usuario
113                String toPathText = FileToDecryptActivity.this.getString(R.string.pathstring)+":   ";
114                //Coloca el texto de la etiqueta en la vista
115                FileToDecryptActivity.this.viewHolder.pathString.setText(toPathText);
116                //Coloca el texto con el path actual
117                FileToDecryptActivity.this.viewHolder.path.setText(location);
118                //Crea un objeto file cwd con la ubicacion dada en location
119            FileToDecryptActivity.this.cwd = new File(location);
120            //Obtiene el directorio padre del objeto file cwd
121            File parent = FileToDecryptActivity.this.cwd.getParentFile();
122            //Si tiene un padre, lo agrega en la posición cero de la lista de directorios 
123           
124            if (parent != null) {
125                directories.add(0, parent);
126            }
127           
128            //Crea un arreglo con las lista de archivos contenidos en el directorio cwd
129            File[] ls = FileToDecryptActivity.this.cwd.listFiles();
130            if (ls != null) {
131                for (File f : ls) { //recorre todos los archivos contenidos en el directorio
132                       
133                    if (FsUtils.isHiddenOrNotReadable(f)) { // Si son ocultos no hace nada
134                        continue;
135                    }
136                  // Si son directorios los agrega a la lista de directorios a partir de la posición 1
137                  // En la posición 0 se encuentra el directorio padre 
138                    if (f.isDirectory()) {
139                        directories.add(f);
140                    } else // De lo contrario lo agrega a la lista de archivos
141                        {
142                        //Valida tipo de archivo a mostrar
143                        Uri selectedUri = Uri.fromFile(f);
144                        String fileExtension = MimeTypeMap.getFileExtensionFromUrl(selectedUri.toString());
145                        String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
146                         
147//                          Toast.makeText(FileToDecryptActivity.this,
148//                          "FileExtension: " + fileExtension + "\n" +
149//                          "MimeType: " + mimeType,
150//                          Toast.LENGTH_LONG).show();
151                       
152                                                 
153                        // en principio no filtrar ningun archivo
154                        if(filterMimeType.isEmpty() || filterMimeType == mimeType || fileExtension.equals("cdoc"))
155                                files.add(f);
156                               
157                    }
158                }
159            }
160
161            Collections.sort(directories); // Ordena los directorios alfabeticamente
162            Collections.sort(files); // Ordena los archivos alfabeticamente
163        }
164       
165        /**
166         * Retorna cantidad total de elementos que se listarán en el directorio.
167         */
168        @Override 
169        public int getCount() {
170               
171            return directories.size() + files.size();
172           
173        }
174
175        /**
176         * Dada una posición en el listado del directorio, retorna un archivo o directorio
177         * según corresponda.
178         */
179        @Override
180        public File getItem(int position) {
181
182            if (position < directories.size()) {
183                return directories.get(position);
184            } else {
185                return files.get(position - directories.size());
186            }
187        }
188
189        /**
190         * Retorna un código hash para el archivo, permite comparar si dos archivos son los mismos
191         */
192        @Override
193        public long getItemId(int position) {
194
195            return getItem(position).hashCode();
196        }
197       
198        /**
199         * Crea la visualización de cada item del fileBrowser
200         */
201        @Override
202        public View getView(int position, View convertView, ViewGroup parent) {
203
204                //Crea la vista de cada fila del filebrowser a partir del layout
205            if (convertView == null) {
206                LayoutInflater inflater = LayoutInflater.from(FileToDecryptActivity.this);
207                convertView = inflater.inflate(R.layout.file_to_verify_bdoc_signature_item, parent, false); 
208            }
209           
210            // Se enlaza a cada componente del layout
211            ImageView image = (ImageView) convertView.findViewById(R.id.type_image);
212            TextView fileName = (TextView) convertView.findViewById(R.id.filename_text);
213            TextView modified = (TextView) convertView.findViewById(R.id.filename_modified);
214           
215            // Se obtiene el archivo ubicado en position
216                File file = getItem(position);
217               
218                //RadioButton
219            RadioButton radio = (RadioButton) convertView.findViewById(R.id.file_radio);
220            radio.setFocusable(false);
221           
222            // Se asignan los iconos según el tipo de archivo y se oculta el radio en los directorios
223            if (file.isDirectory()) {
224                image.setImageResource(R.drawable.ic_carpeta);
225                radio.setVisibility(View.INVISIBLE);
226                radio.setChecked(false);
227            } else {
228                image.setImageResource(R.drawable.ic_archivo);
229                radio.setVisibility(View.VISIBLE);
230               
231                if (FileToDecryptActivity.this.selected == null ||
232                        FileToDecryptActivity.this.selected.hashCode() != file.hashCode()){
233                                radio.setChecked(false);
234                } else{
235                        radio.setChecked(true);
236                }         
237            }
238
239            // Si es el directorio que hace referencia al padre le coloca como nombre ".."
240            if (file.isDirectory() && position == 0 && ! "/".equals(FileToDecryptActivity.this.cwd.getAbsolutePath())) {
241                fileName.setText("..");
242            } else {
243                fileName.setText(file.getName());
244            }
245 
246           
247            //Datos de modificación del archivo
248            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
249            Date date = new Date(file.lastModified());
250           
251            String dateString = FileToDecryptActivity.this.getString(R.string.modified)+": ";
252            if (file.lastModified()>0)
253                modified.setText(dateString+sdf.format(date));
254            else
255                modified.setText(dateString+"-");
256           
257            return convertView;
258        }
259       
260        /**
261         * Controla la selección de cada item del fileBrowser
262         */
263        public void select(ListView parent, int position) {
264
265            File item = getItem(position);
266            //Si es un directorio el seleccionado se hace un llamado del fileBrowser del directorio
267            if (item.isDirectory()) {
268                parent.setAdapter(FileToDecryptActivity.this.listAdapter = new FileListAdapter(item.getAbsolutePath(), filterMImeType));
269            } else { // Si es un archivo
270               
271                        //Se agrega el archivo a la lista de seleccionados si no se encuentra en la misma               
272                if (FileToDecryptActivity.this.selected == null || 
273                        FileToDecryptActivity.this.selected.hashCode() != item.hashCode()){
274                       
275                        FileToDecryptActivity.this.selected = item;
276                       
277                        FileToDecryptActivity.this.updateButton(FileToDecryptActivity.this.viewHolder.accept,true);             
278                                               
279                }
280                else{ // De lo contrario se elimina de la lista de seleccionados
281                       
282                        FileToDecryptActivity.this.selected = null;                             
283                        FileToDecryptActivity.this.updateButton(FileToDecryptActivity.this.viewHolder.accept,false);
284                                       
285                }
286                notifyDataSetChanged();
287           }
288        }       
289    }   
290
291
292   
293   
294    @Override
295    protected void onSaveInstanceState(Bundle outState) {
296        super.onSaveInstanceState(outState);
297
298        outState.putParcelable("intent", this.getIntent());
299        outState.putString("cwd", this.cwd.getAbsolutePath());
300        if(this.selected != null)
301                outState.putString("selected", this.selected.getAbsolutePath());
302       
303        }
304   
305    private void updateButton(View v, boolean bool) {
306        try{
307
308                v.setEnabled(bool);
309                if (v instanceof TextView){
310                        Drawable icon = ((TextView)v).getCompoundDrawables()[1];
311                        if (icon!=null)
312                        if (bool)
313                                icon.setAlpha(255);
314                        else
315                                icon.setAlpha(127);     
316                }
317                if (v instanceof ImageView){
318                        ImageView result = (ImageView) v;
319                        if (bool)
320                                result.setAlpha(255);
321                        else
322                                result.setAlpha(127);   
323                }
324       
325        }catch(NullPointerException e){}
326                       
327        }
328   
329    private void updateButton(LinearLayout layout, boolean bool) {
330        try{
331        layout.setEnabled(bool);
332        for (int i=0; i<layout.getChildCount();i++){
333                this.updateButton(layout.getChildAt(i), bool);
334        }
335        }catch(NullPointerException e){}
336                       
337        }
338
339       
340       
341        /**
342     * Holds references to view objects.
343     *
344     * @author José M. Prieto (jmprieto@emergya.com)
345     */
346    private class FileBrowserView {
347
348        public ListView fileList;
349        public TextView path;
350        public LinearLayout accept;
351                public LinearLayout clear;
352        public TextView pathString;
353
354        public FileBrowserView() {
355
356            setContentView(R.layout.activity_file_to_decrypt);
357            this.path = (TextView) findViewById(R.id.path);
358            this.pathString = (TextView) findViewById(R.id.pathstring);
359
360            this.fileList = (ListView) findViewById(R.id.file_list);
361            this.fileList.setOnItemClickListener(FileToDecryptActivity.this);
362            this.fileList.setItemsCanFocus(true);
363         
364           
365            this.clear = (LinearLayout) findViewById(R.id.button_clear_zone);
366            this.clear.setOnClickListener(FileToDecryptActivity.this);
367           
368            this.accept = (LinearLayout) findViewById(R.id.button_accept_zone);
369            this.accept.setOnClickListener(FileToDecryptActivity.this);
370
371        }
372    }
373   
374        @Override
375    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
376       
377       
378        if (parent.getId() == R.id.file_list) { // user selects a file
379            this.listAdapter.select((ListView) parent, position);
380           
381        } else { // user de-selects a file
382            //this.listAdapter.addIfSameDirectory(selectedAdapter.doUnselect((ListView) parent, position));
383               
384        }
385        //this.viewHolder.numSelected.setText(Integer.toString(this.selected.size()));
386    }
387
388    @Override
389    public void onClick(View v) {
390
391        switch (v.getId()) {
392
393       
394        case R.id.button_clear_zone:
395               
396                this.selected = null;
397                this.listAdapter.notifyDataSetChanged();
398
399                //this.viewHolder.numSelected.setText(""+this.selected.size());
400            this.updateButton(this.viewHolder.accept, false);
401                break;         
402       
403
404       
405            case R.id.button_accept_zone:
406               
407                // lanzar intent para compartir el archivo seleccionado
408                fileToDecrypt = FileToDecryptActivity.this.selected.getAbsolutePath();
409               
410                Toast.makeText(getApplicationContext(), "FileToDecryptActivity: "+fileToDecrypt, Toast.LENGTH_SHORT).show();
411               
412                               
413               
414                selectPKCS12ToDecrypt(fileToDecrypt);
415                                                       
416                break;         
417       
418        }
419    }
420   
421       
422        // funcion para compartir el archivo
423        private void shareIt() {
424               
425                Intent shareIntent = new Intent();
426                shareIntent.setAction(Intent.ACTION_SEND);
427                File file = new File(fileToDecrypt);
428               
429               
430                Uri uri = Uri.fromFile(file);
431                Log.i("DEBUG", file.getPath());
432                //Log.d("******", getMimeType(file.getPath()));
433                //shareIntent.setDataAndType(uri, getMimeType(file.getPath()));
434                shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
435                shareIntent.setType("application/*");
436                startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share_it_using)));
437        }
438       
439       
440        /**
441     * Selecciona el certificado del destinatario del directorio de certificados
442     * para cifrado
443     * @return void
444     */
445        // funcion para desplegar el gestor de certificados de destinatarios para cifrar
446        private void selectPKCS12ToDecrypt(String fileToDecrypt) {
447               
448                // desplegar la actividad de gestor de certificados de destinatarios
449
450                // chequear disponibilidad de directorio de certificados
451            if (!checkDecryptedDirectoryAvailability()){
452                Toast.makeText(getApplicationContext(), "FileToDecryptActivity: directorio no disponible", Toast.LENGTH_SHORT).show();
453               
454                finish();
455                return;
456            }else{
457                // lanzar el activity SelectCeritificateToEncryptActivity
458                Intent intent = new Intent(this, PKCS12ToDecryptActivity.class);               
459                        intent.putExtra("fileToDecrypt", fileToDecrypt);
460                        startActivity(intent);
461
462            }
463               
464               
465               
466               
467               
468        } // fin de selectPKCS12ToDecrypt()
469       
470        /**
471     * Chequea la disponibilidad del directorio de /TibisayMovil/CertificatesToEncrypt
472     * @return boolean
473     */
474    private boolean checkDecryptedDirectoryAvailability() {
475        // verificar acceso al directorio /mnt/sdcard/TibisayMovil/DecryptedFiles
476            boolean mExternalStorageAvailable = false;
477            boolean mExternalStorageWriteable = false;
478            String state = Environment.getExternalStorageState();
479           
480            String decryptedDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
481                        getResources().getString(R.string.app_name) + "/" +
482                        getResources().getString(R.string.decrypted_dir_files) + "/";
483           
484                AlertDialog.Builder builder = new AlertDialog.Builder(FileToDecryptActivity.this);
485               
486           
487            if (Environment.MEDIA_MOUNTED.equals(state)) {
488                // We can read and write the media
489                mExternalStorageAvailable = mExternalStorageWriteable = true;
490                Toast.makeText(getApplicationContext(), "We can read and write the media", Toast.LENGTH_SHORT).show();
491               
492                // Crear directorio CertificatesToEncrypt donde se almacenan los certificados de
493                // destinatarios para cifrado
494                /*
495                        String decryptedDir = Environment.getExternalStorageDirectory() + "/" +
496                        getResources().getString(R.string.app_name) + "/" +
497                        getResources().getString(R.string.certificates_dir) + "/";
498                        */                     
499                        if (prepareDirectory(decryptedDir)){                           
500                                return true;
501                        }else{
502                                builder.setMessage("No existe el directorio "+decryptedDir+" para almacenar certificados.").setTitle("Error:");
503               
504                        }
505                       
506            } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
507                // We can only read the media
508                mExternalStorageAvailable = true;
509                mExternalStorageWriteable = false;
510                Toast.makeText(getApplicationContext(), "We can only read the media", Toast.LENGTH_SHORT).show();
511               
512                builder.setMessage("Directorio "+decryptedDir+ " montado de solo lectura. No se pueden almancenar certificados.").setTitle("Error:");
513       
514               
515            } else {
516                // Something else is wrong. It may be one of many other states, but all we need
517                //  to know is we can neither read nor write
518                mExternalStorageAvailable = mExternalStorageWriteable = false;
519                Toast.makeText(getApplicationContext(), "we can neither read nor write", Toast.LENGTH_SHORT).show();
520               
521                builder.setMessage("Directorio "+decryptedDir+ " no está disponible. No se pueden almancenar certificados.").setTitle("Error:");               
522       
523            }
524           
525           
526        builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
527                public void onClick(DialogInterface dialog, int id) {
528               // User cancelled the dialog
529                        FileToDecryptActivity.this.finish();
530            }
531        });
532            AlertDialog dialog = builder.create();
533            dialog.show();
534            return false;
535    } // fin de checkdecryptedDirectoryAvailability
536       
537   
538    /**
539     * Prepara directorio
540     * @return boolean
541     */
542    boolean prepareDirectory(String dir) 
543    {
544        try
545        {
546            if (makedirs(dir)) 
547            {
548                return true;
549            } else {
550                return false;
551            }
552        } catch (Exception e) 
553        {
554            e.printStackTrace();
555            Toast.makeText(this, "Could not initiate File System.. Is Sdcard mounted properly?", Toast.LENGTH_LONG).show();
556            return false;
557        }
558    }
559   
560    /**
561     * Crea directorio utilizando la variable tmpDir
562     * @return boolean
563     */
564    private boolean makedirs(String dir) 
565    {
566        //File tempdir = new File(extractedDirFiles);
567        File tempdir = new File(dir);
568        if (!tempdir.exists())
569            tempdir.mkdirs();
570        return (tempdir.isDirectory());
571    }
572   
573   
574}
575
Note: See TracBrowser for help on using the repository browser.