Changeset 99d1e61 in murachi for murachi/src/main/java/ve/gob/cenditel/murachi
- Timestamp:
- Aug 24, 2015, 5:33:29 PM (9 years ago)
- Branches:
- master
- Children:
- 6837e71
- Parents:
- f326ef1
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
murachi/src/main/java/ve/gob/cenditel/murachi/MurachiRESTWS.java
rf326ef1 r99d1e61 305 305 * 306 306 * @api {get} /Murachi/0.1/archivos/descargas/{id} Descarga un archivo 307 * @api description Descarga un archivo existente en el servidor307 * @apiDescription Descarga un archivo existente en el servidor 308 308 * @apiName Descargas 309 309 * @apiGroup Archivos … … 335 335 * @return archivo pasado como argumento del servidor 336 336 */ 337 337 /* 338 338 private Response downloadFileFromServer(String fileName) { 339 339 String fileLocation = SERVER_UPLOAD_LOCATION_FOLDER + fileName; … … 361 361 return response; 362 362 } 363 364 365 /* 363 */ 364 365 /** 366 * Descarga un archivo pasado como argumento del servidor 367 * @param fileName nombre o identificador del archivo que se desea descargar 368 * @return archivo pasado como argumento del servidor 369 */ 366 370 private Response downloadFileFromServer(String fileName) { 367 371 logger.info("downloadFileFromServer{"+fileName+"}"); … … 394 398 logger.debug("numero de firmas: "+ Integer.toString(c.getSignatures().size())); 395 399 396 397 // guardar el contenedor .bdoc 398 c.save(SERVER_UPLOAD_LOCATION_FOLDER + fileName + ".bdoc"); 399 logger.debug(" contenedor " + SERVER_UPLOAD_LOCATION_FOLDER + fileName + ".bdoc escrito en sistema de archivos"); 400 401 file = new File(SERVER_UPLOAD_LOCATION_FOLDER + fileName + ".bdoc"); 402 400 if (c.getSignatures().size() > 0) { 401 // guardar el contenedor .bdoc 402 c.save(SERVER_UPLOAD_LOCATION_FOLDER + fileName + ".bdoc"); 403 logger.debug(" contenedor " + SERVER_UPLOAD_LOCATION_FOLDER + fileName + ".bdoc escrito en sistema de archivos"); 404 405 file = new File(SERVER_UPLOAD_LOCATION_FOLDER + fileName + ".bdoc"); 406 } 407 else 408 { 409 // el contenedor no esta firmado por lo tanto no se puede descargar 410 logger.error(" error el contenedor no está firmado y no se puede descargar"); 411 412 //return Response.status(500).entity("{\"error\": \"el contenedor no esta firmado y no se puede descargar.\"}").build(); 413 return response = Response.status(500).entity("{\"error\": \"el contenedor no esta firmado y no se puede descargar.\"}").type("text/plain").build(); 414 } 403 415 } catch (ClassNotFoundException e) { 404 416 logger.error(" error ClassNotFoundException"); … … 422 434 fileName)); 423 435 424 response = Response.status(404).entity("{\"fileExist\": false}").436 return response = Response.status(404).entity("{\"fileExist\": false}"). 425 437 type("text/plain").build(); 426 438 } … … 437 449 return response; 438 450 } 439 */451 440 452 441 453 … … 1460 1472 } catch (InvalidKeyException e) { 1461 1473 logger.error("presignPdf ocurrio una excepcion ", e); 1462 e.printStackTrace();1474 //e.printStackTrace(); 1463 1475 //throw new MurachiException(e.getMessage()); 1464 1476 … … 1469 1481 } catch (NoSuchProviderException e) { 1470 1482 logger.error("presignPdf ocurrio una excepcion ", e); 1471 e.printStackTrace();1483 //e.printStackTrace(); 1472 1484 //throw new MurachiException(e.getMessage()); 1473 1485 … … 1478 1490 } catch (NoSuchAlgorithmException e) { 1479 1491 logger.error("presignPdf ocurrio una excepcion ", e); 1480 e.printStackTrace();1492 //e.printStackTrace(); 1481 1493 //throw new MurachiException(e.getMessage()); 1482 1494 … … 1487 1499 } catch (GeneralSecurityException e) { 1488 1500 logger.error("presignPdf ocurrio una excepcion ", e); 1489 e.printStackTrace();1501 //e.printStackTrace(); 1490 1502 //throw new MurachiException(e.getMessage()); 1491 1503 … … 1736 1748 } 1737 1749 1738 1739 // ******* BDOC *********************************************************** 1750 // ************************************************************************ 1751 // ************************************************************************ 1752 // ************************************************************************ 1753 // ************************************************************************ 1754 // ************************************************************************ 1755 // ************************************************************************ 1756 // ************************************************************************ 1757 // *********************************BDOC*********************************** 1740 1758 1741 1759 /** … … 1855 1873 return jsonSignatures; 1856 1874 } 1875 1876 /** 1877 * Retorna un JSON con informacion de las firmas del documento BDOC 1878 * @param serializedBDOC archivo BDOC serializado 1879 * @return JSON con informacion de las firmas del documento BDOC 1880 */ 1881 private JSONObject getSignaturesInformation(Container container) { 1882 1883 logger.debug("getSignaturesInformation()"); 1884 System.out.println("getSignaturesInformation()"); 1885 1886 JSONObject jsonSignatures = new JSONObject(); 1887 1888 JSONArray jsonSignaturesArray = new JSONArray(); 1889 JSONArray jsonContainerValidationExceptionArray = new JSONArray(); 1890 1891 //java.nio.file.Path path = Paths.get(serializedBDOC); 1892 //String idFile = path.getFileName().toString(); 1893 1894 1895 Security.addProvider(new BouncyCastleProvider()); 1896 //Container container = null; 1897 1898 Configuration configuration = new Configuration(Configuration.Mode.PROD); 1899 1900 configuration.loadConfiguration(DIGIDOC4J_CONFIGURATION); 1901 1902 configuration.setTslLocation(DIGIDOC4J_TSL_LOCATION); 1903 /* 1904 try 1905 { 1906 //container = Container.open(serializedBDOC, configuration); 1907 //logger.debug("Container.open("+serializedBDOC+", DIGIDOC4J_CONFIGURATION)"); 1908 container = deserialize(); 1909 1910 1911 } catch(DigiDoc4JException e) 1912 { 1913 jsonSignatures.put("error", "File is not a valid BDOC container"); 1914 return jsonSignatures; 1915 } 1916 */ 1917 1918 int numberOfSignatures = container.getSignatures().size(); 1919 if (numberOfSignatures == 0){ 1920 jsonSignatures.put("signatureNumber", "0"); 1921 System.out.println("signatureNumber: 0"); 1922 }else{ 1923 //jsonSignatures.put("fileExist", "true"); 1924 //System.out.println("fileExist: true"); 1925 1926 //jsonSignatures.put("fileId", idFile); 1927 //jsonSignatures.put("mimeType", "application/vnd.etsi.asic-e+zip"); 1928 1929 /* 1930 // informacion de archivos dentro del contenedor 1931 if (container.getDataFiles().size() > 0){ 1932 jsonSignatures.put("numberOfDataFiles", container.getDataFiles().size()); 1933 jsonSignatures.put("dataFiles", getJSONFromBDOCDataFiles(container.getDataFiles())); 1934 System.out.println(" dataFiles: " + getJSONFromBDOCDataFiles(container.getDataFiles()).toString()); 1935 }else{ 1936 System.out.println(" dataFiles: == 0"); 1937 } 1938 */ 1939 1940 jsonSignatures.put("numberOfSignatures", numberOfSignatures); 1941 1942 System.out.println("->container.validate()"); 1943 ValidationResult validationResult = container.validate(); 1944 System.out.println("...container.validate()"); 1945 1946 1947 List<DigiDoc4JException> exceptions = validationResult.getContainerErrors(); 1948 System.out.println("...validationResult.getContainerErrors()"); 1949 1950 boolean isDDoc = container.getDocumentType() == DocumentType.DDOC; 1951 1952 if (exceptions.size() > 0){ 1953 jsonSignatures.put("containerValidation", false); 1954 1955 for (DigiDoc4JException exception : exceptions) { 1956 JSONObject containerException = new JSONObject(); 1957 1958 if (isDDoc && isWarning(((DDocContainer) container).getFormat(), exception)){ 1959 System.out.println(" Warning: " + exception.toString()); 1960 1961 } 1962 else{ 1963 System.out.println((isDDoc ? " " : " Error_: ") + exception.toString()); 1964 1965 } 1966 containerException.put("containerValidationException", exception.toString()); 1967 jsonContainerValidationExceptionArray.put(containerException); 1968 } 1969 if (isDDoc && (((ValidationResultForDDoc) validationResult).hasFatalErrors())) { 1970 jsonSignatures.put("validationResultForDDocHasFatalErrors", true); 1971 return jsonSignatures; 1972 } 1973 jsonSignatures.put("containerValidationExceptions", jsonContainerValidationExceptionArray); 1974 1975 1976 }else{ 1977 jsonSignatures.put("containerValidation", true); 1978 1979 HashMap<String, String> signatureInformation; 1980 for (int i=0; i< numberOfSignatures; i++) { 1981 System.out.println("===== firma " + i + " ====="); 1982 signatureInformation = verifyBDOCSignature(container.getSignature(i), container.getDocumentType()); 1983 System.out.println("signatureInformation.size " + signatureInformation.size()); 1984 1985 JSONObject jo = getJSONFromASignature(signatureInformation); 1986 //System.out.println("jo: " + jo.toString()); 1987 jsonSignaturesArray.put(jo); 1988 } 1989 1990 jsonSignatures.put("signatures", jsonSignaturesArray); 1991 System.out.println(jsonSignatures.toString()); 1992 } 1993 } 1994 1995 return jsonSignatures; 1996 } 1997 1857 1998 1858 1999 /** … … 1977 2118 } 1978 2119 2120 // ************************************************************************ 2121 // ************************************************************************ 2122 // ************************************************************************ 2123 // ****************************RECURSOS BDOC******************************* 1979 2124 1980 2125 /** … … 2329 2474 } 2330 2475 2476 2477 // ******************************************************************************** 2478 // ******************************************************************************** 2331 2479 // ******************************************************************************** 2332 2480 // revision de recursos para que cada uno de ellos realice operaciones sobre un 2333 2481 // contenendor BDOC y siempre finalice con el contenedor serializado en el sistema 2334 2482 // de archivos 2335 2336 2337 2483 // ******************************************************************************** 2484 // ******************************************************************************** 2485 // ******************************************************************************** 2486 2487 2338 2488 /** 2339 2489 * Crea un contenedor BDOC con los archivos subidos del formulario, lo serializa y 2340 2490 * retorna el identificados unico del contenedor. 2341 2491 * 2342 * @param formParams parametros del formulario 2492 * @param formParams parametros del formulario. 2343 2493 * 2344 * @return identificador unico del contenedor creado 2494 * @return identificador unico del contenedor creado. 2495 * 2496 * 2497 * @api {post} /Murachi/0.1/archivos/bdocs/cargas Crea un contenedor BDOC. 2498 * @apiName BDocCargas 2499 * @apiGroup BDOCS 2500 * @apiVersion 0.1.0 2501 * @apiDescription Crea un contenedor BDOC con los archivos subidos 2502 * a través del formulario, serializa el contenedor y retorna el identificador único del mismo. 2503 * 2504 * @apiSuccess {String} containerId Identificador único del contenedor BDOC creado. 2505 * 2506 * @apiErrorExample {json} Error-Response: 2507 * HTTP/1.1 500 Internal Server Error 2508 * { 2509 * "error": "no se pudo crear el contenedor; falló la serialización." 2510 * } 2511 * 2345 2512 */ 2346 2513 @POST … … 2395 2562 2396 2563 result = "error al serializar el archivo"+fileId; 2397 result = "\"error\":\"no se pudo crear el contenedor \"";2564 result = "\"error\":\"no se pudo crear el contenedor; falló la serialización.\""; 2398 2565 return Response.status(500).entity(result).build(); 2399 2566 } … … 2413 2580 * 2414 2581 * @return identificador del contenedor 2582 * 2583 * 2584 * @api {post} /Murachi/0.1/archivos/bdocs/cargas/{containerId} Agrega archivo a contenedor. 2585 * @apiName BDocCargasAgrega 2586 * @apiGroup BDOCS 2587 * @apiVersion 0.1.0 2588 * @apiDescription Agrega el (los) archivo(s) subidos a través del formulario al 2589 * contenedor BDOC identificado por containerId, serializa el contenedor y retorna 2590 * el identificador único del mismo. 2591 * 2592 * @apiSuccess {String} containerId Identificador único del contenedor BDOC. 2593 * 2594 * @apiErrorExample {json} Error-Response: 2595 * HTTP/1.1 500 Internal Server Error 2596 * { 2597 * "error": "no se pudo agregar el archivo al contenedor." 2598 * } 2599 * 2415 2600 */ 2416 2601 @POST … … 2451 2636 2452 2637 c = deserialize(containerToOpen); 2638 2639 int signatureNumber = c.getSignatures().size(); 2640 logger.debug(" signatureNumber: "+ Integer.toString(signatureNumber)); 2641 2642 if (signatureNumber > 0) 2643 { 2644 // el archivo esta firmado y no se puede agregar un archivo adicional 2645 logger.error("el contenedor está firmado y no se puede eliminar el archivo."); 2646 return Response.status(200).entity("{\"error\": \"el contenedor está firmado y no se puede agregar archivo\"}").type("text/plain").build(); 2647 } 2648 2453 2649 2454 2650 Map<String, List<FormDataBodyPart>> fieldsByName = formParams.getFields(); … … 2471 2667 // se debe serializar no guardar 2472 2668 2473 String[] array = containerId.split("\\.bin");2669 //String[] array = containerId.split("\\.bin"); 2474 2670 2475 2671 // establecer el nombre del archivo a serializar … … 2505 2701 2506 2702 /** 2507 * Retorna el numero de dataFile que se encuentran en un contenedor 2703 * Retorna el numero de dataFile que se encuentran en un contenedor. 2508 2704 * 2509 2705 * @param containerId 2510 * @return 2706 * @return numero de archivos almacenados en el contenedor 2707 * 2708 * @api {get} /Murachi/0.1/archivos/bdocs/archivos/{containerId} Número de archivos de contenedor. 2709 * @apiName BDocNumeroDeArchivos 2710 * @apiGroup BDOCS 2711 * @apiVersion 0.1.0 2712 * 2713 * @apiParam {String} containerId identificador únicp del contenedor BDOC que se encuentra en el servidor. 2714 * 2715 * @apiDescription Retorna el número de archivos que se encuentran dentro del contendor BDOC. 2716 * 2717 * @apiSuccess {String} dataFileNumber Número de archivos que se encuentran en el contendor BDOC. 2718 * 2719 * @apiErrorExample {json} Error-Response: 2720 * HTTP/1.1 500 Internal Server Error 2721 * { 2722 * "error": "error interno al leer el contenedor." 2723 * } 2724 * HTTP/1.1 500 Internal Server Error 2725 * { 2726 * "error": "no se pudo leer el contenedor." 2727 * } 2728 * HTTP/1.1 404 Not Found 2729 * { 2730 * "error": "el contenedor con identificador containerId no existe ." 2731 * } 2732 * 2511 2733 */ 2512 2734 @GET … … 2576 2798 * se encuentran dentro de un contenedor se comienzan a identificar con cero (0). 2577 2799 * 2578 * @return 2579 * 2580 * @api {get} /Murachi/0.1/archivos/bdocs/archivos/{ fileId}/{dataFileId} Descarga un archivo del Contenedor2581 * @api description Descarga un archivo existente dentro del contenedor BDOC. Un contenedor BDOC puede tener uno2800 * @return archivo a descagar 2801 * 2802 * @api {get} /Murachi/0.1/archivos/bdocs/archivos/{containerId}/{dataFileId} Descarga un archivo del contenedor. 2803 * @apiDescription Descarga un archivo existente dentro del contenedor BDOC. Un contenedor BDOC puede tener uno 2582 2804 * o varios archivos. Los identificadores de archivos dentro de un contenedor BDOC se comienzan e enumerar con 2583 2805 * cero (0). 2584 2806 * 2585 * @apiName BDocsDescarga 2807 * @apiName BDocsDescargaArchivo 2586 2808 * @apiGroup BDOCS 2587 2809 * @apiVersion 0.1.0 2588 2810 * 2589 * @apiParam {String} fileId identificador del contenedor BDOC que se encuentra en el servidor2811 * @apiParam {String} containerId identificador del contenedor BDOC que se encuentra en el servidor 2590 2812 * @apiParam {Number} dataFileId identificador del archivo que se desea descargar. Los archivos que 2591 2813 * se encuentran dentro de un contenedor se comienzan a identificar con cero (0). 2814 * 2592 2815 * 2593 2816 * @apiExample Example usage: … … 2600 2823 * "fileExist": false 2601 2824 * } 2825 * HTTP/1.1 404 Not Found 2826 * { 2827 * "error": "el dataFileId solicitado no existe." 2828 * } 2829 * HTTP/1.1 500 Internal server Error 2830 * { 2831 * "error": "no se pudo leer el contenido del contenedor." 2832 * } 2833 * 2602 2834 */ 2603 2835 @GET … … 2675 2907 2676 2908 /** 2677 * Elimina un archivo DataFile de un contendor existente 2678 * 2679 * @param containerId identificador del contenedor para eliminar su dataFile 2909 * Elimina un archivo DataFile de un contendor existente. 2910 * 2911 * @param containerId identificador del contenedor para eliminar su dataFile. 2680 2912 * @return verificación de eliminación 2913 * 2914 * @api {get} /Murachi/0.1/archivos/bdocs/archivos/papelera/{containerId}/{dataFileId} Elimina un archivo del contenedor. 2915 * @apiDescription Elimina un archivo existente dentro del contenedor BDOC. Un contenedor BDOC puede tener uno 2916 * o varios archivos. Los identificadores de archivos dentro de un contenedor BDOC se comienzan e enumerar con 2917 * cero (0). Para poder eliminar un archivo de un contenedor no deben existir firmas. 2918 * 2919 * @apiName BDocsEliminaArchivos 2920 * @apiGroup BDOCS 2921 * @apiVersion 0.1.0 2922 * 2923 * @apiParam {String} containerId identificador del contenedor BDOC que se encuentra en el servidor. 2924 * @apiParam {Number} dataFileId identificador del archivo que se desea eliminar. Los archivos que 2925 * se encuentran dentro de un contenedor se comienzan a identificar con cero (0). 2926 * 2927 * @apiSuccess {String} mensaje archivo eliminado correctamente 2928 * 2929 * @apiExample Example usage: 2930 * curl -i https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/bdocs/archivos/papelera/f011ff87-f0d0-4a5e-a0b9-a64eb70661ee/0 2931 * 2932 * 2933 * @apiErrorExample {json} Error-Response: 2934 * HTTP/1.1 404 Not Found 2935 * { 2936 * "fileExist": false 2937 * } 2938 * HTTP/1.1 500 Internal server Error 2939 * { 2940 * "error": "no se pudo leer el contenido del contenedor." 2941 * } 2942 * 2681 2943 */ 2682 2944 @GET … … 2776 3038 2777 3039 /** 2778 * Retorna lista de los dataFile que se encuentran en un contenedor 2779 * 2780 * @param containerId identificador del contenedor 2781 * @return lista de los dataFile que se encuentran en un contenedor 3040 * Retorna lista de los dataFile que se encuentran en un contenedor. 3041 * 3042 * @param containerId identificador del contenedor. 3043 * @return lista de los dataFile que se encuentran en un contenedor. 3044 * 3045 * @api {get} /Murachi/0.1/archivos/bdocs/archivos/lista/{containerId} Lista de archivos del contenedor. 3046 * @apiDescription Retorna una lista de los archivos que se encuentran dentro del contenedor BDOC. 3047 * 3048 * @apiName BDocsListaArchivos 3049 * @apiGroup BDOCS 3050 * @apiVersion 0.1.0 3051 * 3052 * @apiParam {String} containerId identificador del contenedor BDOC que se encuentra en el servidor. 3053 * 3054 * @apiSuccess {String} dataFiles lista de archivos que se encuentran en el contenedor. 3055 * 3056 * @apiExample Example usage: 3057 * curl -i https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/bdocs/archivos/lista/f011ff87-f0d0-4a5e-a0b9-a64eb70661ee 3058 * 3059 * 3060 * @apiErrorExample {json} Error-Response: 3061 * HTTP/1.1 404 Not Found 3062 * { 3063 * "error": "El contenedor con identificador containerId no existe." 3064 * } 3065 * HTTP/1.1 500 Internal server Error 3066 * { 3067 * "error": "no se pudo leer el contenido del contenedor." 3068 * } 3069 * HTTP/1.1 500 Internal server Error 3070 * { 3071 * "error": "El contenedor tiene un número menor que cero de archivos." 3072 * } 3073 * 2782 3074 */ 2783 3075 @GET … … 2810 3102 String dataFileName = ""; 2811 3103 Long dataFileSize = (long) 0; 2812 2813 2814 3104 2815 3105 try { 2816 3106 c = deserialize(fullPathBdocFile); … … 2847 3137 response = Response.status(200).entity(jsonDataFile.toString()).build(); 2848 3138 } 2849 else 3139 else if (dataFileNumber == 0) 2850 3140 { 2851 3141 logger.debug("dataFileNumber: "+ Integer.toString(dataFileNumber)); 2852 3142 jsonDataFile.put("dataFileNumber", Integer.toString(dataFileNumber)); 2853 3143 response = Response.status(200).entity(jsonDataFile.toString()).build(); 2854 } 3144 } 3145 else 3146 { 3147 logger.error("El contenedor con id: "+containerId+ " tiene un número menor que cero de dataFiles."); 3148 jsonDataFile.put("error", "El contenedor tiene un número menor que cero de archivos"); 3149 response = Response.status(500).entity(jsonDataFile.toString()).build(); 3150 } 2855 3151 2856 3152 2857 3153 } else { 2858 3154 logger.error("El contenedor con id: "+containerId+ " no existe."); 2859 jsonDataFile.put("error", "El contenedor con id :"+containerId+ " no existe.");3155 jsonDataFile.put("error", "El contenedor con identificador "+containerId+ " no existe."); 2860 3156 response = Response.status(404).entity(jsonDataFile.toString()).build(); 2861 3157 } … … 2866 3162 2867 3163 /** 2868 * Retorna el numero de firmas que tiene en un contenedor 2869 * 2870 * @param containerId 2871 * @return numero de firmas del contenedor 3164 * Retorna el numero de firmas que tiene en un contenedor. 3165 * 3166 * @param containerId identificador del contenedor BDOC. 3167 * @return numero de firmas del contenedor. 3168 * 3169 * @api {get} /Murachi/0.1/archivos/bdocs/firmas/{containerId} Número de firmas de un contenedor. 3170 * @apiName BDocNumeroFirmas 3171 * @apiGroup BDOCS 3172 * @apiVersion 0.1.0 3173 * 3174 * @apiParam {String} containerId identificador único del contenedor BDOC que se encuentra en el servidor. 3175 * 3176 * @apiDescription Retorna el número de firmas del contendor BDOC. 3177 * 3178 * @apiSuccess {String} signatureNumber Número de firmas del contendor BDOC. 3179 * 3180 * @apiErrorExample {json} Error-Response: 3181 * HTTP/1.1 500 Internal Server Error 3182 * { 3183 * "error": "error interno al leer el contenedor." 3184 * } 3185 * HTTP/1.1 404 Not Found 3186 * { 3187 * "error": "el contenedor con identificador containerId no existe ." 3188 * } 2872 3189 */ 2873 3190 @GET … … 2933 3250 * @param signatureId identificador de la firma a eliminar 2934 3251 * 2935 * @return identificador del contenedor 3252 * @return identificador del contenedor. 3253 * 3254 * * @api {get} /Murachi/0.1/archivos/bdocs/firmas/papelera{containerId}/{signatureId} Elimina una firma de un contenedor. 3255 * @apiName BDocEliminaFirmas 3256 * @apiGroup BDOCS 3257 * @apiVersion 0.1.0 3258 * 3259 * @apiParam {String} containerId identificador único del contenedor BDOC que se encuentra en el servidor. 3260 * @apiParam {Number} signatureId identificador de firma a eliminar. 3261 * 3262 * @apiDescription Elimina una firma del contendor BDOC. 3263 * 3264 * @apiSuccess {String} mensaje firma eliminada correctamente 3265 * 3266 * @apiErrorExample {json} Error-Response: 3267 * HTTP/1.1 500 Internal Server Error 3268 * { 3269 * "error": "no se pudo leer el contenido del contenedor." 3270 * } 3271 * HTTP/1.1 404 Not Found 3272 * { 3273 * "error": "el contenedor con identificador containerId no existe ." 3274 * } 3275 * 2936 3276 */ 2937 3277 @GET … … 2983 3323 if (signatureNumber < 1) 2984 3324 { 2985 // el archivo esta firmado y no se puede eliminar el dataFile3325 // el archivo no esta firmado y no se puede eliminar la firma 2986 3326 response = Response.status(200).entity("{\"error\": \"el contenedor no está firmado\"}").type("text/plain").build(); 2987 3327 logger.error("el contenedor no está firmado."); … … 2991 3331 if (signatureId >= signatureNumber) 2992 3332 { 2993 // el dataFileId no es valido3333 // el signatureId no es valido 2994 3334 response = Response.status(200).entity("{\"error\": \"el identificador de la firma a eliminar no es valido\"}").type("text/plain").build(); 2995 3335 logger.error("el identificador de la firma a eliminar no es valido."); … … 3023 3363 3024 3364 } 3025 3026 // ------------> a seguir 3027 3365 3366 3367 /** 3368 * Retorna una lista con información de las firmas que tiene en un contenedor. 3369 * 3370 * @param containerId identificador del contenedor BDOC. 3371 * @return lista con información de las firmas que tiene en un contenedor. 3372 * 3373 * @api {get} /Murachi/0.1/archivos/bdocs/firmas/lista/{containerId} Lista de firmas de un contenedor. 3374 * @apiName BDocListaFirmas 3375 * @apiGroup BDOCS 3376 * @apiVersion 0.1.0 3377 * 3378 * @apiParam {String} containerId identificador único del contenedor BDOC que se encuentra en el servidor. 3379 * 3380 * @apiDescription Retorna una lista con la información de las firmas del contendor BDOC. 3381 * 3382 * @apiSuccess {Number} numberOfSignatures Número de firmas existentes en el archivo. 3383 * @apiSuccess {Object[]} signatures Lista de firmas del contenedor BDOC 3384 * @apiSuccess {String} signatures.signaturePostalCode Código postal del lugar donde se realiza la firma. 3385 * @apiSuccess {String} signatures.signerCertificateSerial Serial del certificado del firmante. 3386 * @apiSuccess {String} signatures.signatureState Estado del lugar donde se realiza la firma. 3387 * @apiSuccess {String} signatures.signatureProfile Perfil de la firma. 3388 * @apiSuccess {String} signatures.signatureMethod Algoritmo de firma utilizado. 3389 * @apiSuccess {String} signatures.signatureId identificador de la firma. 3390 * @apiSuccess {String} signatures.signatureSigningTime Hora y fecha en que se realiza la firma. 3391 * @apiSuccess {Boolean} signatures.signerCertificateIsValid El certificado firmante es válido. 3392 * @apiSuccess {String} signatures.signerCertificateIssuer Emisor del certificado firmante. 3393 * @apiSuccess {String} signatures.signatureCity Ciudad donde se realiza la firma. 3394 * @apiSuccess {String} signatures.signatureValidationException Exepciones de la validación de la firma. 3395 * @apiSuccess {String} signatures.isValid Firma electrónica válida. 3396 * @apiSuccess {String} signatures.signerCertificateIssuer Emisor del certificado firmante. 3397 * @apiSuccess {String} signatures.signatureCountry País donde se realiza la firma. 3398 * 3399 * @apiSuccess {Boolean} containerValidation: Especifica si el contenedor posee una estructura válida. 3400 3401 * 3402 * @apiErrorExample {json} Error-Response: 3403 * HTTP/1.1 500 Internal Server Error 3404 * { 3405 * "error": "error interno al leer el contenedor." 3406 * } 3407 * HTTP/1.1 500 Internal Server Error 3408 * { 3409 * "error": "El contenedor tiene un número menor que cero de firmas" 3410 * } 3411 3412 * HTTP/1.1 404 Not Found 3413 * { 3414 * "error": "el contenedor con identificador containerId no existe ." 3415 * } 3416 */ 3417 @GET 3418 @Path("/bdocs/firmas/lista/{containerId}") 3419 @Produces(MediaType.APPLICATION_JSON) 3420 public Response getSignaturesList(@PathParam("containerId") String containerId) { 3421 logger.info("/bdocs/firmas/lista/"+containerId); 3422 3423 String fullPathBdocFile = SERVER_UPLOAD_LOCATION_FOLDER + containerId + "-serialized.bin"; 3424 logger.debug(fullPathBdocFile); 3425 3426 3427 JSONObject jsonSignatures = new JSONObject(); 3428 int signatureNumber = 0; 3429 3430 Response response; 3431 3432 // Retrieve the file 3433 File file = new File(fullPathBdocFile); 3434 if (file.exists()) { 3435 3436 Security.addProvider(new BouncyCastleProvider()); 3437 3438 Configuration configuration = new Configuration(Configuration.Mode.PROD); 3439 configuration.loadConfiguration(DIGIDOC4J_CONFIGURATION); 3440 configuration.setTslLocation(DIGIDOC4J_TSL_LOCATION); 3441 3442 Container c; 3443 3444 try { 3445 c = deserialize(fullPathBdocFile); 3446 3447 signatureNumber = c.getSignatures().size(); 3448 3449 logger.debug("signatureNumber: "+ Integer.toString(signatureNumber)); 3450 3451 if (signatureNumber > 0) { 3452 jsonSignatures = getSignaturesInformation(c); 3453 } 3454 else if(signatureNumber == 0) 3455 { 3456 logger.debug("numberOfSignatures: "+ Integer.toString(signatureNumber)); 3457 jsonSignatures.put("numberOfSignatures", Integer.toString(signatureNumber)); 3458 response = Response.status(200).entity(jsonSignatures.toString()).build(); 3459 } 3460 else 3461 { 3462 logger.error("El contenedor con id: "+containerId+ " tiene un número menor que cero de firmas."); 3463 jsonSignatures.put("error", "El contenedor tiene un número menor que cero de firmas"); 3464 response = Response.status(500).entity(jsonSignatures.toString()).build(); 3465 } 3466 3467 response = Response.status(200).entity(jsonSignatures.toString()).build(); 3468 3469 } catch (ClassNotFoundException e) { 3470 3471 jsonSignatures.put("error", "error interno al leer el contenedor"); 3472 response = Response.status(500).entity(jsonSignatures.toString()).build(); 3473 3474 } catch (IOException e) { 3475 3476 jsonSignatures.put("error", "no se pudo leer el contenedor"); 3477 response = Response.status(500).entity(jsonSignatures.toString()).build(); 3478 } 3479 } else { 3480 logger.error("El contenedor con id: "+containerId+ " no existe."); 3481 jsonSignatures.put("error", "El contenedor con id: "+containerId+ " no existe."); 3482 response = Response.status(404).entity(jsonSignatures.toString()).build(); 3483 } 3484 return response; 3485 } 3028 3486 3029 3487 … … 3035 3493 * @return hash del archivo a firmar del lado del cliente. 3036 3494 * @throws MurachiException 3495 * 3496 * @api {post} /Murachi/0.1/archivos/bdocs/firmas/pre Prepara la firma de un contenedor BDOC. 3497 * @apiName BDocsFirmasPre 3498 * @apiGroup BDOCS 3499 * @apiVersion 0.1.0 3500 * @apiDescription Prepara la firma de un contenedor BDOC existente en el servidor. 3501 * Se debe pasar un JSON con la siguiente estructura: 3502 * 3503 * {"fileId":"file_id", "certificate":"hex_cert_value", 3504 * "city":"ciudad", "state":"estado", "postalCode":"codigoPostal", 3505 * "country":"pais", "role":"rol"} 3506 * 3507 * fileId: corresponde al identificador del contenedor que se encuentra en el servidor y se desea firmar. 3508 * 3509 * certificate: corresponde al certificado del firmante en formato hexadecimal. 3510 * 3511 * city: corresponde a la ciudad en la que se realiza la firma. 3512 * 3513 * state: corresponde al estado en el que se reailza la firma. 3514 * 3515 * postalCode: corresponde al código postal del lugar donde se realiza la firma. 3516 * 3517 * country: corresponde al país donde se realiza la firma. 3518 * 3519 * role: corresponde al rol del firmante. 3520 * 3521 * @apiSuccess {String} hash Reseña o hash del contenedor que se debe cifrar con la clave privada protegida por el 3522 * dispositivo criptográfico. 3523 * 3524 * @apiExample Example usage: 3525 * 3526 * var parameters = JSON.stringify({ 3527 * "fileId":fileId, 3528 * "certificate":cert.hex, 3529 * "city":"Merida", 3530 * "state":"Merida", 3531 * "postalCode":"5101", 3532 * "country":"Venezuela", 3533 * "role":"Desarrollador" 3534 * }); 3535 * 3536 * $.ajax({ 3537 * url: "https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/bdocs/firmas/pre", 3538 * type: "post", 3539 * dataType: "json", 3540 * data: parameters, 3541 * contentType: "application/json", 3542 * success: function(data, textStatus, jqXHR){ 3543 * var json_x = data; 3544 * var hash = json_x['hash']; 3545 * alert("hash recibido del servidor "+hash); 3546 * }, 3547 * error: function(jqXHR, textStatus, errorThrown){ 3548 * //alert('error: ' + textStatus); 3549 * //var responseText = jQuery.parseJSON(jqXHR.responseText); 3550 * alert('ajax error function: ' + jqXHR.responseText); 3551 * 3552 * } 3553 * }); 3554 * 3555 * 3556 * 3557 * @apiErrorExample {json} Error-Response: 3558 * HTTP/1.1 500 Internal Server Error 3559 * { 3560 * "hash": "", 3561 * "error": "Error en el certificado del firmante" 3562 * } 3563 * HTTP/1.1 404 Not Found 3564 * { 3565 * "error": "el contenedor con identificador containerId no existe ." 3566 * } 3567 * 3568 * 3037 3569 */ 3038 3570 @POST … … 3046 3578 PresignHash presignHash = new PresignHash(); 3047 3579 3048 // obtener el id del archivo a firma er3580 // obtener el id del archivo a firmar 3049 3581 String containerId = presignPar.getFileId(); 3050 3582 … … 3068 3600 logger.debug(" role: " + role); 3069 3601 3070 Boolean addSignature = presignPar.getAddSignature();3071 logger.debug(" addSignature: " + addSignature.toString());3602 //Boolean addSignature = presignPar.getAddSignature(); 3603 //logger.debug(" addSignature: " + addSignature.toString()); 3072 3604 3073 3605 CertificateFactory cf; … … 3102 3634 try 3103 3635 { 3636 /* 3104 3637 Security.addProvider(new BouncyCastleProvider()); 3105 3638 Container container = null; … … 3151 3684 serialize(container, serializedContainerId); 3152 3685 logger.debug("serializado el contenedor: " + serializedContainerId); 3686 */ 3687 3688 3689 Security.addProvider(new BouncyCastleProvider()); 3690 Container container = null; 3691 3692 Configuration configuration = new Configuration(Configuration.Mode.PROD); 3693 configuration.loadConfiguration(DIGIDOC4J_CONFIGURATION); 3694 configuration.setTslLocation(DIGIDOC4J_TSL_LOCATION); 3695 3696 3697 // deserializar el contenedor 3698 //container = deserialize(fullPathContainerId); 3699 container = deserializer1(fullPathContainerId); 3700 3701 logger.debug("deserializado el contenedor: " + fullPathContainerId); 3702 3703 3704 SignatureParameters signatureParameters = new SignatureParameters(); 3705 SignatureProductionPlace productionPlace = new SignatureProductionPlace(); 3706 productionPlace.setCity(city); 3707 productionPlace.setStateOrProvince(state); 3708 productionPlace.setPostalCode(postalCode); 3709 productionPlace.setCountry(country); 3710 signatureParameters.setProductionPlace(productionPlace); 3711 logger.debug("container setProductionPlace"); 3712 3713 signatureParameters.setRoles(asList(role)); 3714 container.setSignatureParameters(signatureParameters); 3715 container.setSignatureProfile(SignatureProfile.B_BES); 3716 3717 cf = CertificateFactory.getInstance("X.509"); 3718 3719 InputStream in = new ByteArrayInputStream(hexStringToByteArray(certHex)); 3720 3721 signerCert = (X509Certificate) cf.generateCertificate(in); 3722 3723 signedInfo = container.prepareSigning(signerCert); 3724 3725 hashToSign = byteArrayToHexString(signedInfo.getDigest()); 3726 3727 System.out.println("presignBdoc - hash: " + hashToSign); 3728 logger.debug("hash to sign: " + hashToSign); 3729 3730 3731 //String[] array = containerId.split("\\.bin"); 3732 3733 // establecer el nombre del archivo a serializar 3734 String serializedContainerId = SERVER_UPLOAD_LOCATION_FOLDER + containerId + "-serialized"; 3735 logger.debug("serializedContainerId: " + serializedContainerId); 3736 3737 // serializar el archivo 3738 serialize(container, serializedContainerId); 3739 logger.debug("serializado el contenedor: " + serializedContainerId); 3740 3741 3153 3742 3154 3743 } catch(IOException e) … … 3191 3780 * @throws IOException 3192 3781 * @throws MurachiException 3782 * 3783 * @api {post} /Murachi/0.1/archivos/firmados/bdocs/resenas Completa la firma de un contenedor BDOC. 3784 * @apiName BdocFirmasPost 3785 * @apiGroup BDOCS 3786 * @apiVersion 0.1.0 3787 * @apiDescription Completa la firma de un contenedor BDOC. Recibe el hash cifrado del cliente y 3788 * completa la firma del contenedor BDOC. 3789 * 3790 * @apiSuccess {String} signedFileId Identificador único del contenedor firmado en el servidor. 3791 * 3792 * @apiExample Example usage: 3793 * 3794 * $.ajax({ 3795 * url: "https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/bdocs/firmas/post", 3796 * type: "post", 3797 * dataType: "json", 3798 * data: JSON.stringify({ 3799 * "signature":signature.hex, 3800 * "containerId":"351d6f62-4653-48d8-8a41-6145b53f3921" 3801 * }), 3802 * contentType: "application/json", 3803 * success: function(data, textStatus, jqXHR){ 3804 * alert('Archivo firmado correctamente: ' + data['signedFileId']); 3805 * }, 3806 * error: function(jqXHR, textStatus, errorThrown){ 3807 * alert('error en pdfs/resenas: ' + textStatus); 3808 * } 3809 * }); 3810 * 3811 * 3812 * 3813 * @apiErrorExample {json} Error-Response: 3814 * HTTP/1.1 500 Internal Server Error 3815 * { 3816 * "error": "Error en proceso de deserialización y completación de firma" 3817 * } 3818 * HTTP/1.1 404 Not Found 3819 * { 3820 * "error": "el contenedor con identificador containerId no existe ." 3821 * } 3822 * 3193 3823 */ 3194 3824 @POST … … 3216 3846 logger.debug(" serializedContainerId: " + serializedContainerId); 3217 3847 3848 File f = new File(serializedContainerId); 3849 3850 if (!f.exists()) { 3851 logger.error("el contenedor "+ serializedContainerId + " no existe."); 3852 String result = "\"error\":\"el contenedor "+ serializedContainerId + " no existe\""; 3853 return Response.status(404).entity(result).build(); 3854 } 3855 3218 3856 try { 3219 3857 Container deserializedContainer = deserialize(serializedContainerId); 3220 3858 logger.debug(" deserializado el contenedor "+ serializedContainerId); 3221 3859 3860 /* 3861 if (deserializedContainer.getSignatures().size() > 0) { 3862 ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); 3863 deserializedContainer.save(byteOut); 3864 ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray()); 3865 3866 //Configuration configuration = initConfig(); // also need to re-initialize configuration settings 3867 3868 Configuration configuration = new Configuration(Configuration.Mode.PROD); 3869 configuration.loadConfiguration(DIGIDOC4J_CONFIGURATION); 3870 configuration.setTslLocation(DIGIDOC4J_TSL_LOCATION); 3871 3872 Container container2 = Container.open(byteIn, configuration); 3873 3874 byteOut.close(); 3875 byteIn.close(); 3876 //container2.sign(new PKCS12Signer("/tmp/ayzarra.p12", "ayzarra".toCharArray())); 3877 3878 byte[] signatureInBytes = hexStringToByteArray(signature); 3879 3880 container2.signRaw(signatureInBytes); 3881 logger.debug("asignada firma al contenedor previamente firmado"); 3882 3883 System.out.println("********numero de firmas deserialize : "+ Integer.toString(container2.getSignatures().size())); 3884 3885 serialize(container2, SERVER_UPLOAD_LOCATION_FOLDER + containerId + "-serialized"); 3886 logger.debug(" serializado el contenedor: " + SERVER_UPLOAD_LOCATION_FOLDER + containerId + "-serialized"); 3887 3888 } 3889 else 3890 { 3891 // el contenedor no tiene firmas previas 3892 byte[] signatureInBytes = hexStringToByteArray(signature); 3893 3894 deserializedContainer.signRaw(signatureInBytes); 3895 logger.debug("asignada firma al contenedor sin firmas previas"); 3896 3897 serialize(deserializedContainer, SERVER_UPLOAD_LOCATION_FOLDER + containerId + "-serialized"); 3898 logger.debug(" serializado el contenedor: " + SERVER_UPLOAD_LOCATION_FOLDER + containerId + "-serialized"); 3899 } 3900 */ 3901 3222 3902 byte[] signatureInBytes = hexStringToByteArray(signature); 3223 3903 3224 3904 deserializedContainer.signRaw(signatureInBytes); 3225 logger.debug("asignada firma al contenedor"); 3905 logger.debug("asignada firma al contenedor " + containerId ); 3906 3907 serialize(deserializedContainer, SERVER_UPLOAD_LOCATION_FOLDER + containerId + "-serialized"); 3908 logger.debug(" serializado el contenedor: " + SERVER_UPLOAD_LOCATION_FOLDER + containerId + "-serialized"); 3909 3910 3911 3226 3912 3227 3913 /* … … 3231 3917 */ 3232 3918 3233 3919 /* 3234 3920 // prueba para evitar que las firmas tengan la misma hora de aplicacion 3235 3921 … … 3247 3933 serialize(c, SERVER_UPLOAD_LOCATION_FOLDER + containerId + "-serialized"); 3248 3934 logger.debug(" serializado contenedor: " + SERVER_UPLOAD_LOCATION_FOLDER + containerId + "-serialized"); 3935 */ 3936 3937 3938 //c.save(SERVER_UPLOAD_LOCATION_FOLDER + containerId + ".bdoc"); 3249 3939 3250 3940 // eliminar el contenedor guardado … … 3273 3963 3274 3964 JSONObject jsonFinalResult = new JSONObject(); 3275 jsonFinalResult.put("signedFileId", containerId +".bdoc");3965 jsonFinalResult.put("signedFileId", containerId); 3276 3966 3277 3967 logger.info(jsonFinalResult.toString()); … … 3354 4044 } 3355 4045 4046 @GET 4047 @Path("/serializar") 4048 @Produces("text/plain") 4049 public String serialize() { 4050 4051 logger.debug("recurso /serializar"); 4052 4053 Security.addProvider(new BouncyCastleProvider()); 4054 4055 Container c; 4056 try { 4057 c = deserialize("/tmp/container.bin"); 4058 logger.debug("deserializado contenedor"); 4059 4060 logger.debug("numero de firmas: "+ Integer.toString(c.getSignatures().size())); 4061 4062 Security.addProvider(new BouncyCastleProvider()); 4063 4064 //c.sign(new PKCS12Signer("/tmp/ayzarra.p12", "ayzarra".toCharArray())); 4065 4066 //c.save("/tmp/deserializado.bdoc"); 4067 4068 if (c.getSignatures().size() > 0) { 4069 ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); 4070 c.save(byteOut); 4071 ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray()); 4072 4073 //Configuration configuration = initConfig(); // also need to re-initialize configuration settings 4074 4075 Configuration configuration = new Configuration(Configuration.Mode.PROD); 4076 configuration.loadConfiguration("/tmp/digidoc4j.yaml"); 4077 configuration.setTslLocation("file:///tmp/venezuela-tsl.xml"); 4078 4079 Container container2 = Container.open(byteIn, configuration); 4080 container2.sign(new PKCS12Signer("/tmp/ayzarra.p12", "ayzarra".toCharArray())); 4081 4082 System.out.println("********numero de firmas deserialize : "+ Integer.toString(container2.getSignatures().size())); 4083 container2.save("/tmp/deserializado2.bdoc"); 4084 4085 } 4086 4087 4088 4089 } catch (ClassNotFoundException | IOException e) { 4090 e.printStackTrace(); 4091 4092 logger.error("ClassNotFoundException | IOException e"); 4093 return "error ClassNotFoundException | IOException e"; 4094 4095 } 4096 4097 4098 return "prueba exitosa"; 4099 } 4100 3356 4101 3357 4102 /** … … 3422 4167 } 3423 4168 4169 /** 4170 * Agrega un archivo a un contenedor BDOC existente 4171 * @param is InputStream del archivo 4172 * @param fileName ruta del archivo que se desea agregar 4173 * @param mimeType tipo mime 4174 * @param c contenedor BDOC 4175 */ 3424 4176 private void addFileToBDOCContainer(InputStream is, String fileName, String mimeType, Container c) { 3425 4177 logger.debug("addFileToBDOCContainer(InputStream) "); … … 3688 4440 3689 4441 } catch (IOException e) { 3690 // TODO Auto-generated catch block 4442 3691 4443 e.printStackTrace(); 3692 4444 } … … 4571 5323 } 4572 5324 5325 /** 5326 * Deserializa el contenedor BDOC pasado como argumento. Verifica si el contenedor está 5327 * firmado para escribirlo y leerlo de nuevo. 5328 * @param filePath ruta absoluta al contenedor que se desea deserializar 5329 * @return contenedor deserializado 5330 * @throws IOException 5331 * @throws ClassNotFoundException 5332 * 5333 */ 5334 private Container deserializer1(String filePath) throws IOException, ClassNotFoundException { 5335 //FileInputStream fileIn = new FileInputStream("container.bin"); 5336 FileInputStream fileIn = new FileInputStream(filePath); 5337 ObjectInputStream in = new ObjectInputStream(fileIn); 5338 Container container = (Container) in.readObject(); 5339 in.close(); 5340 fileIn.close(); 5341 5342 if (container.getSignatures().size() > 0) { 5343 ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); 5344 container.save(byteOut); 5345 ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray()); 5346 5347 //Configuration configuration = initConfig(); // also need to re-initialize configuration settings 5348 Configuration configuration = new Configuration(Configuration.Mode.PROD); 5349 configuration.loadConfiguration(DIGIDOC4J_CONFIGURATION); 5350 configuration.setTslLocation(DIGIDOC4J_TSL_LOCATION); 5351 Container container2 = Container.open(byteIn, configuration); 5352 5353 byteOut.close(); 5354 byteIn.close(); 5355 return container2; 5356 } else { 5357 return container; 5358 } 5359 } 5360 4573 5361 }
Note: See TracChangeset
for help on using the changeset viewer.