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