source: dispositivos_moviles/TibisayMovil/src/ve/gob/cenditel/tibisaymovil/SelectCertificateToEncryptActivity.java @ ae1bcd1

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

*- Implementada funcionalidad de cifrar un archivo. Se selecciona un archivo del sistema de archivos, se selecciona un cerficado de destinatario del repositorio de certificados y se cifra el archivo. El archivo resultante se puede compartir a través de distintas aplicaciones y se almacena en el directorio de archivos cifrados.

*- Se crearon nuevas actividades: FileToEncryptActivity? para seleccionar el archivo a cifrar, SelectCertificateToEncryptActivity? para seleccionar el certificado del destinatario y EncryptionResultActivity? para desplegar resultados del cifrado.

  • Property mode set to 100644
File size: 28.9 KB
Line 
1package ve.gob.cenditel.tibisaymovil;
2
3import java.io.File;
4import java.io.FileOutputStream;
5import java.security.cert.X509Certificate;
6import java.text.SimpleDateFormat;
7import java.util.ArrayList;
8import java.util.Collections;
9import java.util.Date;
10
11import ee.sk.digidoc.DataFile;
12import ee.sk.digidoc.SignedDoc;
13import ee.sk.utils.ConfigManager;
14import ee.sk.xmlenc.EncryptedData;
15import ee.sk.xmlenc.EncryptedKey;
16
17import ve.gob.cenditel.tibisaymovil.R;
18import android.app.Activity;
19import android.app.AlertDialog;
20import android.content.Context;
21import android.content.DialogInterface;
22import android.content.Intent;
23import android.graphics.drawable.Drawable;
24import android.net.Uri;
25import android.os.Bundle;
26import android.os.Environment;
27import android.util.Log;
28import android.view.LayoutInflater;
29import android.view.View;
30import android.view.ViewGroup;
31import android.view.View.OnClickListener;
32import android.view.Window;
33import android.webkit.MimeTypeMap;
34import android.widget.AdapterView;
35import android.widget.ArrayAdapter;
36import android.widget.BaseAdapter;
37import android.widget.ImageView;
38import android.widget.LinearLayout;
39import android.widget.ListView;
40import android.widget.RadioButton;
41import android.widget.TextView;
42import android.widget.AdapterView.OnItemClickListener;
43import android.widget.Toast;
44
45public class SelectCertificateToEncryptActivity extends Activity implements OnItemClickListener, OnClickListener {
46
47        private File cwd;
48    private File selected;
49    private FileBrowserView viewHolder;
50    private FileListAdapter listAdapter;
51    private String filterMImeType = "application/x-pem-file";
52   
53    // cadena que mantiene la ruta del archivo a compartir
54    private String fileToEncrypt = null;
55
56    // cadena que mantiene la ruta del certificado del destinatario
57    private String certificateToEncrypt = null;
58
59    // cadena que mantiene la ruta del directorio de certificados
60    String certificateDirFiles = null;
61   
62    // cadena que mantiene la ruta del directorio archivos cifrados
63    String encrypted_dir_files = null;
64   
65   
66        @Override
67        protected void onCreate(Bundle savedInstanceState) {
68                //Estilando la barra de titulo
69                final boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
70
71                super.onCreate(savedInstanceState);
72               
73                this.viewHolder = new FileBrowserView();       
74
75               
76        // obtener la ruta del archivo que se va a cifrar           
77        Bundle bundle = getIntent().getExtras();
78        fileToEncrypt = bundle.getString("fileToEncrypt");
79
80               
81        if (savedInstanceState != null) {
82                if(savedInstanceState.getString("selected") != null)
83                        this.selected = new File(savedInstanceState.getString("selected"));
84
85            if (this.selected != null) {
86               
87                SelectCertificateToEncryptActivity.this.updateButton
88                (SelectCertificateToEncryptActivity.this.viewHolder.accept,true);
89
90            }
91           
92            this.cwd = new File(savedInstanceState.getString("cwd"));
93            this.viewHolder.fileList.setAdapter(this.listAdapter = new FileListAdapter(this.cwd.getAbsolutePath(), filterMImeType));
94           
95        } else {
96            this.selected = null;
97            //this.viewHolder.fileList.setAdapter(this.listAdapter = new FileListAdapter());
98           
99           
100            certificateDirFiles = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
101                        getResources().getString(R.string.app_name) + "/" +
102                        getResources().getString(R.string.certificates_dir) + "/";
103                       
104                        this.viewHolder.fileList.setAdapter(this.listAdapter = new FileListAdapter(certificateDirFiles, filterMImeType));
105                       
106                       
107                        encrypted_dir_files = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
108                        getResources().getString(R.string.app_name) + "/" +
109                        getResources().getString(R.string.encrypted_dir_files) + "/";
110        }
111       
112       
113        boolean enabled = false;
114        if (this.selected != null)
115                enabled = this.viewHolder.accept.isEnabled();
116       
117        SelectCertificateToEncryptActivity.this.updateButton
118        (SelectCertificateToEncryptActivity.this.viewHolder.accept,enabled);
119       
120        //Estilando Barra de titulo
121                if(customTitleSupported)
122                        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar);
123        }
124
125       
126    /**
127     * Provides the data to be shown in the file browser ListView.
128     *
129     * @author José M. Prieto (jmprieto@emergya.com)
130     */
131    private class FileListAdapter extends BaseAdapter {
132
133        private final ArrayList<File> directories;
134        private final ArrayList<File> files;
135
136        private FileListAdapter() {
137            this("/",filterMImeType);
138        }
139
140        private FileListAdapter(String location) {
141            this(location, "");
142        }
143       
144        private FileListAdapter(String location, String filterMimeType) {
145                Log.d("***location", location);
146                Log.d("***filterMimeType", filterMimeType);
147               
148            directories = new ArrayList<File>();
149            files = new ArrayList<File>();
150           
151            //Obtiene etiqueta que se colocará antes del path que visualizará el usuario
152                String toPathText = SelectCertificateToEncryptActivity.this.getString(R.string.pathstring)+":   ";
153                //Coloca el texto de la etiqueta en la vista
154                SelectCertificateToEncryptActivity.this.viewHolder.pathString.setText(toPathText);
155                //Coloca el texto con el path actual
156                SelectCertificateToEncryptActivity.this.viewHolder.path.setText(location);
157                //Crea un objeto file cwd con la ubicacion dada en location
158            SelectCertificateToEncryptActivity.this.cwd = new File(location);
159            //Obtiene el directorio padre del objeto file cwd
160            File parent = SelectCertificateToEncryptActivity.this.cwd.getParentFile();
161            //Si tiene un padre, lo agrega en la posición cero de la lista de directorios 
162           
163            if (parent != null) {
164                directories.add(0, parent);
165                Log.d("***", "directories.add(0, parent)");
166                Log.d("***", parent.getAbsolutePath());
167            }
168           
169            Log.d("***cwd", SelectCertificateToEncryptActivity.this.cwd.getAbsolutePath());
170           
171            //Crea un arreglo con las lista de archivos contenidos en el directorio cwd
172            File[] ls = SelectCertificateToEncryptActivity.this.cwd.listFiles();
173            if (ls != null) {
174               
175                Log.d("***", "ls != null");
176                for (File f : ls) { //recorre todos los archivos contenidos en el directorio
177                       
178                    if (FsUtils.isHiddenOrNotReadable(f)) { // Si son ocultos no hace nada
179                        Log.d("***", "archivo oculto o no legible");
180                        continue;
181                    }
182                  // Si son directorios los agrega a la lista de directorios a partir de la posición 1
183                  // En la posición 0 se encuentra el directorio padre 
184                    if (f.isDirectory()) {
185                        directories.add(f);
186                        Log.d("***", "directories.add(f)");
187                    } else // De lo contrario lo agrega a la lista de archivos
188                        {
189                        Log.d("***", "agregar archivo a la lista");
190                        //Valida tipo de archivo a mostrar
191                        Uri selectedUri = Uri.fromFile(f);
192                        String fileExtension = MimeTypeMap.getFileExtensionFromUrl(selectedUri.toString());
193                        String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
194                         
195                          //Toast.makeText(SelectCertificateToEncryptActivity.this,
196                          //"FileExtension: " + fileExtension + "\n" +
197                          //"MimeType: " + mimeType,
198                          //Toast.LENGTH_LONG).show();
199                       
200                                                 
201                      //Filtra por mimeType: se consideran los .pem .crt .cer
202                        //if(filterMimeType.isEmpty() || /*filterMimeType == mimeType*/ fileExtension.equals("pem")
203                        if(fileExtension.equals("pem") || fileExtension.equals("crt") || fileExtension.equals("cer"))                       
204                            files.add(f);
205                               
206                    }
207                }
208            }else{
209                Log.d("***", "ls == null");
210            }
211
212            Collections.sort(directories); // Ordena los directorios alfabeticamente
213            Collections.sort(files); // Ordena los archivos alfabeticamente
214        }
215       
216        /**
217         * Retorna cantidad total de elementos que se listarán en el directorio.
218         */
219        @Override 
220        public int getCount() {
221               
222            return directories.size() + files.size();
223           
224        }
225
226        /**
227         * Dada una posición en el listado del directorio, retorna un archivo o directorio
228         * según corresponda.
229         */
230        @Override
231        public File getItem(int position) {
232
233            if (position < directories.size()) {
234                return directories.get(position);
235            } else {
236                return files.get(position - directories.size());
237            }
238        }
239
240        /**
241         * Retorna un código hash para el archivo, permite comparar si dos archivos son los mismos
242         */
243        @Override
244        public long getItemId(int position) {
245
246            return getItem(position).hashCode();
247        }
248       
249        /**
250         * Crea la visualización de cada item del fileBrowser
251         */
252        @Override
253        public View getView(int position, View convertView, ViewGroup parent) {
254
255                //Crea la vista de cada fila del filebrowser a partir del layout
256            if (convertView == null) {
257                LayoutInflater inflater = LayoutInflater.from(SelectCertificateToEncryptActivity.this);
258                convertView = inflater.inflate(R.layout.file_to_verify_bdoc_signature_item, parent, false); 
259            }
260           
261            // Se enlaza a cada componente del layout
262            ImageView image = (ImageView) convertView.findViewById(R.id.type_image);
263            TextView fileName = (TextView) convertView.findViewById(R.id.filename_text);
264            TextView modified = (TextView) convertView.findViewById(R.id.filename_modified);
265           
266            // Se obtiene el archivo ubicado en position
267                File file = getItem(position);
268               
269                //RadioButton
270            RadioButton radio = (RadioButton) convertView.findViewById(R.id.file_radio);
271            radio.setFocusable(false);
272           
273            // Se asignan los iconos según el tipo de archivo y se oculta el radio en los directorios
274            if (file.isDirectory()) {
275                image.setImageResource(R.drawable.ic_carpeta);
276                radio.setVisibility(View.INVISIBLE);
277                radio.setChecked(false);
278            } else {
279                image.setImageResource(R.drawable.ic_archivo);
280                radio.setVisibility(View.VISIBLE);
281               
282                if (SelectCertificateToEncryptActivity.this.selected == null ||
283                        SelectCertificateToEncryptActivity.this.selected.hashCode() != file.hashCode()){
284                                radio.setChecked(false);
285                } else{
286                        radio.setChecked(true);
287                }         
288            }
289
290            // Si es el directorio que hace referencia al padre le coloca como nombre ".."
291            if (file.isDirectory() && position == 0 && ! "/".equals(SelectCertificateToEncryptActivity.this.cwd.getAbsolutePath())) {
292                fileName.setText("..");
293            } else {
294                fileName.setText(file.getName());
295            }
296 
297           
298            //Datos de modificación del archivo
299            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
300            Date date = new Date(file.lastModified());
301           
302            String dateString = SelectCertificateToEncryptActivity.this.getString(R.string.modified)+": ";
303            if (file.lastModified()>0)
304                modified.setText(dateString+sdf.format(date));
305            else
306                modified.setText(dateString+"-");
307           
308            return convertView;
309        }
310       
311        /**
312         * Controla la selección de cada item del fileBrowser
313         */
314        public void select(ListView parent, int position) {
315
316            File item = getItem(position);
317            //Si es un directorio el seleccionado se hace un llamado del fileBrowser del directorio
318            if (item.isDirectory()) {
319                parent.setAdapter(SelectCertificateToEncryptActivity.this.listAdapter = new FileListAdapter(item.getAbsolutePath(), filterMImeType));
320            } else { // Si es un archivo
321               
322                        //Se agrega el archivo a la lista de seleccionados si no se encuentra en la misma               
323                if (SelectCertificateToEncryptActivity.this.selected == null || 
324                        SelectCertificateToEncryptActivity.this.selected.hashCode() != item.hashCode()){
325                       
326                        SelectCertificateToEncryptActivity.this.selected = item;
327                       
328                        SelectCertificateToEncryptActivity.this.updateButton(SelectCertificateToEncryptActivity.this.viewHolder.accept,true);           
329                                               
330                }
331                else{ // De lo contrario se elimina de la lista de seleccionados
332                       
333                        SelectCertificateToEncryptActivity.this.selected = null;                       
334                        SelectCertificateToEncryptActivity.this.updateButton(SelectCertificateToEncryptActivity.this.viewHolder.accept,false);
335                                       
336                }
337                notifyDataSetChanged();
338           }
339        }       
340    }   
341
342
343   
344   
345    @Override
346    protected void onSaveInstanceState(Bundle outState) {
347        super.onSaveInstanceState(outState);
348
349        outState.putParcelable("intent", this.getIntent());
350        outState.putString("cwd", this.cwd.getAbsolutePath());
351        if(this.selected != null)
352                outState.putString("selected", this.selected.getAbsolutePath());
353       
354        }
355   
356    private void updateButton(View v, boolean bool) {
357        try{
358
359                v.setEnabled(bool);
360                if (v instanceof TextView){
361                        Drawable icon = ((TextView)v).getCompoundDrawables()[1];
362                        if (icon!=null)
363                        if (bool)
364                                icon.setAlpha(255);
365                        else
366                                icon.setAlpha(127);     
367                }
368                if (v instanceof ImageView){
369                        ImageView result = (ImageView) v;
370                        if (bool)
371                                result.setAlpha(255);
372                        else
373                                result.setAlpha(127);   
374                }
375       
376        }catch(NullPointerException e){}
377                       
378        }
379   
380    private void updateButton(LinearLayout layout, boolean bool) {
381        try{
382        layout.setEnabled(bool);
383        for (int i=0; i<layout.getChildCount();i++){
384                this.updateButton(layout.getChildAt(i), bool);
385        }
386        }catch(NullPointerException e){}
387                       
388        }
389
390       
391       
392        /**
393     * Holds references to view objects.
394     *
395     * @author José M. Prieto (jmprieto@emergya.com)
396     */
397    private class FileBrowserView {
398
399        public ListView fileList;
400        public TextView path;
401        public LinearLayout accept;
402                public LinearLayout clear;
403        public TextView pathString;
404
405        public FileBrowserView() {
406
407            setContentView(R.layout.activity_select_certificate_to_encrypt);
408            this.path = (TextView) findViewById(R.id.path);
409            this.pathString = (TextView) findViewById(R.id.pathstring);
410
411            this.fileList = (ListView) findViewById(R.id.file_list);
412            this.fileList.setOnItemClickListener(SelectCertificateToEncryptActivity.this);
413            this.fileList.setItemsCanFocus(true);
414         
415           
416            this.clear = (LinearLayout) findViewById(R.id.button_clear_zone);
417            this.clear.setOnClickListener(SelectCertificateToEncryptActivity.this);
418           
419            this.accept = (LinearLayout) findViewById(R.id.button_accept_zone);
420            this.accept.setOnClickListener(SelectCertificateToEncryptActivity.this);
421
422        }
423    }
424   
425        @Override
426    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
427       
428       
429        if (parent.getId() == R.id.file_list) { // user selects a file
430            this.listAdapter.select((ListView) parent, position);
431           
432        } else { // user de-selects a file
433            //this.listAdapter.addIfSameDirectory(selectedAdapter.doUnselect((ListView) parent, position));
434               
435        }
436        //this.viewHolder.numSelected.setText(Integer.toString(this.selected.size()));
437    }
438
439    @Override
440    public void onClick(View v) {
441
442        switch (v.getId()) {
443
444       
445        case R.id.button_clear_zone:
446               
447                this.selected = null;
448                this.listAdapter.notifyDataSetChanged();
449
450                //this.viewHolder.numSelected.setText(""+this.selected.size());
451            this.updateButton(this.viewHolder.accept, false);
452                break;         
453       
454
455       
456            case R.id.button_accept_zone:
457               
458                // lanzar intent para compartir el archivo seleccionado
459                //fileToEncrypt = SelectCertificateToEncryptActivity.this.selected.getAbsolutePath();
460                certificateToEncrypt = SelectCertificateToEncryptActivity.this.selected.getAbsolutePath();
461               
462                Toast.makeText(getApplicationContext(), "SelectCertificateToEncryptActivity: "+certificateToEncrypt, Toast.LENGTH_SHORT).show();
463               
464               
465                encryptFile(fileToEncrypt, certificateToEncrypt);
466                                                       
467                break;         
468       
469        }
470    }
471   
472       
473        // funcion para compartir el archivo
474        private void shareIt() {
475               
476                Intent shareIntent = new Intent();
477                shareIntent.setAction(Intent.ACTION_SEND);
478                File file = new File(fileToEncrypt);
479               
480               
481                Uri uri = Uri.fromFile(file);
482                Log.i("DEBUG", file.getPath());
483                //Log.d("******", getMimeType(file.getPath()));
484                //shareIntent.setDataAndType(uri, getMimeType(file.getPath()));
485                shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
486                shareIntent.setType("application/*");
487                startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share_it_using)));
488        }
489       
490       
491        /**
492     * Cifra el archivo pasado como argumento
493     *
494     * @return void
495     */
496        // funcion para desplegar el gestor de certificados de destinatarios para cifrar
497        private void encryptFile(String fileToEncrypt, String certificateToEncrypt) {
498               
499                Toast.makeText(getApplicationContext(), "Encrypting file: " + fileToEncrypt, Toast.LENGTH_SHORT).show();
500       
501                // TODO chequear que se pueda escribir en el directorio /mnt/sdcard/TibisayMovil/EncryptedFiles
502                // chequear disponibilidad de directorio de certificados
503            if (!checkCertificatesDirectoryAvailability()){
504                Toast.makeText(getApplicationContext(), "SelectCertificateToEncryptActivity: directorio no disponible", Toast.LENGTH_SHORT).show();
505               
506                finish();
507                return;
508            }
509               
510               
511        ConfigManager.init("jar://jdigidoc.cfg");
512                Log.d("despues de:", "ConfigManager.init");
513       
514        /** signed doc object if used */
515        SignedDoc m_sdoc;
516        m_sdoc = null;
517
518        /** encrypted data object if used */
519        EncryptedData m_cdoc;
520        m_cdoc = null;
521       
522        String inFile = null, outFile = null;
523        String certFile = null;
524        String recipient = null;
525        String keyName = null;
526        String carriedKeyName = null;
527        String sId = null;     
528               
529        inFile = fileToEncrypt;
530        certFile = certificateToEncrypt;
531       
532        // agregar el destinatario
533        try {
534
535                if (m_cdoc == null){
536                        Log.d("m_cdoc == null", "-");
537                        m_cdoc = new EncryptedData(null, null, null, EncryptedData.DENC_XMLNS_XMLENC, EncryptedData.DENC_ENC_METHOD_AES128);
538                }
539                Log.d("Adding recipient", certFile);
540                X509Certificate recvCert = SignedDoc.readCertificate(new File(certFile));
541                if (recvCert != null && recipient == null)
542                        recipient = SignedDoc.getCommonName(recvCert.getSubjectDN().getName());
543                Log.d("Recipient", recipient);
544                if (sId == null){
545                        int n = m_cdoc.getNumKeys() + 1;
546                        sId = "ID" + n;
547                       
548                }
549               
550                EncryptedKey ekey = new EncryptedKey(sId, recipient, EncryptedData.DENC_ENC_METHOD_RSA1_5, keyName, carriedKeyName, recvCert);
551                m_cdoc.addEncryptedKey(ekey);
552
553               
554        }catch(Exception e){
555                Log.d("Error adding EncryptedKey: ", e.getMessage());
556                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
557               
558                showDialog("Error:", e.getMessage());
559                return;
560        }
561       
562        // ejecutar el cifrado
563        try {
564
565                Log.d("Encrypting file:", inFile + " to: " + outFile);
566                File fIn = new File(inFile);
567                // create a ddoc intermediate file
568                m_sdoc = new SignedDoc(SignedDoc.FORMAT_DIGIDOC_XML, SignedDoc.VERSION_1_3);
569               
570                Log.d("Encrypting file:", "paso new SignedDoc");
571               
572                DataFile df = m_sdoc.addDataFile(new File(inFile), SignedDoc.xmlns_digidoc13, DataFile.CONTENT_EMBEDDED_BASE64);
573                               
574                Log.d("Encrypting file:", "paso addDataFile");
575               
576               
577                byte[] data = SignedDoc.readFile(new File(inFile));
578               
579                Log.d("Encrypting file:", "paso readFile");
580               
581                df.setBase64Body(data);
582               
583                Log.d("Encrypting file:", "paso setBase64Body");
584               
585                byte[] inData = m_sdoc.toXML().getBytes("UTF-8");
586               
587                Log.d("Encrypting file:", "paso toXML()");
588               
589                Log.d("Encrypting file", "Content: " + inFile + " size: " + data.length);
590                Log.d("Encrypting file", "DF: " + new String(inData));
591               
592                m_cdoc.setData(inData);
593                m_cdoc.setDataStatus(EncryptedData.DENC_DATA_STATUS_UNENCRYPTED_AND_NOT_COMPRESSED);
594                m_cdoc.addProperty(EncryptedData.ENCPROP_FILENAME, inFile + ".ddoc");
595                m_cdoc.setMimeType(EncryptedData.DENC_ENCDATA_TYPE_DDOC);
596                StringBuffer sb = new StringBuffer();
597                sb.append(fIn.getName());
598                sb.append("|");
599                sb.append(new Long(fIn.length()).toString() + " B|");
600                sb.append("application/unknown|");
601                sb.append("/" + fIn.getName());
602                m_cdoc.addProperty(EncryptedData.ENCPROP_ORIG_FILE, sb.toString());
603                //m_cdoc.addProperty(EncryptedData.ENCPROP_ORIG_SIZE, new Long(inData.length).toString());
604               
605                int nCompressOption = 0;
606               
607                m_cdoc.encrypt(nCompressOption);
608                               
609                // genera el archivo cifrado en /data/data/ve.gob.cenditel/files
610                //FileOutputStream fos = openFileOutput(outFile, Context.MODE_WORLD_WRITEABLE);
611               
612                outFile = encrypted_dir_files + fIn.getName()+".cdoc";
613                Toast.makeText(getApplicationContext(), "outFile: " + outFile, Toast.LENGTH_SHORT).show();
614               
615               
616                FileOutputStream fos = new FileOutputStream( outFile );
617               
618                Log.d("Encrypting file", "antes de escribir archivo " + outFile);
619               
620                fos.write(m_cdoc.toXML());
621               
622                Log.d("Encrypting file", "despues de escribir archivo " + outFile);
623               
624                fos.close();
625               
626                Log.d("Encrypting file", "despues de cerrar archivo " + outFile);
627               
628                Toast.makeText(getApplicationContext(), "Cifrado correctamente: " + outFile, Toast.LENGTH_SHORT).show();
629               
630
631        } catch(Exception e) {
632                Log.d("Error encrypting file: ", inFile + " - " + e.getMessage());
633                e.printStackTrace(System.err);
634                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
635               
636                showDialog("Error:", e.getMessage());
637                return;                 
638        }
639               
640        // lanzar la actividad para mostrar el resultado del cifrado
641        showEncryptionResults(fileToEncrypt, outFile, recipient);
642       
643       
644               
645        } // fin de selectRecipientCertificate()
646       
647       
648       
649        /**
650     * Chequea la disponibilidad del directorio de /TibisayMovil/CertificatesToEncrypt
651     * @return boolean
652     */
653    private boolean checkCertificatesDirectoryAvailability() {
654        // verificar acceso al directorio /mnt/sdcard/TibisayMovil/EncryptedFiles
655            boolean mExternalStorageAvailable = false;
656            boolean mExternalStorageWriteable = false;
657            String state = Environment.getExternalStorageState();
658           
659            String certificatesDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
660                        getResources().getString(R.string.app_name) + "/" +
661                        getResources().getString(R.string.encrypted_dir_files) + "/";
662           
663                AlertDialog.Builder builder = new AlertDialog.Builder(SelectCertificateToEncryptActivity.this);
664               
665           
666            if (Environment.MEDIA_MOUNTED.equals(state)) {
667                // We can read and write the media
668                mExternalStorageAvailable = mExternalStorageWriteable = true;
669                Toast.makeText(getApplicationContext(), "We can read and write the media", Toast.LENGTH_SHORT).show();
670               
671                // Crear directorio CertificatesToEncrypt donde se almacenan los certificados de
672                // destinatarios para cifrado
673                /*
674                        String certificatesDir = Environment.getExternalStorageDirectory() + "/" +
675                        getResources().getString(R.string.app_name) + "/" +
676                        getResources().getString(R.string.certificates_dir) + "/";
677                        */                     
678                        if (prepareDirectory(certificatesDir)){                         
679                                return true;
680                        }else{
681                                builder.setMessage("No existe el directorio "+certificatesDir+" para almacenar certificados.").setTitle("Error:");
682               
683                        }
684                       
685            } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
686                // We can only read the media
687                mExternalStorageAvailable = true;
688                mExternalStorageWriteable = false;
689                Toast.makeText(getApplicationContext(), "We can only read the media", Toast.LENGTH_SHORT).show();
690               
691                builder.setMessage("Directorio "+certificatesDir+ " montado de solo lectura. No se pueden almancenar certificados.").setTitle("Error:");
692       
693               
694            } else {
695                // Something else is wrong. It may be one of many other states, but all we need
696                //  to know is we can neither read nor write
697                mExternalStorageAvailable = mExternalStorageWriteable = false;
698                Toast.makeText(getApplicationContext(), "we can neither read nor write", Toast.LENGTH_SHORT).show();
699               
700                builder.setMessage("Directorio "+certificatesDir+ " no está disponible. No se pueden almancenar certificados.").setTitle("Error:");                     
701       
702            }
703           
704           
705        builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
706                public void onClick(DialogInterface dialog, int id) {
707               // User cancelled the dialog
708                        SelectCertificateToEncryptActivity.this.finish();
709            }
710        });
711            AlertDialog dialog = builder.create();
712            dialog.show();
713            return false;
714    } // fin de checkCertificatesDirectoryAvailability
715       
716   
717    /**
718     * Prepara directorio
719     * @return boolean
720     */
721    boolean prepareDirectory(String dir) 
722    {
723        try
724        {
725            if (makedirs(dir)) 
726            {
727                return true;
728            } else {
729                return false;
730            }
731        } catch (Exception e) 
732        {
733            e.printStackTrace();
734            Toast.makeText(this, "Could not initiate File System.. Is Sdcard mounted properly?", Toast.LENGTH_LONG).show();
735            return false;
736        }
737    }
738   
739    /**
740     * Crea directorio utilizando la variable tmpDir
741     * @return boolean
742     */
743    private boolean makedirs(String dir) 
744    {
745        //File tempdir = new File(extractedDirFiles);
746        File tempdir = new File(dir);
747        if (!tempdir.exists())
748            tempdir.mkdirs();
749        return (tempdir.isDirectory());
750    }
751       
752    /**
753     * Crea un dialogo con el titulo y mensaje como argumentos y lo despliega 
754     *
755     * @return void
756     */
757    public void showDialog(String title, String msg) {
758       
759        // 1. Instantiate an AlertDialog.Builder with its constructor
760                AlertDialog.Builder builder = new AlertDialog.Builder(SelectCertificateToEncryptActivity.this);
761
762                // 2. Chain together various setter methods to set the dialog characteristics
763                builder.setMessage(msg)
764                .setTitle(title);
765
766                builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
767            public void onClick(DialogInterface dialog, int id) {
768                // User clicked OK button                                               
769                Toast.makeText(getApplicationContext(), "User clicked OK button", Toast.LENGTH_LONG).show();
770                finish();                               
771               
772                // lanzar el activity EncryptionCertificatesActivity
773               
774            }
775                });
776               
777                // 3. Get the AlertDialog from create()                         
778                AlertDialog dialog = builder.create();
779                dialog.show();         
780    }
781   
782    /**
783     * Muestra la actividad de información del proceso de cifrado 
784     *
785     * @return void
786     */
787    public void showEncryptionResults(String fileToEncrypt, String encryptedFile, String recipient) {
788               
789        // lanzar el activity EncryptionResultActivity
790        Intent intent = new Intent(this, EncryptionResultActivity.class);               
791                intent.putExtra("fileToEncrypt", fileToEncrypt);
792                intent.putExtra("encryptedFile", encryptedFile);
793                intent.putExtra("recipient", recipient);
794               
795                startActivity(intent);
796
797       
798    }
799   
800   
801   
802   
803}
804
Note: See TracBrowser for help on using the repository browser.