1 | /* |
---|
2 | Tibisay Movil |
---|
3 | |
---|
4 | Copyright (C) 2013 Antonio Araujo (aaraujo@cenditel.gob.ve), Jose Ruiz |
---|
5 | (jruiz@cenditel.gob.ve), Fundacion Centro Nacional de Desarrollo e |
---|
6 | Investigacion en Tecnologias Libres - CENDITEL. |
---|
7 | |
---|
8 | La Fundación CENDITEL concede permiso para usar, copiar, distribuir y/o |
---|
9 | modificar este programa, reconociendo el derecho que la humanidad posee al |
---|
10 | libre acceso al conocimiento, bajo los términos de la licencia de software |
---|
11 | GPL versión 2.0 de la Free Software Foundation. |
---|
12 | |
---|
13 | Este programa se distribuye con la esperanza de que sea util, pero SIN |
---|
14 | NINGUNA GARANTIA; tampoco las implicitas garantias de MERCANTILIDAD o |
---|
15 | ADECUACION A UN PROPOSITO PARTICULAR. |
---|
16 | |
---|
17 | Para mayor información sobre los términos de la licencia ver el archivo |
---|
18 | llamado "gpl-2.0.txt" en ingles. |
---|
19 | */ |
---|
20 | |
---|
21 | package ve.gob.cenditel.tibisaymovil; |
---|
22 | |
---|
23 | import java.io.BufferedInputStream; |
---|
24 | import java.io.File; |
---|
25 | import java.io.FileInputStream; |
---|
26 | import java.io.FileOutputStream; |
---|
27 | import java.io.IOException; |
---|
28 | import java.io.InputStream; |
---|
29 | import java.io.OutputStream; |
---|
30 | import java.net.HttpURLConnection; |
---|
31 | import java.net.MalformedURLException; |
---|
32 | import java.net.URL; |
---|
33 | import java.net.URLConnection; |
---|
34 | import java.security.KeyStore; |
---|
35 | import java.security.cert.Certificate; |
---|
36 | import java.security.cert.CertificateFactory; |
---|
37 | import java.util.ArrayList; |
---|
38 | |
---|
39 | import javax.net.ssl.HttpsURLConnection; |
---|
40 | import javax.net.ssl.SSLContext; |
---|
41 | import javax.net.ssl.TrustManagerFactory; |
---|
42 | |
---|
43 | |
---|
44 | import ee.sk.digidoc.DataFile; |
---|
45 | import ee.sk.digidoc.DigiDocException; |
---|
46 | import ee.sk.digidoc.Signature; |
---|
47 | import ee.sk.digidoc.SignedDoc; |
---|
48 | import ee.sk.digidoc.factory.DigiDocFactory; |
---|
49 | import ee.sk.utils.ConfigManager; |
---|
50 | import android.net.Uri; |
---|
51 | import android.os.AsyncTask; |
---|
52 | import android.os.Bundle; |
---|
53 | import android.os.Environment; |
---|
54 | import android.os.Looper; |
---|
55 | import android.app.Activity; |
---|
56 | import android.app.AlertDialog; |
---|
57 | import android.app.Dialog; |
---|
58 | import android.app.ProgressDialog; |
---|
59 | import android.content.Context; |
---|
60 | import android.content.DialogInterface; |
---|
61 | import android.content.Intent; |
---|
62 | import android.util.Log; |
---|
63 | import android.view.LayoutInflater; |
---|
64 | import android.view.Menu; |
---|
65 | import android.view.View; |
---|
66 | import android.view.ViewGroup; |
---|
67 | import android.view.Window; |
---|
68 | import android.view.View.OnClickListener; |
---|
69 | import android.webkit.MimeTypeMap; |
---|
70 | import android.widget.AdapterView; |
---|
71 | import android.widget.BaseAdapter; |
---|
72 | import android.widget.EditText; |
---|
73 | import android.widget.ImageView; |
---|
74 | import android.widget.LinearLayout; |
---|
75 | import android.widget.ListView; |
---|
76 | import android.widget.TextView; |
---|
77 | import android.widget.Toast; |
---|
78 | |
---|
79 | public class BDOCVerifyResultActivity extends Activity { |
---|
80 | |
---|
81 | |
---|
82 | |
---|
83 | |
---|
84 | // linear |
---|
85 | private LinearLayout button_share; |
---|
86 | private LinearLayout button_finish; |
---|
87 | private ListView documents_list; |
---|
88 | private ImageView arrowShowErrors; |
---|
89 | |
---|
90 | // cadena que mantiene la ruta para almacenar los archivos |
---|
91 | // extraidos de un contendor BDOC |
---|
92 | private String extractedDirFiles; |
---|
93 | |
---|
94 | // cadena que mantiene la ruta para almacenar los archivos |
---|
95 | // descargados desde un servidor para verificar su firma |
---|
96 | private String downloadedDirFiles; |
---|
97 | |
---|
98 | // ruta absoluta al archivo a verificar |
---|
99 | private String fileToVerify; |
---|
100 | |
---|
101 | // extension del archivo a verificar |
---|
102 | private String fileToVerifyExtension; |
---|
103 | |
---|
104 | |
---|
105 | // mimetype del archivo a verificar |
---|
106 | private String mimeTypeFileToVerify; |
---|
107 | |
---|
108 | |
---|
109 | private ArrayList<SignatureErrorDetail> errorList; |
---|
110 | |
---|
111 | // Progress Dialog |
---|
112 | private ProgressDialog mProgressDialog; |
---|
113 | |
---|
114 | // Progress dialog type (0 - for Horizontal progress bar) |
---|
115 | public static final int DIALOG_DOWNLOAD_PROGRESS = 0; |
---|
116 | |
---|
117 | //String urlhttps = "https://tibisay.cenditel.gob.ve/trac/raw-attachment/wiki/WikiStart/actados.2.bdoc"; |
---|
118 | String urlhttps = null; |
---|
119 | |
---|
120 | @Override |
---|
121 | protected void onCreate(Bundle savedInstanceState) { |
---|
122 | |
---|
123 | //Estilando la barra de titulo |
---|
124 | final boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); |
---|
125 | Log.d("onCreate", "antes de super"); |
---|
126 | super.onCreate(savedInstanceState); |
---|
127 | |
---|
128 | setContentView(R.layout.activity_verify_result_bdoc); |
---|
129 | |
---|
130 | //Estilando Barra de titulo |
---|
131 | if(customTitleSupported) |
---|
132 | getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar); |
---|
133 | |
---|
134 | arrowShowErrors = (ImageView) this.findViewById(R.id.arrow_show_errors); |
---|
135 | arrowShowErrors.setVisibility(ImageView.GONE); |
---|
136 | |
---|
137 | button_share = (LinearLayout) this.findViewById(R.id.button_remove_certificate_zone); |
---|
138 | button_finish = (LinearLayout) this.findViewById(R.id.button_add_certificate_zone); |
---|
139 | |
---|
140 | // inicializa la lista de objetos de errores de firma |
---|
141 | errorList = new ArrayList<SignatureErrorDetail>(); |
---|
142 | |
---|
143 | |
---|
144 | // habilita el click sobre la acción de finalizar la verificacion de firma y regresar |
---|
145 | button_finish.setOnClickListener(new OnClickListener() |
---|
146 | { |
---|
147 | public void onClick(View v) |
---|
148 | { |
---|
149 | |
---|
150 | Intent oIntent = new Intent(BDOCVerifyResultActivity.this, TibisayMovilActivity.class); |
---|
151 | oIntent.setAction(Intent.ACTION_VIEW); |
---|
152 | oIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); |
---|
153 | startActivity(oIntent); |
---|
154 | |
---|
155 | finish(); |
---|
156 | } |
---|
157 | }); |
---|
158 | |
---|
159 | // habilita el click sobre la acción de compartir el archivo |
---|
160 | button_share.setOnClickListener(new OnClickListener() |
---|
161 | { |
---|
162 | public void onClick(View v) |
---|
163 | { |
---|
164 | shareIt(); |
---|
165 | } |
---|
166 | }); |
---|
167 | |
---|
168 | // habilita el click sobre la flecha para mostrar los errores de la firma |
---|
169 | arrowShowErrors.setOnClickListener(new OnClickListener(){ |
---|
170 | |
---|
171 | public void onClick(View arg0) { |
---|
172 | |
---|
173 | Intent intent = new Intent(BDOCVerifyResultActivity.this, ActivitySignatureErrors.class); |
---|
174 | |
---|
175 | |
---|
176 | |
---|
177 | intent.setClass(BDOCVerifyResultActivity.this, ActivitySignatureErrors.class); |
---|
178 | intent.putExtra("SignatureErrorDetailList", errorList); |
---|
179 | intent.putExtra("numeroObjetoError", Integer.toString(errorList.size())); |
---|
180 | |
---|
181 | startActivity(intent); |
---|
182 | |
---|
183 | } |
---|
184 | |
---|
185 | }); |
---|
186 | |
---|
187 | // chequear si intent tiene data |
---|
188 | final android.content.Intent intent = getIntent(); |
---|
189 | |
---|
190 | final Bundle bundle = getIntent().getExtras(); |
---|
191 | |
---|
192 | if (intent != null) { |
---|
193 | //Toast.makeText(getApplicationContext(), "intent != null", Toast.LENGTH_SHORT).show(); |
---|
194 | |
---|
195 | final android.net.Uri data = intent.getData (); |
---|
196 | |
---|
197 | if (data != null) { |
---|
198 | //Toast.makeText(getApplicationContext(), "data != null", Toast.LENGTH_SHORT).show(); |
---|
199 | |
---|
200 | // verificar el tipo de scheme |
---|
201 | String scheme = data.getScheme(); |
---|
202 | |
---|
203 | // verificacion de un archivo que esta en el dispositivo |
---|
204 | if (scheme.equals("file")) { |
---|
205 | //Toast.makeText(getApplicationContext(), "file: "+data.getPath(), Toast.LENGTH_SHORT).show(); |
---|
206 | |
---|
207 | // verificar el archivo |
---|
208 | if (data.getPath().endsWith("bdoc")){ |
---|
209 | fileToVerify = data.getPath(); |
---|
210 | |
---|
211 | // ejecutar la verificacion |
---|
212 | doBdocVerification(data.getPath()); |
---|
213 | }else{ |
---|
214 | //Toast.makeText(getApplicationContext(), "¡Por Implementar! scheme == file", Toast.LENGTH_SHORT).show(); |
---|
215 | |
---|
216 | } |
---|
217 | |
---|
218 | } |
---|
219 | |
---|
220 | // verificacion de un archivo que se debe descargar |
---|
221 | if (scheme.equals("https")) { |
---|
222 | //Toast.makeText(getApplicationContext(), "scheme: "+data.toString(), Toast.LENGTH_SHORT).show(); |
---|
223 | |
---|
224 | //Toast.makeText(getApplicationContext(), "externalStorage: "+Environment.getExternalStorageDirectory().toString(), Toast.LENGTH_SHORT).show(); |
---|
225 | |
---|
226 | urlhttps = data.toString(); |
---|
227 | new DownloadFileAsync().execute(data.toString(), "false"); |
---|
228 | |
---|
229 | //new DownloadFileFromURL().execute("http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg"); |
---|
230 | |
---|
231 | //Toast.makeText(getApplicationContext(), "****despues de execute()", Toast.LENGTH_SHORT).show(); |
---|
232 | // verificar el archivo |
---|
233 | //Toast.makeText(getApplicationContext(), "Ahora viene la verificación del archivo", Toast.LENGTH_SHORT).show(); |
---|
234 | } |
---|
235 | |
---|
236 | |
---|
237 | return; |
---|
238 | } |
---|
239 | |
---|
240 | // verificacion de archivo desde la Activity principal |
---|
241 | if (bundle != null) { |
---|
242 | fileToVerify = bundle.getString("fileToVerify"); |
---|
243 | fileToVerifyExtension = bundle.getString("fileExtension"); |
---|
244 | mimeTypeFileToVerify = getMimeType(fileToVerify); |
---|
245 | |
---|
246 | //Toast.makeText(getApplicationContext(), "BDOCVerifyResultActivity fileToVerify: "+fileToVerify, Toast.LENGTH_SHORT).show(); |
---|
247 | //Toast.makeText(getApplicationContext(), "BDOCVerifyResultActivity fileToVerifyExtension: "+fileToVerifyExtension, Toast.LENGTH_SHORT).show(); |
---|
248 | |
---|
249 | if (fileToVerifyExtension.equals("bdoc")){ |
---|
250 | //Toast.makeText(getApplicationContext(), "BDOCVerifyResultActivity: -> doBdocVerification(fileToVerify)", Toast.LENGTH_SHORT).show(); |
---|
251 | // ejecutar la verificacion |
---|
252 | doBdocVerification(fileToVerify); |
---|
253 | }else{ |
---|
254 | //Toast.makeText(getApplicationContext(), "¡Por Implementar bundle != null!", Toast.LENGTH_SHORT).show(); |
---|
255 | |
---|
256 | // ejecutar la verificacion del pdf firmado |
---|
257 | doPdfVerification(fileToVerify); |
---|
258 | } |
---|
259 | |
---|
260 | //return; |
---|
261 | } |
---|
262 | |
---|
263 | }else{ |
---|
264 | //Toast.makeText(getApplicationContext(), "intent == null", Toast.LENGTH_SHORT).show(); |
---|
265 | } |
---|
266 | |
---|
267 | |
---|
268 | //Bundle bundle=getIntent().getExtras(); |
---|
269 | //fileToVerify = bundle.getString("fileToVerify"); |
---|
270 | //fileToVerifyExtension = bundle.getString("fileExtension"); |
---|
271 | //mimeTypeFileToVerify = getMimeType(fileToVerify); |
---|
272 | //Toast.makeText(getApplicationContext(), "fileToVerify: "+fileToVerify, Toast.LENGTH_SHORT).show(); |
---|
273 | |
---|
274 | |
---|
275 | /* |
---|
276 | if (fileToVerifyExtension.equals("bdoc")){ |
---|
277 | // ejecutar la verificacion |
---|
278 | doBdocVerification(fileToVerify); |
---|
279 | }else{ |
---|
280 | Toast.makeText(getApplicationContext(), "¡Por Implementar!", Toast.LENGTH_SHORT).show(); |
---|
281 | |
---|
282 | } |
---|
283 | */ |
---|
284 | |
---|
285 | |
---|
286 | |
---|
287 | } |
---|
288 | |
---|
289 | |
---|
290 | |
---|
291 | |
---|
292 | |
---|
293 | @Override |
---|
294 | public void onStart () { |
---|
295 | |
---|
296 | android.util.Log.d ("**onStart(): ", " onStart"); |
---|
297 | super.onStart (); |
---|
298 | |
---|
299 | |
---|
300 | final android.content.Intent intent = getIntent (); |
---|
301 | |
---|
302 | if (intent != null) |
---|
303 | { |
---|
304 | android.util.Log.d ("**onStart(): ", "> Got intent : " + intent); |
---|
305 | |
---|
306 | final android.net.Uri data = intent.getData (); |
---|
307 | |
---|
308 | if (data != null) |
---|
309 | { |
---|
310 | android.util.Log.d ("**onStart(): ", "> Got data : " + data); |
---|
311 | |
---|
312 | final String filePath = data.getEncodedPath (); |
---|
313 | |
---|
314 | android.util.Log.d ("**onStart(): ", "> Open file : " + filePath); |
---|
315 | |
---|
316 | // file loading comes here. |
---|
317 | } // if |
---|
318 | } // if |
---|
319 | android.util.Log.d ("**onStart(): ", "- saliendo onStart"); |
---|
320 | return; |
---|
321 | |
---|
322 | } |
---|
323 | |
---|
324 | |
---|
325 | |
---|
326 | // funcion para verificar un documento |
---|
327 | private void doBdocVerification(String absolutePathFileToVerify){ |
---|
328 | |
---|
329 | //Toast.makeText(getApplicationContext(), "BDOCVerifyResultActivity: dentro doBdocVerification(fileToVerify)"+absolutePathFileToVerify, Toast.LENGTH_SHORT).show(); |
---|
330 | try { |
---|
331 | Log.d("doBdocVerification:", "Inicializando jdigidoc ..."); |
---|
332 | ConfigManager.init("jar://jdigidoc.cfg"); |
---|
333 | Log.d("despues de:", "ConfigManager.init"); |
---|
334 | |
---|
335 | Log.d("antes de:", "digFac"); |
---|
336 | DigiDocFactory digFac = ConfigManager.instance().getDigiDocFactory(); |
---|
337 | |
---|
338 | Log.d("getFilesDir:", getFilesDir().getAbsolutePath()); |
---|
339 | |
---|
340 | Log.d("PATH", Environment.getExternalStorageDirectory().toString()); |
---|
341 | |
---|
342 | File file = new File(absolutePathFileToVerify); |
---|
343 | InputStream selectedFile = null; |
---|
344 | selectedFile = new BufferedInputStream(new FileInputStream(file)); |
---|
345 | |
---|
346 | SignedDoc sdoc = digFac.readSignedDocFromStreamOfType(selectedFile, true); |
---|
347 | selectedFile.close(); |
---|
348 | |
---|
349 | //SignedDoc sdoc = digFac.readSignedDocFromStreamOfType(fraw, true); |
---|
350 | Signature signature = sdoc.getSignature(0); |
---|
351 | |
---|
352 | // TextView para colocar el resultado de la firma |
---|
353 | TextView signatureVerificationResult = (TextView) findViewById(R.id.archivo_original_a_descifrar); |
---|
354 | |
---|
355 | |
---|
356 | // array de excepciones lanzadas al verificar firmas |
---|
357 | ArrayList arraySignaturesErrors = null; |
---|
358 | |
---|
359 | // verificar cada una de las firmas del contenedor |
---|
360 | for (int i = 0; i < sdoc.countSignatures(); i++){ |
---|
361 | Signature tmpSignature = sdoc.getSignature(i); |
---|
362 | arraySignaturesErrors = new ArrayList(); |
---|
363 | arraySignaturesErrors = tmpSignature.verify(sdoc, false, false); |
---|
364 | Log.d("**La Firma: "+Integer.toString(i),"tiene : "+ arraySignaturesErrors.size()+" errores."); |
---|
365 | |
---|
366 | // lista de cadenas que almancenara los errores para el firmante i |
---|
367 | ArrayList<String> signatureVerificationErrors = new ArrayList<String>(); |
---|
368 | |
---|
369 | for (int j = 0; j < arraySignaturesErrors.size(); j++){ |
---|
370 | // agregar la cadena de error particular a la lista |
---|
371 | signatureVerificationErrors.add(arraySignaturesErrors.get(j).toString() + "\n"); |
---|
372 | } |
---|
373 | |
---|
374 | //String cn = SignedDoc.getCommonName(sdoc.getSignature(i).getKeyInfo().getSignersCertificate().getSubjectDN().getName()); |
---|
375 | String signer = sdoc.getSignature(i).getKeyInfo().getSubjectLastName(); |
---|
376 | |
---|
377 | // crear objeto SignatureErrorDetail con detalles de error para la firma i |
---|
378 | SignatureErrorDetail object = new SignatureErrorDetail(signer, signatureVerificationErrors); |
---|
379 | |
---|
380 | // agregar el objeto SignatureErrorDetail a lista |
---|
381 | errorList.add(object); |
---|
382 | |
---|
383 | } // fin del for para la firma i |
---|
384 | |
---|
385 | if (arraySignaturesErrors.isEmpty()) { |
---|
386 | signatureVerificationResult.setText(getResources().getString(R.string.string_valid_signature)); |
---|
387 | Log.d("signature.verify", "NO HUBO ERROR EN LA VERIFICACION DE FIRMA"); |
---|
388 | Toast.makeText(getApplicationContext(), "¡FIRMA CORRECTA!", Toast.LENGTH_SHORT).show(); |
---|
389 | |
---|
390 | }else{ |
---|
391 | |
---|
392 | // habilitar la flecha para mostrar los errores de firma |
---|
393 | arrowShowErrors.setVisibility(ImageView.VISIBLE); |
---|
394 | |
---|
395 | //signatureVerificationResult.setText("Inválida."); |
---|
396 | signatureVerificationResult.setText(getResources().getString(R.string.string_invalid_signature)); |
---|
397 | Log.d("************", "SI HUBO ERROR"); |
---|
398 | |
---|
399 | Toast.makeText(getApplicationContext(), "ERROR DE VERIFICACION DE FIRMA", Toast.LENGTH_SHORT).show(); |
---|
400 | } |
---|
401 | |
---|
402 | |
---|
403 | //ArrayList sigError = signature.verify(sdoc, false, false); |
---|
404 | //ArrayList sigError = sdoc.verify(false, false); |
---|
405 | |
---|
406 | // se crea el adaptador para mostrar los documentos firmados |
---|
407 | ListView documentListView = (ListView) findViewById(R.id.documents_list); |
---|
408 | final ArrayList<DocumentFromBDOC> docs = new ArrayList<DocumentFromBDOC>(); |
---|
409 | |
---|
410 | // Crear directorio ExtractedFiles donde se almacenan los archivos extraidos |
---|
411 | // de los contenedores BDOC |
---|
412 | extractedDirFiles = Environment.getExternalStorageDirectory() + "/" + |
---|
413 | getResources().getString(R.string.app_name) + "/" + |
---|
414 | getResources().getString(R.string.extracted_dir_files) + "/"; |
---|
415 | prepareDirectory(extractedDirFiles); |
---|
416 | |
---|
417 | for (int i = 0; i < sdoc.countDataFiles(); i++){ |
---|
418 | // obtener el DataFile |
---|
419 | DataFile df = sdoc.getDataFile(i); |
---|
420 | docs.add(new DocumentFromBDOC(df.getFileName())); |
---|
421 | Log.d("MIMETYPE:", df.getMimeType()); |
---|
422 | // Extraer el archivo y guardarlo en /mnt/sdcard/TibisayMovil/ExtractedFiles |
---|
423 | FileOutputStream fos = new FileOutputStream(extractedDirFiles+df.getFileName()); |
---|
424 | InputStream is = df.getBodyAsStream(); |
---|
425 | if(is == null) { |
---|
426 | Log.d("ERROR al extrarer archivo", "DataFile has no data!"); |
---|
427 | //return false; |
---|
428 | } |
---|
429 | byte[] data = new byte[4096]; |
---|
430 | int n = 0, m = 0; |
---|
431 | while((n = is.read(data)) > 0) { |
---|
432 | fos.write(data, 0, n); |
---|
433 | m += n; |
---|
434 | } |
---|
435 | fos.close(); |
---|
436 | is.close(); |
---|
437 | } |
---|
438 | |
---|
439 | DocumentFromBDOCAdapter documentAdapter = new DocumentFromBDOCAdapter(BDOCVerifyResultActivity.this, docs); |
---|
440 | documentListView.setAdapter(documentAdapter); |
---|
441 | documentListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() { |
---|
442 | |
---|
443 | @Override |
---|
444 | public void onItemClick(AdapterView<?> parent, View view, |
---|
445 | int position, long id) { |
---|
446 | String absolutePathToOpen = extractedDirFiles + docs.get(position).getName(); |
---|
447 | //Toast.makeText(getApplicationContext(), getMimeType(absolutePathToOpen), Toast.LENGTH_SHORT).show(); |
---|
448 | openIt(absolutePathToOpen, getMimeType(absolutePathToOpen)); |
---|
449 | |
---|
450 | |
---|
451 | } |
---|
452 | |
---|
453 | }); |
---|
454 | |
---|
455 | // se crea el adaptador para mostrar los firmantes del contenedor |
---|
456 | ListView signerListView = (ListView) findViewById(R.id.signatures_list); |
---|
457 | final ArrayList<SignerFromBDOC> signers = new ArrayList<SignerFromBDOC>(); |
---|
458 | |
---|
459 | for (int i = 0; i < sdoc.countSignatures(); i++){ |
---|
460 | Signature signatureTemp = sdoc.getSignature(i); |
---|
461 | //signers.add(new SignerFromBDOC(signatureTemp.getSubject())); |
---|
462 | |
---|
463 | String cn = SignedDoc.getCommonName( |
---|
464 | sdoc.getSignature(i).getKeyInfo().getSignersCertificate().getSubjectDN().getName()); |
---|
465 | String name = sdoc.getSignature(i).getKeyInfo().getSubjectLastName(); |
---|
466 | String date = sdoc.getSignature(i).getSignedProperties().getSigningTime().toString(); |
---|
467 | String certificateSerial = sdoc.getSignature(i).getKeyInfo().getSignersCertificate().getSerialNumber().toString(); |
---|
468 | String validFrom = sdoc.getSignature(i).getKeyInfo().getSignersCertificate().getNotBefore().toLocaleString(); |
---|
469 | String validUntil = sdoc.getSignature(i).getKeyInfo().getSignersCertificate().getNotAfter().toLocaleString(); |
---|
470 | String certificateIssuer = sdoc.getSignature(i).getKeyInfo().getSignersCertificate().getIssuerX500Principal().toString(); |
---|
471 | |
---|
472 | // agregar el nombre comun del firmante y la fecha y la hora |
---|
473 | signers.add(new SignerFromBDOC(name, cn, date, certificateSerial, validFrom, validUntil, certificateIssuer)); |
---|
474 | |
---|
475 | } |
---|
476 | SignerFromBDOCAdapter signerAdapter = new SignerFromBDOCAdapter(BDOCVerifyResultActivity.this, signers); |
---|
477 | signerListView.setAdapter(signerAdapter); |
---|
478 | signerListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() { |
---|
479 | |
---|
480 | |
---|
481 | @Override |
---|
482 | public void onItemClick(AdapterView<?> parent, View view, |
---|
483 | int position, long id) { |
---|
484 | |
---|
485 | //String signer = parent.getItemAtPosition(position).toString(); |
---|
486 | |
---|
487 | //Toast.makeText(getApplicationContext(), "SE DEBE MOSTRAR INFORMACIÓN DEL FIRMANTE", Toast.LENGTH_SHORT).show(); |
---|
488 | showSignatureDetails(position, signers); |
---|
489 | } |
---|
490 | |
---|
491 | }); |
---|
492 | |
---|
493 | |
---|
494 | |
---|
495 | } catch (Exception e) { |
---|
496 | // TODO Auto-generated catch block |
---|
497 | |
---|
498 | //showOneButtonDialog(e.getMessage()); |
---|
499 | |
---|
500 | Log.d("****exception:", e.getMessage()); |
---|
501 | e.printStackTrace(); |
---|
502 | Toast.makeText(getApplicationContext(), "BDOCVerifyResultActivity: "+e.getMessage(), Toast.LENGTH_LONG).show(); |
---|
503 | } |
---|
504 | |
---|
505 | } // fin de doVerification(String f) |
---|
506 | |
---|
507 | |
---|
508 | |
---|
509 | |
---|
510 | |
---|
511 | |
---|
512 | |
---|
513 | |
---|
514 | |
---|
515 | |
---|
516 | // clase que abstrae un documento incluido dentro de un contenedor BDOC |
---|
517 | public class DocumentFromBDOC { |
---|
518 | private String mName; |
---|
519 | |
---|
520 | public DocumentFromBDOC(String name){ |
---|
521 | mName = name; |
---|
522 | } |
---|
523 | |
---|
524 | public void setName(String name) { |
---|
525 | this.mName = name; |
---|
526 | } |
---|
527 | |
---|
528 | public String getName() { |
---|
529 | return mName; |
---|
530 | } |
---|
531 | } // fin de clase DocumentFromBDOC |
---|
532 | |
---|
533 | // clase que abstrae el adaptador para llenar el ListView de documentos que |
---|
534 | // se encuentran dentro del contenedor BDOC |
---|
535 | private class DocumentFromBDOCAdapter extends BaseAdapter { |
---|
536 | |
---|
537 | private ArrayList<DocumentFromBDOC> mDocumentFromBDOCList; |
---|
538 | private LayoutInflater lInflater; |
---|
539 | |
---|
540 | private DocumentFromBDOCAdapter(Context context, ArrayList<DocumentFromBDOC> documents) { |
---|
541 | this.lInflater = LayoutInflater.from(context); |
---|
542 | this.mDocumentFromBDOCList = documents; |
---|
543 | |
---|
544 | } |
---|
545 | |
---|
546 | |
---|
547 | @Override |
---|
548 | public int getCount() { |
---|
549 | return mDocumentFromBDOCList.size(); |
---|
550 | } |
---|
551 | |
---|
552 | @Override |
---|
553 | public Object getItem(int position) { |
---|
554 | return mDocumentFromBDOCList.get(position); |
---|
555 | } |
---|
556 | |
---|
557 | @Override |
---|
558 | public long getItemId(int position) { |
---|
559 | return position; |
---|
560 | } |
---|
561 | |
---|
562 | @Override |
---|
563 | public View getView(int position, View convertView, ViewGroup parent) { |
---|
564 | ViewHolder container = null; |
---|
565 | |
---|
566 | if (convertView == null){ |
---|
567 | container = new ViewHolder(); |
---|
568 | convertView = lInflater.inflate(R.layout.document_inside_bdoc_item, null); |
---|
569 | |
---|
570 | container.filename_text = (TextView) convertView.findViewById(R.id.filename_text); |
---|
571 | container.filename_modified = (TextView) convertView.findViewById(R.id.filename_modified); |
---|
572 | container.type_image = (ImageView) convertView.findViewById(R.id.type_image); |
---|
573 | convertView.setTag(container); |
---|
574 | }else{ |
---|
575 | container = (ViewHolder) convertView.getTag(); |
---|
576 | } |
---|
577 | |
---|
578 | DocumentFromBDOC doc = (DocumentFromBDOC) getItem(position); |
---|
579 | container.filename_text.setText(doc.getName()); |
---|
580 | container.filename_modified.setText(doc.getName()); |
---|
581 | container.type_image.setImageResource(R.drawable.ic_archivo_verde); |
---|
582 | |
---|
583 | return convertView; |
---|
584 | } |
---|
585 | |
---|
586 | |
---|
587 | class ViewHolder{ |
---|
588 | TextView filename_text; |
---|
589 | TextView filename_modified; |
---|
590 | ImageView type_image; |
---|
591 | } |
---|
592 | |
---|
593 | } |
---|
594 | |
---|
595 | |
---|
596 | // class que abstrae un firmante incluido en un contenedor BDOC |
---|
597 | private class SignerFromBDOC { |
---|
598 | |
---|
599 | // nombre del firmante |
---|
600 | private String mName; |
---|
601 | |
---|
602 | // nombre comun del firmante |
---|
603 | private String mCN; |
---|
604 | |
---|
605 | // fecha y hora de la firma |
---|
606 | private String mDate; |
---|
607 | |
---|
608 | // serial del certificado |
---|
609 | private String mCertificateSerial; |
---|
610 | |
---|
611 | // fecha de validez inicial |
---|
612 | private String mValidFrom; |
---|
613 | |
---|
614 | // fecha de validez final |
---|
615 | private String mValidUntil; |
---|
616 | |
---|
617 | // emisor del certificado |
---|
618 | private String mCertificateIssuer; |
---|
619 | |
---|
620 | public SignerFromBDOC(String name, String cn, String date, String serial, String validFrom, String validUntil, String issuer){ |
---|
621 | mName = name; |
---|
622 | mCN = cn; |
---|
623 | mDate = date; |
---|
624 | mCertificateSerial = serial; |
---|
625 | mValidFrom = validFrom; |
---|
626 | mValidUntil = validUntil; |
---|
627 | mCertificateIssuer = issuer; |
---|
628 | } |
---|
629 | |
---|
630 | public void setName(String name) { |
---|
631 | this.mName = name; |
---|
632 | } |
---|
633 | |
---|
634 | public String getName() { |
---|
635 | return mName; |
---|
636 | } |
---|
637 | |
---|
638 | public void setCN(String cn) { |
---|
639 | this.mCN = cn; |
---|
640 | } |
---|
641 | |
---|
642 | public String getCN() { |
---|
643 | return mCN; |
---|
644 | } |
---|
645 | |
---|
646 | public void setDate(String date) { |
---|
647 | this.mDate = date; |
---|
648 | } |
---|
649 | |
---|
650 | public String getDate() { |
---|
651 | return mDate; |
---|
652 | } |
---|
653 | |
---|
654 | public void setCertificateSerial(String certSerial) { |
---|
655 | this.mCertificateSerial = certSerial; |
---|
656 | } |
---|
657 | |
---|
658 | public String getCertificateSerial() { |
---|
659 | return mCertificateSerial; |
---|
660 | } |
---|
661 | |
---|
662 | public void setValidFrom(String validFrom) { |
---|
663 | this.mValidFrom = validFrom; |
---|
664 | } |
---|
665 | |
---|
666 | public String getValidFrom() { |
---|
667 | return mValidFrom; |
---|
668 | } |
---|
669 | |
---|
670 | public void setValidUntil(String validUntil) { |
---|
671 | this.mValidUntil = validUntil; |
---|
672 | } |
---|
673 | |
---|
674 | public String getValidUntil() { |
---|
675 | return mValidUntil; |
---|
676 | } |
---|
677 | |
---|
678 | public void setCertificateIssuer(String certIssuer) { |
---|
679 | this.mCertificateIssuer = certIssuer; |
---|
680 | } |
---|
681 | |
---|
682 | public String getCertificateIssuer() { |
---|
683 | return mCertificateIssuer; |
---|
684 | } |
---|
685 | |
---|
686 | } // fin de clase SignerFromBDOC |
---|
687 | |
---|
688 | // clase que abstrae el adaptador para llenar el ListView de documentos que |
---|
689 | // se encuentran dentro del contenedor BDOC |
---|
690 | private class SignerFromBDOCAdapter extends BaseAdapter { |
---|
691 | |
---|
692 | private ArrayList<SignerFromBDOC> mSignerFromBDOCList; |
---|
693 | private LayoutInflater lInflater; |
---|
694 | |
---|
695 | private SignerFromBDOCAdapter(Context context, ArrayList<SignerFromBDOC> signers) { |
---|
696 | this.lInflater = LayoutInflater.from(context); |
---|
697 | this.mSignerFromBDOCList = signers; |
---|
698 | |
---|
699 | } |
---|
700 | |
---|
701 | |
---|
702 | @Override |
---|
703 | public int getCount() { |
---|
704 | return mSignerFromBDOCList.size(); |
---|
705 | } |
---|
706 | |
---|
707 | @Override |
---|
708 | public Object getItem(int position) { |
---|
709 | return mSignerFromBDOCList.get(position); |
---|
710 | } |
---|
711 | |
---|
712 | @Override |
---|
713 | public long getItemId(int position) { |
---|
714 | return position; |
---|
715 | } |
---|
716 | |
---|
717 | @Override |
---|
718 | public View getView(int position, View convertView, ViewGroup parent) { |
---|
719 | ViewHolder container = null; |
---|
720 | |
---|
721 | if (convertView == null){ |
---|
722 | container = new ViewHolder(); |
---|
723 | convertView = lInflater.inflate(R.layout.signer_inside_bdoc_item, null); |
---|
724 | |
---|
725 | container.signer_text = (TextView) convertView.findViewById(R.id.signer_info); |
---|
726 | container.signer_modified = (TextView) convertView.findViewById(R.id.signature_errors); |
---|
727 | container.type_image = (ImageView) convertView.findViewById(R.id.type_image); |
---|
728 | convertView.setTag(container); |
---|
729 | }else{ |
---|
730 | container = (ViewHolder) convertView.getTag(); |
---|
731 | } |
---|
732 | |
---|
733 | SignerFromBDOC doc = (SignerFromBDOC) getItem(position); |
---|
734 | container.signer_text.setText(doc.getName()); |
---|
735 | container.signer_modified.setText(doc.getName()); |
---|
736 | container.type_image.setImageResource(R.drawable.ic_firmar_verde); |
---|
737 | |
---|
738 | return convertView; |
---|
739 | } |
---|
740 | |
---|
741 | |
---|
742 | class ViewHolder{ |
---|
743 | TextView signer_text; |
---|
744 | TextView signer_modified; |
---|
745 | ImageView type_image; |
---|
746 | } |
---|
747 | |
---|
748 | } |
---|
749 | |
---|
750 | |
---|
751 | /** |
---|
752 | * Prepara directorio |
---|
753 | * @return boolean |
---|
754 | */ |
---|
755 | private boolean prepareDirectory(String dir) |
---|
756 | { |
---|
757 | try |
---|
758 | { |
---|
759 | if (makedirs(dir)) |
---|
760 | { |
---|
761 | return true; |
---|
762 | } else { |
---|
763 | return false; |
---|
764 | } |
---|
765 | } catch (Exception e) |
---|
766 | { |
---|
767 | e.printStackTrace(); |
---|
768 | //Toast.makeText(this, "Could not initiate File System.. Is Sdcard mounted properly?", Toast.LENGTH_LONG).show(); |
---|
769 | Toast.makeText(this, "No se pudo iniciar el sistema de archivos. ¿Está la SDCARD montada?", Toast.LENGTH_LONG).show(); |
---|
770 | return false; |
---|
771 | } |
---|
772 | } |
---|
773 | |
---|
774 | /** |
---|
775 | * Crea directorio utilizando la variable tmpDir |
---|
776 | * @return boolean |
---|
777 | */ |
---|
778 | private boolean makedirs(String dir) |
---|
779 | { |
---|
780 | //File tempdir = new File(extractedDirFiles); |
---|
781 | File tempdir = new File(dir); |
---|
782 | if (!tempdir.exists()) |
---|
783 | tempdir.mkdirs(); |
---|
784 | |
---|
785 | // if (tempdir.isDirectory()) |
---|
786 | // { |
---|
787 | // File[] files = tempdir.listFiles(); |
---|
788 | // for (File file : files) |
---|
789 | // { |
---|
790 | // if (!file.delete()) |
---|
791 | // { |
---|
792 | // System.out.println("Failed to delete " + file); |
---|
793 | // } |
---|
794 | // } |
---|
795 | // } |
---|
796 | return (tempdir.isDirectory()); |
---|
797 | } |
---|
798 | |
---|
799 | // funcion para lanzar un intent que abra un archivo |
---|
800 | private void openIt(String filePath, String mimeType) { |
---|
801 | |
---|
802 | Intent shareIntent = new Intent(); |
---|
803 | shareIntent.setAction(Intent.ACTION_VIEW); |
---|
804 | File file = new File(filePath); |
---|
805 | Uri uri = Uri.fromFile(file); |
---|
806 | Log.i("DEBUG", file.getPath()); |
---|
807 | shareIntent.setDataAndType(uri, mimeType); |
---|
808 | startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.open_it_using))); |
---|
809 | } |
---|
810 | |
---|
811 | // funcion para obtener el tipo mime de un archivo |
---|
812 | public static String getMimeType(String url) |
---|
813 | { |
---|
814 | String extension = url.substring(url.lastIndexOf(".")); |
---|
815 | String mimeTypeMap = MimeTypeMap.getFileExtensionFromUrl(extension); |
---|
816 | String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(mimeTypeMap); |
---|
817 | return mimeType; |
---|
818 | } |
---|
819 | |
---|
820 | // funcion para compartir el documento |
---|
821 | private void shareIt() { |
---|
822 | |
---|
823 | Intent shareIntent = new Intent(); |
---|
824 | shareIntent.setAction(Intent.ACTION_SEND); |
---|
825 | File file = new File(fileToVerify); |
---|
826 | |
---|
827 | |
---|
828 | Uri uri = Uri.fromFile(file); |
---|
829 | Log.i("DEBUG", file.getPath()); |
---|
830 | //Log.d("******", getMimeType(file.getPath())); |
---|
831 | //shareIntent.setDataAndType(uri, getMimeType(file.getPath())); |
---|
832 | shareIntent.putExtra(Intent.EXTRA_STREAM, uri); |
---|
833 | shareIntent.setType("application/*"); |
---|
834 | startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share_it_using))); |
---|
835 | } |
---|
836 | |
---|
837 | @Override |
---|
838 | public boolean onCreateOptionsMenu(Menu menu) { |
---|
839 | // Inflate the menu; this adds items to the action bar if it is present. |
---|
840 | getMenuInflater().inflate(R.menu.bdocverify_result, menu); |
---|
841 | return true; |
---|
842 | } |
---|
843 | |
---|
844 | private void showSignatureDetails(int position, ArrayList<SignerFromBDOC> signers) { |
---|
845 | |
---|
846 | Log.d("**showSignatureDetails", Integer.toString(position)); |
---|
847 | Log.d("** nombre", signers.get(position).getName()); |
---|
848 | Intent intent = new Intent(this, ActivitySignerInfo.class); |
---|
849 | |
---|
850 | intent.putExtra("name", signers.get(position).getName()); |
---|
851 | intent.putExtra("cn", signers.get(position).getCN()); |
---|
852 | intent.putExtra("date", signers.get(position).getDate()); |
---|
853 | intent.putExtra("certificateSerial", signers.get(position).getCertificateSerial()); |
---|
854 | intent.putExtra("validFrom", signers.get(position).getValidFrom()); |
---|
855 | intent.putExtra("validUntil", signers.get(position).getValidUntil()); |
---|
856 | intent.putExtra("certificateIssuer", signers.get(position).getCertificateIssuer()); |
---|
857 | startActivity(intent); |
---|
858 | } |
---|
859 | |
---|
860 | // funcion para desplegar la interfaz con los detalles de errores de la firma |
---|
861 | private void showSignatureDetails() { |
---|
862 | Log.d("showSignatureDetails()", "..."); |
---|
863 | } |
---|
864 | |
---|
865 | /** |
---|
866 | * Showing Dialog for downloading file |
---|
867 | * */ |
---|
868 | @Override |
---|
869 | protected Dialog onCreateDialog(int id) { |
---|
870 | switch (id) { |
---|
871 | case DIALOG_DOWNLOAD_PROGRESS: // we set this to 0 |
---|
872 | mProgressDialog = new ProgressDialog(this); |
---|
873 | mProgressDialog.setMessage("Descargando archivo. Por favor espere..."); |
---|
874 | mProgressDialog.setIndeterminate(false); |
---|
875 | mProgressDialog.setMax(100); |
---|
876 | mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); |
---|
877 | mProgressDialog.setCancelable(true); |
---|
878 | mProgressDialog.show(); |
---|
879 | return mProgressDialog; |
---|
880 | default: |
---|
881 | return null; |
---|
882 | } |
---|
883 | } |
---|
884 | |
---|
885 | // clase para descargar archivo |
---|
886 | private class DownloadFileAsync extends AsyncTask<String, String, ArrayList<String>> { |
---|
887 | |
---|
888 | File rootDir = Environment.getExternalStorageDirectory(); |
---|
889 | |
---|
890 | /** |
---|
891 | * Before starting background thread |
---|
892 | * Show Progress Bar Dialog |
---|
893 | * */ |
---|
894 | @Override |
---|
895 | protected void onPreExecute() { |
---|
896 | super.onPreExecute(); |
---|
897 | showDialog(DIALOG_DOWNLOAD_PROGRESS); |
---|
898 | } |
---|
899 | |
---|
900 | |
---|
901 | /** |
---|
902 | * Downloading file in background thread |
---|
903 | * */ |
---|
904 | @Override |
---|
905 | protected ArrayList<String> doInBackground(String... params) { |
---|
906 | |
---|
907 | // para solventar error: |
---|
908 | // Can't create handler inside thread that has not called Looper.prepare() |
---|
909 | Looper.prepare(); |
---|
910 | |
---|
911 | int count; |
---|
912 | |
---|
913 | Log.d("doInBackground", params[0]); |
---|
914 | |
---|
915 | // resultArray [0] -> 0 para ruta de archivo valida |
---|
916 | // resultArray [0] -> 1 ocurrio un error |
---|
917 | // resultArray [1] -> ruta del archivo descargado |
---|
918 | // resultArray [1] -> mensaje de la excepcion |
---|
919 | ArrayList<String> resultArray = new ArrayList<String>(); |
---|
920 | |
---|
921 | |
---|
922 | |
---|
923 | String outputString = null; |
---|
924 | try { |
---|
925 | URL url = new URL(params[0]); |
---|
926 | |
---|
927 | int lenghtOfFile = 0; |
---|
928 | InputStream input = null; |
---|
929 | |
---|
930 | if (url.getProtocol().equals("http")){ |
---|
931 | HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); |
---|
932 | input = new BufferedInputStream(httpConnection.getInputStream()); |
---|
933 | lenghtOfFile = httpConnection.getContentLength(); |
---|
934 | |
---|
935 | }else{ // https |
---|
936 | |
---|
937 | // ejecutar la descarga despues de haber aceptado que el certificado |
---|
938 | // no es conocido |
---|
939 | if (params[1].equals("true")){ |
---|
940 | Log.d("***", "params[1].equals(true)"); |
---|
941 | |
---|
942 | // descarga del certificado del servidor |
---|
943 | CertificateFactory cf = CertificateFactory.getInstance("X.509"); |
---|
944 | InputStream caInput = new BufferedInputStream(new FileInputStream(rootDir+"/tibisay.cenditel.gob.ve.pem")); |
---|
945 | //InputStream caInput = new BufferedInputStream(new FileInputStream(rootDir+"/tibisay.pem")); |
---|
946 | Certificate ca; |
---|
947 | try { |
---|
948 | ca = cf.generateCertificate(caInput); |
---|
949 | //Log.d("**ca:", ((X509Certificate) ca).getSubjectDN()); |
---|
950 | |
---|
951 | //Log.d("*** try: ca.toString()", ca.toString()); |
---|
952 | } finally { |
---|
953 | caInput.close(); |
---|
954 | } |
---|
955 | Log.d("***", "despues de Certificate ca"); |
---|
956 | // Create a KeyStore containing our trusted CAs |
---|
957 | String keyStoreType = KeyStore.getDefaultType(); |
---|
958 | KeyStore keyStore = KeyStore.getInstance(keyStoreType); |
---|
959 | keyStore.load(null, null); |
---|
960 | keyStore.setCertificateEntry("ca", ca); |
---|
961 | Log.d("***", "despues de crear KeyStore"); |
---|
962 | |
---|
963 | // Create a TrustManager that trusts the CAs in our KeyStore |
---|
964 | String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); |
---|
965 | TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); |
---|
966 | tmf.init(keyStore); |
---|
967 | Log.d("***", "despues de crear TrustManager"); |
---|
968 | |
---|
969 | // Create an SSLContext that uses our TrustManager |
---|
970 | SSLContext context = SSLContext.getInstance("TLS"); |
---|
971 | context.init(null, tmf.getTrustManagers(), null); |
---|
972 | Log.d("***", "despues de crear SSLContext"); |
---|
973 | |
---|
974 | HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection(); |
---|
975 | Log.d("***", "despues de crear httpsConnection"); |
---|
976 | |
---|
977 | httpsConnection.setSSLSocketFactory(context.getSocketFactory()); |
---|
978 | Log.d("***", "despues de crear setSSLSocketFactory"); |
---|
979 | |
---|
980 | //input = new BufferedInputStream(httpsConnection.getInputStream()); |
---|
981 | input = httpsConnection.getInputStream(); |
---|
982 | |
---|
983 | Log.d("***", "despues de crear BufferedInputStream"); |
---|
984 | |
---|
985 | lenghtOfFile = httpsConnection.getContentLength(); |
---|
986 | Log.d("***", "se acepto la excepcion"); |
---|
987 | |
---|
988 | }else{ |
---|
989 | HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection(); |
---|
990 | input = new BufferedInputStream(httpsConnection.getInputStream()); |
---|
991 | lenghtOfFile = httpsConnection.getContentLength(); |
---|
992 | } |
---|
993 | } |
---|
994 | |
---|
995 | |
---|
996 | // Crear directorio DownloadedFiles donde se almacenan los archivos descargados |
---|
997 | // desde un servidor para verificar su firma |
---|
998 | downloadedDirFiles = Environment.getExternalStorageDirectory() + "/" + |
---|
999 | getResources().getString(R.string.app_name) + "/" + |
---|
1000 | getResources().getString(R.string.downloaded_dir_files) + "/"; |
---|
1001 | prepareDirectory(downloadedDirFiles); |
---|
1002 | |
---|
1003 | //int lenghtOfFile = conexion.getContentLength(); |
---|
1004 | Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile); |
---|
1005 | |
---|
1006 | //InputStream input = new BufferedInputStream(url.openStream()); |
---|
1007 | //InputStream input = new BufferedInputStream(conexion.getInputStream()); |
---|
1008 | |
---|
1009 | //OutputStream output = new FileOutputStream("/mnt/sdcard/TibisayMovil/ExtractedFiles/photo.jpg"); |
---|
1010 | |
---|
1011 | //OutputStream output = new FileOutputStream(new File(rootDir+"/midescarga/", "foto.jpg")); |
---|
1012 | |
---|
1013 | String urlString = url.toString(); |
---|
1014 | String[] values = urlString.split("/"); |
---|
1015 | |
---|
1016 | //OutputStream output = new FileOutputStream(new File(downloadedDirFiles, "acta.2.bdoc")); |
---|
1017 | OutputStream output = new FileOutputStream(new File(downloadedDirFiles, values[values.length-1])); |
---|
1018 | |
---|
1019 | byte data[] = new byte[1024]; |
---|
1020 | |
---|
1021 | long total = 0; |
---|
1022 | |
---|
1023 | while ((count = input.read(data)) != -1) { |
---|
1024 | total += count; |
---|
1025 | publishProgress(""+(int)((total*100)/lenghtOfFile)); |
---|
1026 | output.write(data, 0, count); |
---|
1027 | } |
---|
1028 | |
---|
1029 | output.flush(); |
---|
1030 | |
---|
1031 | output.close(); |
---|
1032 | input.close(); |
---|
1033 | |
---|
1034 | resultArray.add("0"); |
---|
1035 | resultArray.add(output.toString()); |
---|
1036 | |
---|
1037 | } catch (Exception e) { |
---|
1038 | |
---|
1039 | Log.e("Error: ", e.getMessage()); |
---|
1040 | outputString = e.getMessage(); |
---|
1041 | |
---|
1042 | resultArray.add("1"); |
---|
1043 | resultArray.add(e.toString()); |
---|
1044 | |
---|
1045 | } |
---|
1046 | |
---|
1047 | //return null; |
---|
1048 | return resultArray; |
---|
1049 | |
---|
1050 | } |
---|
1051 | |
---|
1052 | protected void onProgressUpdate(String... progress) { |
---|
1053 | Log.d("ANDRO_ASYNC",progress[0]); |
---|
1054 | mProgressDialog.setProgress(Integer.parseInt(progress[0])); |
---|
1055 | } |
---|
1056 | |
---|
1057 | @Override |
---|
1058 | protected void onPostExecute(ArrayList<String> result) { |
---|
1059 | dismissDialog(DIALOG_DOWNLOAD_PROGRESS); |
---|
1060 | //Toast.makeText(getApplicationContext(), "onPostExecute: "+ result.get(0), Toast.LENGTH_LONG).show(); |
---|
1061 | |
---|
1062 | // ocurrio una excepcion |
---|
1063 | if (result.get(0).equals("1")){ |
---|
1064 | |
---|
1065 | //Toast.makeText(getApplicationContext(), "onPostExecute: dentro del if" , Toast.LENGTH_LONG).show(); |
---|
1066 | |
---|
1067 | // ocurrio un problema |
---|
1068 | AlertDialog.Builder builder = new AlertDialog.Builder(BDOCVerifyResultActivity.this); |
---|
1069 | |
---|
1070 | |
---|
1071 | builder.setMessage(result.get(1)).setTitle("Error al descargar el archivo"); |
---|
1072 | |
---|
1073 | builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { |
---|
1074 | public void onClick(DialogInterface dialog, int id) { |
---|
1075 | // User clicked OK button |
---|
1076 | |
---|
1077 | Log.d("***", "DownloadFileAsync().execute(urlhttps, true)"); |
---|
1078 | //Toast.makeText(getApplicationContext(), "DownloadFileAsync().execute(urlhttps, true)", Toast.LENGTH_LONG).show(); |
---|
1079 | // pasar como segundo argmento que se acepta que el sertivor es desconocido |
---|
1080 | new DownloadFileAsync().execute(urlhttps, "true"); |
---|
1081 | } |
---|
1082 | }); |
---|
1083 | builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() { |
---|
1084 | public void onClick(DialogInterface dialog, int id) { |
---|
1085 | // User cancelled the dialog |
---|
1086 | } |
---|
1087 | }); |
---|
1088 | AlertDialog dialog = builder.create(); |
---|
1089 | dialog.show(); |
---|
1090 | |
---|
1091 | }else{ |
---|
1092 | // no ocurrió excepcion |
---|
1093 | Toast.makeText(getApplicationContext(), "Se descargo correctamente el archivo", Toast.LENGTH_LONG).show(); |
---|
1094 | |
---|
1095 | } |
---|
1096 | |
---|
1097 | } |
---|
1098 | |
---|
1099 | |
---|
1100 | } // fin de la clase DownloadFileAsync |
---|
1101 | |
---|
1102 | // funcion para verificar un documento pdf |
---|
1103 | private void doPdfVerification(String pdfToVerify) { |
---|
1104 | |
---|
1105 | Intent intent = new Intent(this, PDFVerifyResultActivity.class); |
---|
1106 | |
---|
1107 | intent.putExtra("pdfToVerify", pdfToVerify); |
---|
1108 | |
---|
1109 | startActivity(intent); |
---|
1110 | |
---|
1111 | finish(); |
---|
1112 | |
---|
1113 | } // fin de doPdfVerification(String fileToVerify) |
---|
1114 | |
---|
1115 | |
---|
1116 | } |
---|
1117 | |
---|
1118 | |
---|
1119 | |
---|
1120 | |
---|