Changeset 6638d33 in dispositivos_moviles for TibisayMovil/src
- Timestamp:
- Oct 14, 2013, 5:07:19 PM (11 years ago)
- Branches:
- master
- Children:
- 56b06e2
- Parents:
- 308adc7
- Location:
- TibisayMovil/src/ve/gob/cenditel/tibisaymovil
- Files:
-
- 1 added
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
TibisayMovil/src/ve/gob/cenditel/tibisaymovil/BDOCVerifyResultActivity.java
r308adc7 r6638d33 12 12 import java.net.URL; 13 13 import java.net.URLConnection; 14 import java.security.KeyStore; 15 import java.security.cert.Certificate; 16 import java.security.cert.CertificateFactory; 14 17 import java.util.ArrayList; 15 18 16 19 import javax.net.ssl.HttpsURLConnection; 20 import javax.net.ssl.SSLContext; 21 import javax.net.ssl.TrustManagerFactory; 17 22 18 23 … … 29 34 import android.os.Looper; 30 35 import android.app.Activity; 36 import android.app.AlertDialog; 31 37 import android.app.Dialog; 32 38 import android.app.ProgressDialog; 33 39 import android.content.Context; 40 import android.content.DialogInterface; 34 41 import android.content.Intent; 35 42 import android.util.Log; … … 65 72 private String extractedDirFiles; 66 73 74 // cadena que mantiene la ruta para almacenar los archivos 75 // descargados desde un servidor para verificar su firma 76 private String downloadedDirFiles; 77 67 78 // ruta absoluta al archivo a verificar 68 79 private String fileToVerify; … … 79 90 80 91 // Progress Dialog 81 private ProgressDialog pDialog;92 private ProgressDialog mProgressDialog; 82 93 83 94 // Progress dialog type (0 - for Horizontal progress bar) 84 public static final int progress_bar_type = 0; 95 public static final int DIALOG_DOWNLOAD_PROGRESS = 0; 96 97 //String urlhttps = "https://tibisay.cenditel.gob.ve/trac/raw-attachment/wiki/WikiStart/actados.2.bdoc"; 98 String urlhttps = null; 85 99 86 100 @Override … … 190 204 Toast.makeText(getApplicationContext(), "externalStorage: "+Environment.getExternalStorageDirectory().toString(), Toast.LENGTH_SHORT).show(); 191 205 206 urlhttps = data.toString(); 207 new DownloadFileAsync().execute(data.toString(), "false"); 192 208 193 new DownloadFileFromURL().execute(data.toString());194 209 //new DownloadFileFromURL().execute("http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg"); 195 210 196 211 //Toast.makeText(getApplicationContext(), "****despues de execute()", Toast.LENGTH_SHORT).show(); 197 212 // verificar el archivo 213 Toast.makeText(getApplicationContext(), "Ahora viene la verificación del archivo", Toast.LENGTH_SHORT).show(); 198 214 } 199 215 … … 208 224 mimeTypeFileToVerify = getMimeType(fileToVerify); 209 225 210 Toast.makeText(getApplicationContext(), "fileToVerify: "+fileToVerify, Toast.LENGTH_SHORT).show(); 226 Toast.makeText(getApplicationContext(), "BDOCVerifyResultActivity fileToVerify: "+fileToVerify, Toast.LENGTH_SHORT).show(); 227 Toast.makeText(getApplicationContext(), "BDOCVerifyResultActivity fileToVerifyExtension: "+fileToVerifyExtension, Toast.LENGTH_SHORT).show(); 211 228 212 229 if (fileToVerifyExtension.equals("bdoc")){ 230 Toast.makeText(getApplicationContext(), "BDOCVerifyResultActivity: -> doBdocVerification(fileToVerify)", Toast.LENGTH_SHORT).show(); 213 231 // ejecutar la verificacion 214 232 doBdocVerification(fileToVerify); … … 287 305 private void doBdocVerification(String absolutePathFileToVerify){ 288 306 307 Toast.makeText(getApplicationContext(), "BDOCVerifyResultActivity: dentro doBdocVerification(fileToVerify)"+absolutePathFileToVerify, Toast.LENGTH_SHORT).show(); 289 308 try { 290 309 Log.d("doBdocVerification:", "Inicializando jdigidoc ..."); … … 372 391 getResources().getString(R.string.app_name) + "/" + 373 392 getResources().getString(R.string.extracted_dir_files) + "/"; 374 prepareDirectory( );393 prepareDirectory(extractedDirFiles); 375 394 376 395 for (int i = 0; i < sdoc.countDataFiles(); i++){ … … 457 476 //showOneButtonDialog(e.getMessage()); 458 477 459 Log.d("****exception:", e.getMessage()); 478 Log.d("****exception:", e.getMessage()); 460 479 e.printStackTrace(); 480 Toast.makeText(getApplicationContext(), "BDOCVerifyResultActivity: "+e.getMessage(), Toast.LENGTH_LONG).show(); 461 481 } 462 482 … … 711 731 * @return boolean 712 732 */ 713 private boolean prepareDirectory( )733 private boolean prepareDirectory(String dir) 714 734 { 715 735 try 716 736 { 717 if (makedirs( ))737 if (makedirs(dir)) 718 738 { 719 739 return true; … … 733 753 * @return boolean 734 754 */ 735 private boolean makedirs( )755 private boolean makedirs(String dir) 736 756 { 737 File tempdir = new File(extractedDirFiles); 757 //File tempdir = new File(extractedDirFiles); 758 File tempdir = new File(dir); 738 759 if (!tempdir.exists()) 739 760 tempdir.mkdirs(); … … 825 846 protected Dialog onCreateDialog(int id) { 826 847 switch (id) { 827 case progress_bar_type: // we set this to 0828 pDialog = new ProgressDialog(this);829 pDialog.setMessage("Downloading file. Please wait...");830 pDialog.setIndeterminate(false);831 pDialog.setMax(100);832 pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);833 pDialog.setCancelable(true);834 pDialog.show();835 return pDialog;848 case DIALOG_DOWNLOAD_PROGRESS: // we set this to 0 849 mProgressDialog = new ProgressDialog(this); 850 mProgressDialog.setMessage("Descargando archivo. Por favor espere..."); 851 mProgressDialog.setIndeterminate(false); 852 mProgressDialog.setMax(100); 853 mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 854 mProgressDialog.setCancelable(true); 855 mProgressDialog.show(); 856 return mProgressDialog; 836 857 default: 837 858 return null; … … 840 861 841 862 // clase para descargar archivo 842 private class DownloadFileFromURL extends AsyncTask<String, String, String> { 843 863 private class DownloadFileAsync extends AsyncTask<String, String, ArrayList<String>> { 864 865 File rootDir = Environment.getExternalStorageDirectory(); 844 866 845 867 /** … … 850 872 protected void onPreExecute() { 851 873 super.onPreExecute(); 852 showDialog( progress_bar_type);874 showDialog(DIALOG_DOWNLOAD_PROGRESS); 853 875 } 854 876 … … 858 880 * */ 859 881 @Override 860 protected String doInBackground(String... f_url) {882 protected ArrayList<String> doInBackground(String... params) { 861 883 862 884 // para solventar error: … … 865 887 866 888 int count; 889 890 Log.d("doInBackground", params[0]); 891 892 // resultArray [0] -> 0 para ruta de archivo valida 893 // resultArray [0] -> 1 ocurrio un error 894 // resultArray [1] -> ruta del archivo descargado 895 // resultArray [1] -> mensaje de la excepcion 896 ArrayList<String> resultArray = new ArrayList<String>(); 897 898 867 899 868 900 String outputString = null; 869 901 try { 870 Toast.makeText(getApplicationContext(), "doInBackground", Toast.LENGTH_SHORT).show(); 871 Log.d("doInBackground", "log"); 872 873 URL url = new URL(f_url[0]); 874 //URLConnection conection = url.openConnection(); 875 HttpURLConnection conection = (HttpURLConnection) url.openConnection(); 876 conection.connect(); 902 URL url = new URL(params[0]); 903 904 int lenghtOfFile = 0; 905 InputStream input = null; 906 907 if (url.getProtocol().equals("http")){ 908 HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); 909 input = new BufferedInputStream(httpConnection.getInputStream()); 910 lenghtOfFile = httpConnection.getContentLength(); 911 912 }else{ // https 913 914 // ejecutar la descarga despues de haber aceptado que el certificado 915 // no es conocido 916 if (params[1].equals("true")){ 917 Log.d("***", "params[1].equals(true)"); 918 919 // descarga del certificado del servidor 920 CertificateFactory cf = CertificateFactory.getInstance("X.509"); 921 InputStream caInput = new BufferedInputStream(new FileInputStream(rootDir+"/tibisay.cenditel.gob.ve.pem")); 922 //InputStream caInput = new BufferedInputStream(new FileInputStream(rootDir+"/tibisay.pem")); 923 Certificate ca; 924 try { 925 ca = cf.generateCertificate(caInput); 926 //Log.d("**ca:", ((X509Certificate) ca).getSubjectDN()); 927 928 //Log.d("*** try: ca.toString()", ca.toString()); 929 } finally { 930 caInput.close(); 931 } 932 Log.d("***", "despues de Certificate ca"); 933 // Create a KeyStore containing our trusted CAs 934 String keyStoreType = KeyStore.getDefaultType(); 935 KeyStore keyStore = KeyStore.getInstance(keyStoreType); 936 keyStore.load(null, null); 937 keyStore.setCertificateEntry("ca", ca); 938 Log.d("***", "despues de crear KeyStore"); 939 940 // Create a TrustManager that trusts the CAs in our KeyStore 941 String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); 942 TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); 943 tmf.init(keyStore); 944 Log.d("***", "despues de crear TrustManager"); 945 946 // Create an SSLContext that uses our TrustManager 947 SSLContext context = SSLContext.getInstance("TLS"); 948 context.init(null, tmf.getTrustManagers(), null); 949 Log.d("***", "despues de crear SSLContext"); 950 951 HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection(); 952 Log.d("***", "despues de crear httpsConnection"); 953 954 httpsConnection.setSSLSocketFactory(context.getSocketFactory()); 955 Log.d("***", "despues de crear setSSLSocketFactory"); 956 957 //input = new BufferedInputStream(httpsConnection.getInputStream()); 958 input = httpsConnection.getInputStream(); 959 960 Log.d("***", "despues de crear BufferedInputStream"); 961 962 lenghtOfFile = httpsConnection.getContentLength(); 963 Log.d("***", "se acepto la excepcion"); 964 965 }else{ 966 HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection(); 967 input = new BufferedInputStream(httpsConnection.getInputStream()); 968 lenghtOfFile = httpsConnection.getContentLength(); 969 } 970 } 877 971 878 972 973 // Crear directorio DownloadedFiles donde se almacenan los archivos descargados 974 // desde un servidor para verificar su firma 975 downloadedDirFiles = Environment.getExternalStorageDirectory() + "/" + 976 getResources().getString(R.string.app_name) + "/" + 977 getResources().getString(R.string.downloaded_dir_files) + "/"; 978 prepareDirectory(downloadedDirFiles); 979 980 //int lenghtOfFile = conexion.getContentLength(); 981 Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile); 982 983 //InputStream input = new BufferedInputStream(url.openStream()); 984 //InputStream input = new BufferedInputStream(conexion.getInputStream()); 879 985 880 // this will be useful so that you can show a tipical 0-100% progress bar 881 int lenghtOfFile = conection.getContentLength(); 882 883 // download the file 884 //InputStream input = new BufferedInputStream(url.openStream(), 8192); 885 InputStream input = new BufferedInputStream(url.openStream()); 886 986 //OutputStream output = new FileOutputStream("/mnt/sdcard/TibisayMovil/ExtractedFiles/photo.jpg"); 887 987 888 File rootDir = Environment.getExternalStorageDirectory(); 889 // Output stream 890 //OutputStream output = new FileOutputStream("/sdcard/downloaded.jpg"); 891 OutputStream output = new FileOutputStream(new File(rootDir+"/TibisayMovil/", "descarga.bdoc")); 892 988 //OutputStream output = new FileOutputStream(new File(rootDir+"/midescarga/", "foto.jpg")); 989 990 String urlString = url.toString(); 991 String[] values = urlString.split("/"); 992 993 //OutputStream output = new FileOutputStream(new File(downloadedDirFiles, "acta.2.bdoc")); 994 OutputStream output = new FileOutputStream(new File(downloadedDirFiles, values[values.length-1])); 995 893 996 byte data[] = new byte[1024]; 894 997 895 998 long total = 0; 896 999 897 1000 while ((count = input.read(data)) != -1) { 898 1001 total += count; 899 // publishing the progress....900 // After this onProgressUpdate will be called901 1002 publishProgress(""+(int)((total*100)/lenghtOfFile)); 902 903 // writing data to file 904 //output.write(data, 0, count); 1003 output.write(data, 0, count); 905 1004 } 906 907 // flushing output 1005 908 1006 output.flush(); 909 910 // closing streams 1007 911 1008 output.close(); 912 913 1009 input.close(); 914 1010 1011 resultArray.add("0"); 1012 resultArray.add(output.toString()); 915 1013 916 1014 } catch (Exception e) { … … 919 1017 outputString = e.getMessage(); 920 1018 1019 resultArray.add("1"); 1020 resultArray.add(e.toString()); 921 1021 922 1022 } 923 1023 924 1024 //return null; 925 return outputString;1025 return resultArray; 926 1026 927 1027 } 928 1028 929 /**930 * Updating progress bar931 * */932 1029 protected void onProgressUpdate(String... progress) { 933 // setting progress percentage 934 pDialog.setProgress(Integer.parseInt(progress[0])); 935 } 1030 Log.d("ANDRO_ASYNC",progress[0]); 1031 mProgressDialog.setProgress(Integer.parseInt(progress[0])); 1032 } 1033 1034 @Override 1035 protected void onPostExecute(ArrayList<String> result) { 1036 dismissDialog(DIALOG_DOWNLOAD_PROGRESS); 1037 Toast.makeText(getApplicationContext(), "onPostExecute: "+ result.get(0), Toast.LENGTH_LONG).show(); 1038 1039 // ocurrio una excepcion 1040 if (result.get(0).equals("1")){ 1041 1042 Toast.makeText(getApplicationContext(), "onPostExecute: dentro del if" , Toast.LENGTH_LONG).show(); 1043 1044 // ocurrio un problema 1045 AlertDialog.Builder builder = new AlertDialog.Builder(BDOCVerifyResultActivity.this); 1046 1047 1048 builder.setMessage(result.get(1)).setTitle("Error al descargar el archivo"); 1049 1050 builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 1051 public void onClick(DialogInterface dialog, int id) { 1052 // User clicked OK button 1053 1054 Log.d("***", "DownloadFileAsync().execute(urlhttps, true)"); 1055 Toast.makeText(getApplicationContext(), "DownloadFileAsync().execute(urlhttps, true)", Toast.LENGTH_LONG).show(); 1056 // pasar como segundo argmento que se acepta que el sertivor es desconocido 1057 new DownloadFileAsync().execute(urlhttps, "true"); 1058 } 1059 }); 1060 builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() { 1061 public void onClick(DialogInterface dialog, int id) { 1062 // User cancelled the dialog 1063 } 1064 }); 1065 AlertDialog dialog = builder.create(); 1066 dialog.show(); 1067 1068 1069 1070 }else{ 1071 // no ocurrió excepcion 1072 Toast.makeText(getApplicationContext(), "Se descargo correctamente el archivo", Toast.LENGTH_LONG).show(); 1073 1074 1075 1076 1077 } 1078 1079 1080 } 1081 1082 936 1083 937 /** 938 * After completing background task 939 * Dismiss the progress dialog 940 * **/ 941 @Override 942 protected void onPostExecute(String file_url) { 943 // dismiss the dialog after the file was downloaded 944 dismissDialog(progress_bar_type); 945 946 // Displaying downloaded image into image view 947 // Reading image path from sdcard 948 //String filePath = Environment.getExternalStorageDirectory().toString() + "/TibisayMovil" +"/downloaded.bdoc"; 949 Toast.makeText(getApplicationContext(), "onPostExecute " , Toast.LENGTH_SHORT).show(); 950 Toast.makeText(getApplicationContext(), file_url , Toast.LENGTH_LONG).show(); 951 // setting downloaded into image view 952 //my_image.setImageDrawable(Drawable.createFromPath(imagePath)); 953 } 954 955 956 957 } 958 959 960 961 962 1084 1085 1086 1087 } // fin de la clase DownloadFileAsync 963 1088 } 964 1089
Note: See TracChangeset
for help on using the changeset viewer.