Index: murachi/src/main/java/ve/gob/cenditel/murachi/MurachiRESTWS.java
===================================================================
--- murachi/src/main/java/ve/gob/cenditel/murachi/MurachiRESTWS.java	(revision 99d1e61cb5cdabc54ff8d0bbe1f710ae5c19cf3d)
+++ murachi/src/main/java/ve/gob/cenditel/murachi/MurachiRESTWS.java	(revision 276a8db41d99a15513edf8e2096ad7a1f0039904)
@@ -3,19 +3,15 @@
 import static java.util.Arrays.asList;
 
-import java.io.BufferedReader;
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
-import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
-import java.io.InputStreamReader;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 import java.io.OutputStream;
 import java.net.URISyntaxException;
-import java.net.URL;
 import java.nio.file.Files;
 import java.nio.file.Paths;
@@ -3970,133 +3966,5 @@
 	
 	
-	
-	// ************************************************************************
-	// ************************************************************************
-	// ************************************************************************
-
-	// pruebas de funciones para gestionar un contenedor BDOC
-	
-	@GET
-	@Path("/pruebaBDOC")
-	@Produces("text/plain")
-	public String testBDOCFunctions()  {
-		
-		Security.addProvider(new BouncyCastleProvider());
-		
-		Container c = createBDOCContainer();
-		
-		String containerId = UUID.randomUUID().toString();
-		System.out.println(containerId);
-		
-		if (c==null)
-		{
-			System.out.println("container == null");
-		}
-		else
-		{
-			System.out.println("container != null");
-		}
-		
-		addFileToBDOCContainer("/tmp/slides-93-cfrg-9.pdf", c);
-		
-		System.out.println("numero de archivos en el contenedor: " + Integer.toString(c.getDataFiles().size()));
-		
-		PKCS12Signer PKCS12_SIGNER = new PKCS12Signer("/tmp/tibisay.p12", "123456".toCharArray());
-		
-		SignatureParameters signatureParameters = new SignatureParameters();
-		SignatureProductionPlace productionPlace = new SignatureProductionPlace();
-		productionPlace.setCity("Merida");
-		productionPlace.setStateOrProvince("Merida");
-		productionPlace.setPostalCode("5101");
-		productionPlace.setCountry("Venezuela");
-		signatureParameters.setProductionPlace(productionPlace);
-		logger.debug("container setProductionPlace");
-		signatureParameters.setRoles(asList("Desarrollador"));
-		c.setSignatureParameters(signatureParameters);
-		c.setSignatureProfile(SignatureProfile.B_BES);
-		
-		c.sign(PKCS12_SIGNER);
-		
-		
-		if (deleteDataFileFromBDOCContainer("/tmp/slides-93-cfrg-9.pdf", c))
-		{
-			System.out.println("eliminado archivo del contenedor");
-		}
-		else
-		{
-			System.out.println("NO se eliminó el archivo del contenedor");
-		}
-			
-		if (deleteSignatureFromBDOCContainer(0, c))
-		{
-			System.out.println("SE ELIMINO la firma 2");
-		}
-		else
-		{
-			System.out.println("no se pudo eliminar la firma 0");
-		}
-		
-		System.out.println("numero de firmas restantes: "+ Integer.toString(c.getSignatures().size()));
-		
-		c.save("/tmp/prueba.bdoc");
-		
-		return "prueba exitosa";
-	}
-	
-	@GET
-	@Path("/serializar")
-	@Produces("text/plain")
-	public String serialize()  {
-		
-		logger.debug("recurso /serializar");
-		
-		Security.addProvider(new BouncyCastleProvider());
-		
-		Container c;
-		try {
-			c = deserialize("/tmp/container.bin");
-			logger.debug("deserializado contenedor");
-			
-			logger.debug("numero de firmas: "+ Integer.toString(c.getSignatures().size()));
-			
-			Security.addProvider(new BouncyCastleProvider());
-			
-			//c.sign(new PKCS12Signer("/tmp/ayzarra.p12", "ayzarra".toCharArray()));
-						
-			//c.save("/tmp/deserializado.bdoc");
-			
-			if (c.getSignatures().size() > 0) {
-		    	ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
-		        c.save(byteOut);
-		        ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
-		        
-		        //Configuration configuration = initConfig(); // also need to re-initialize configuration settings
-		        
-		        Configuration configuration = new Configuration(Configuration.Mode.PROD);		
-		    	configuration.loadConfiguration("/tmp/digidoc4j.yaml");
-		    	configuration.setTslLocation("file:///tmp/venezuela-tsl.xml");        
-		        
-		        Container container2 = Container.open(byteIn, configuration);
-		        container2.sign(new PKCS12Signer("/tmp/ayzarra.p12", "ayzarra".toCharArray()));
-		        
-		        System.out.println("********numero de firmas deserialize : "+ Integer.toString(container2.getSignatures().size()));
-		        container2.save("/tmp/deserializado2.bdoc");
-
-		    }
-			
-			
-			
-		} catch (ClassNotFoundException | IOException e) {
-			e.printStackTrace();
-			
-			logger.error("ClassNotFoundException | IOException e");
-			return "error ClassNotFoundException | IOException e";
-			
-		}
-		
-			
-		return "prueba exitosa";
-	}
-	
+
 	
 	/**
@@ -4269,7 +4137,5 @@
 	
 	
-	// ************************************************************************
-	// ************************************************************************
-	// ************************************************************************
+	
 	
 	private static void verifyBdocContainer(Container container) {
@@ -4358,841 +4224,5 @@
 
 	
-	
-	/**
-	 * Verifica si un archivo posee firmas electronicas y retorna informacion
-	 * de las mismas en un json
-	 * @param idFile
-	 * @return
-	 */
-	@GET
-	@Path("/verificar/{idFile}")
-	//@Produces("application/json")
-	@Produces("text/plain")
-	public String verifyFile(@PathParam("idFile") String idFile) {
-		
-		String file = SERVER_UPLOAD_LOCATION_FOLDER + idFile;
-	
-		//return getMimeType(file);
-		
-				
-		File tmpFile = new File(file);
-		String result = "";
-
-		
-		
-		
-		if (tmpFile.exists()) {
-			result = "El archivo existe.";
-			
-			try {
-				PdfReader reader = new PdfReader(file);
-				AcroFields af = reader.getAcroFields();
-				ArrayList<String> names = af.getSignatureNames();
-				if (names.size() > 0) {
-					result = "el archivo PDF posee "+ names.size() +" firma(s).\n";
-					
-					// sin esto explota: se debe agregar una implementacion del provider en tiempo de ejecucion
-					//http://www.cs.berkeley.edu/~jonah/bc/org/bouncycastle/jce/provider/BouncyCastleProvider.html
-					Security.addProvider(new BouncyCastleProvider());
-					
-					for (String name: names) {
-						result = result +"Nombre de la firma: "+ name + "\n";
-						System.out.println("Nombre de la firma: "+ name);
-						
-						PdfPKCS7 pk = af.verifySignature(name);
-						
-						Certificate[] pkc = pk.getCertificates();
-						
-						String tmpSignerName = pk.getSigningCertificate().getSubjectX500Principal().toString();
-						
-						
-						result = result + "Sujeto del certificado firmante: " + tmpSignerName + "\n"; 
-						//pk.getSigningCertificate().getSubjectX500Principal().getName() + "\n";
-						System.out.println("Sujeto del certificado firmante: " + 
-								pk.getSigningCertificate().getSubjectX500Principal().toString());
-						  
-						Calendar cal = pk.getSignDate();
-						
-						SimpleDateFormat date_format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
-						
-						//result = result + "Fecha de la firma: " + cal.toString() + "\n";
-						result = result + "Fecha de la firma: " + date_format.format(cal.getTime()) + "\n";
-						
-						/*
-						System.out.println("año: "+ cal.get(Calendar.YEAR));
-						System.out.println("mes: "+ (cal.get(Calendar.MONTH) + 1));
-						System.out.println("día: "+ cal.get(Calendar.DAY_OF_MONTH));
-						System.out.println("hora: "+ cal.get(Calendar.HOUR));
-						System.out.println("minuto: "+ cal.get(Calendar.MINUTE));
-						System.out.println("segundo: "+ cal.get(Calendar.SECOND));
-						*/
-						//SimpleDateFormat date_format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
-					    System.out.println(date_format.format(cal.getTime()));
-
-					}
-					
-					
-				}else{
-					result = "el archivo PDF no posee firmas";
-				}
-				
-				
-				
-			} catch (IOException e) {
-
-				e.printStackTrace();
-			}
-			
-			
-		}else {
-			result = "El archivo NO existe.";
-		}
-		
-		
-		return result;
-		
-		
-	}
-	
-	/**
-	 * Ejecuta el proceso de presign o preparacion de firma de documento pdf
-	 * @param presignPar
-	 * @param req objeto request para crear una sesion y mantener elementos del 
-	 * pdf en la misma
-	 * @param resp
-	 */
-	@POST
-	@Path("/prepararfirmapdf")
-	@Consumes(MediaType.APPLICATION_JSON)
-	@Produces(MediaType.APPLICATION_JSON)
-	//public Response presign(PresignParameters presignPar, @Context HttpServletRequest req) {
-	public PresignHash presign(PresignParameters presignPar, @Context HttpServletRequest req) {
-		
-
-		// cadena resultado de la funcion
-		String result = "";
-		
-		PresignHash presignHash = new PresignHash();
-		
-		
-		// cadena con el certificado
-		String certHex = presignPar.getCertificate();
-		System.out.println("certificado en Hex: " + certHex);
-		
-		// obtener el id del archivo 
-		String fileId = presignPar.getFileId();
-				
-		try {
-			CertificateFactory factory = CertificateFactory.getInstance("X.509");
-			Certificate[] chain = new Certificate[1];
-			
-			InputStream in = new ByteArrayInputStream(hexStringToByteArray(certHex));
-			chain[0] = factory.generateCertificate(in);
-			
-			if (chain[0] == null) {
-				System.out.println("error chain[0] == null");
-			}else {
-				
-				System.out.println("se cargo el certificado correctamente");
-				System.out.println(chain[0].toString());
-			}
-			
-			//String pdf = SERVER_UPLOAD_LOCATION_FOLDER + "e27a6a90-f955-4191-8e54-580e316a999d";
-			String pdf = SERVER_UPLOAD_LOCATION_FOLDER + fileId;
-			System.out.println("archivo a firmar: " + pdf);
-			
-			PdfReader reader = new PdfReader(pdf);
-			
-			ByteArrayOutputStream baos = new ByteArrayOutputStream();
-			
-			//FileOutputStream baos = new FileOutputStream(pdf+"-signed.pdf");
-			
-			PdfStamper stamper = PdfStamper.createSignature(reader, baos, '\0');
-			
-			// crear la apariencia de la firma
-	    	PdfSignatureAppearance sap = stamper.getSignatureAppearance();
-	    	sap.setReason("Prueba de firma en dos partes");
-	    	sap.setLocation("Merida, Venezuela");
-	    	sap.setVisibleSignature(new Rectangle(36, 748, 144,780),1, "sig");
-	    	sap.setCertificate(chain[0]);
-	    	
-	    	// crear la estructura de la firma
-	    	PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
-	    	dic.setReason(sap.getReason());
-	    	dic.setLocation(sap.getLocation());
-	    	dic.setContact(sap.getContact());
-	    	dic.setDate(new PdfDate(sap.getSignDate()));
-	    	
-	    	sap.setCryptoDictionary(dic);
-	    	
-	    	HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer> ();
-	    	exc.put(PdfName.CONTENTS, new Integer(8192 * 2 + 2));
-	    	sap.preClose(exc);
-	    	
-	    	ExternalDigest externalDigest = new ExternalDigest() {
-	    		public MessageDigest getMessageDigest(String hashAlgorithm)
-	    		throws GeneralSecurityException {
-	    			return DigestAlgorithms.getMessageDigest(hashAlgorithm, null);
-	    		}
-	    	};
-			
-			
-	    	PdfPKCS7 sgn = new PdfPKCS7(null, chain, "SHA256", null, externalDigest, false);
-	    	
-	    	InputStream data = sap.getRangeStream();
-	    	
-	    	byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest("SHA256"));
-	    	
-	    	Calendar cal = Calendar.getInstance();
-	    	byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, null, null, CryptoStandard.CMS);
-	    	
-	    	sh = DigestAlgorithms.digest(new ByteArrayInputStream(sh), externalDigest.getMessageDigest("SHA256"));
-	    	
-	    	System.out.println("sh length: "+ sh.length);
-	    	    	
-	    	String hashToSign = byteArrayToHexString(sh);
-	    	System.out.println("***************************************************************");
-	    	System.out.println("HASH EN HEXADECIMAL:");
-	    	System.out.println(hashToSign);
-	    	System.out.println("length: " +hashToSign.length());	
-	    	System.out.println("***************************************************************");
-			
-	    	DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
-			Date date = new Date();
-			System.out.println(dateFormat.format(date));
-			//String d = dateFormat.format(date);
-			
-			
-			// almacenar los objetos necesarios para realizar el postsign en una sesion
-			HttpSession session = req.getSession(true);
-			session.setAttribute("hashToSign", hashToSign);
-			
-			session.setAttribute("stamper", stamper);
-			session.setAttribute("sgn", sgn);
-			session.setAttribute("hash", hash);
-			session.setAttribute("cal", cal);
-			session.setAttribute("sap", sap);
-			session.setAttribute("baos", baos);
-			session.setAttribute("fileId", fileId);
-			
-			// creacion del json
-			JSONObject jsonHash = new JSONObject();
-			jsonHash.put("hashToSign", hashToSign);
-			
-			result = jsonHash.toString();
-			
-			presignHash.setHash(hashToSign);
-				
-			
-		} catch (CertificateException e1) {
-			// TODO Auto-generated catch block
-			e1.printStackTrace();
-		} catch (IOException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		} catch (DocumentException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		} catch (InvalidKeyException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		} catch (NoSuchProviderException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		} catch (NoSuchAlgorithmException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		} catch (GeneralSecurityException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		}
-		
-		//return Response.status(200).entity(result).build();
-		return presignHash;
-			
-	}
-	
-	
-	/**
-	 * Ejecuta el proceso de postsign o completacion de firma de documento pdf
-	 * @param postsignPar
-	 * @param req objeto request para crear una sesion y mantener elementos del 
-	 * pdf en la misma
-	 * @param resp
-	 * @throws IOException 
-	 */
-	@POST
-	@Path("/completarfirmapdf")
-	@Consumes(MediaType.APPLICATION_JSON)
-	@Produces(MediaType.APPLICATION_JSON)
-	public Response postsign(PostsignParameters postsignPar, @Context HttpServletRequest req) throws IOException {
-		
-		
-		// cadena resultado de la funcion
-		String result = "";
-				
-		// cadena con la firma
-		String signature = postsignPar.getSignature();
-		System.out.println("firma en Hex: " + signature);
-		
-		HttpSession session = req.getSession(false);
-		
-		String fileId = (String) session.getAttribute("fileId");
-		System.out.println("fileId: " + fileId);
-		
-		PdfStamper stamper = (PdfStamper) session.getAttribute("stamper");
-		
-		PdfPKCS7 sgn = (PdfPKCS7) session.getAttribute("sgn");
-		
-		byte[] hash = (byte[]) session.getAttribute("hash");
-		
-		Calendar cal = (Calendar) session.getAttribute("cal");
-		
-		PdfSignatureAppearance sap = (PdfSignatureAppearance) session.getAttribute("sap");
-		
-		ByteArrayOutputStream os = (ByteArrayOutputStream) session.getAttribute("baos");
-		
-		if (sgn == null) {
-			System.out.println("sgn == null");
-		}
-		if (hash == null) {
-			System.out.println("hash == null");
-		}
-		if (cal == null) {
-			System.out.println("cal == null");
-		}
-		if (sap == null) {
-			System.out.println("sap == null");
-		}
-		if (os == null) {
-			System.out.println("os == null");
-		}
-		
-		
-		
-		// convertir signature en bytes		
-		byte[] signatureInBytes = hexStringToByteArray(signature);
-				
-		// completar el proceso de firma
-		sgn.setExternalDigest(signatureInBytes, null, RSA_DIGEST_ENCRYPTION_ALGORITHM);
-		byte[] encodeSig = sgn.getEncodedPKCS7(hash, cal, null, null, null, CryptoStandard.CMS);
-		byte[] paddedSig = new byte[8192];
-		System.arraycopy(encodeSig, 0, paddedSig, 0, encodeSig.length);
-		PdfDictionary dic2 = new PdfDictionary();
-		dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
-		try {
-			sap.close(dic2);
-			
-			stamper.close();
-			System.out.println("stamper.close");
-			
-		}catch(DocumentException e) {
-			
-			System.out.println("throw new IOException");
-			throw new IOException(e);
-			
-		} catch (IOException e) {
-			// TODO Auto-generated catch block
-			System.out.println("IOException e");
-			e.printStackTrace();
-			
-		}
-		
-		String signedPdf = SERVER_UPLOAD_LOCATION_FOLDER + fileId + "-signed.pdf";
-		
-		FileOutputStream signedFile = new FileOutputStream(signedPdf);
-		
-		os.writeTo(signedFile);
-		os.flush();
-		
-		
-		
-		// en este punto el archivo pdf debe estar disponible en la ruta
-		// SERVER_UPLOAD_LOCATION_FOLDER + fileId;
-		
-		// llamar a una funcion que permita descargar el archivo
-		
-		result = "Archivo firmado correctamente";
-		System.out.println("Archivo firmado correctamente");
-		
-		return Response.status(200).entity(result).build();
-	}
-	
-	/**
-	 * Ejecuta el proceso de presign o preparacion de firma de documento en formato BDOC
-	 * 
-	 * @param presignPar
-	 * @param req
-	 * @return
-	 */
-	@POST
-	@Path("/bdoc/")
-	@Consumes(MediaType.APPLICATION_JSON)
-	@Produces(MediaType.APPLICATION_JSON)
-	public PresignHash presignBdoc2(PresignParameters presignPar, @Context HttpServletRequest req) {
-		
-		System.out.println("presignBdoc2: ");
-		
-		
-		String fileId;
-		String certHex;
-		
-		CertificateFactory cf;
-		X509Certificate signerCert;
-		
-		// cadena resultado de la funcion
-		String result = "";
-				
-		PresignHash presignHash = new PresignHash();
-		
-		SignedInfo signedInfo;
-		
-		fileId = presignPar.getFileId();
-		String sourceFile = SERVER_UPLOAD_LOCATION_FOLDER + fileId;
-		
-		certHex = presignPar.getCertificate();
-		System.out.println("certificado en Hex: " + certHex);
-		
-//		try {
-			/*		
-			Configuration configuration = new Configuration(Configuration.Mode.TEST);
-			
-			configuration.loadConfiguration("/home/aaraujo/desarrollo/2015/workspace-luna/JAXRS-Murachi/WebContent/WEB-INF/lib/digidoc4j.yaml");
-			configuration.setTslLocation("http://localhost/trusted-test-mp.xml");
-		    
-			Container container = Container.create(configuration);
-		    SignatureParameters signatureParameters = new SignatureParameters();
-		    SignatureProductionPlace productionPlace = new SignatureProductionPlace();
-		    productionPlace.setCity("Merida");
-		    signatureParameters.setProductionPlace(productionPlace);
-		    signatureParameters.setRoles(asList("Desarrollador"));
-		    container.setSignatureParameters(signatureParameters);
-		    container.setSignatureProfile(SignatureProfile.B_BES);
-		    container.addDataFile("/tmp/215d6ef7-d639-4191-87a1-ef68a91b2b27", "text/plain");
-		    container.sign(new PKCS12Signer("/tmp/JuanHilario.p12", "123456".toCharArray()));
-//		    Container container = Container.open("util/faulty/bdoc21-bad-nonce-content.bdoc");
-		    container.save("/tmp/signed.bdoc");
-		    ValidationResult results = container.validate();
-		    System.out.println(results.getReport());
-			*/
-
-			
-		Security.addProvider(new BouncyCastleProvider());
-			System.setProperty("digidoc4j.mode", "TEST");
-			
-			Configuration configuration;
-			configuration = new Configuration(Configuration.Mode.TEST);
-			//configuration.loadConfiguration("/home/aaraujo/desarrollo/2015/workspace-luna/JAXRS-Murachi/WebContent/WEB-INF/lib/digidoc4j.yaml");
-			
-			//configuration.setTslLocation("https://tibisay.cenditel.gob.ve/murachi/raw-attachment/wiki/WikiStart/trusted-test-mp.xml");
-			configuration.setTslLocation("http://localhost/trusted-test-mp.xml");
-			
-			Container container;
-			
-			container = Container.create(Container.DocumentType.BDOC, configuration);
-			
-			SignatureParameters signatureParameters = new SignatureParameters();
-		    SignatureProductionPlace productionPlace = new SignatureProductionPlace();
-		    productionPlace.setCity("Merida");
-		    signatureParameters.setProductionPlace(productionPlace);
-		    signatureParameters.setRoles(asList("Desarrollador"));
-		    container.setSignatureParameters(signatureParameters);
-		    container.setSignatureProfile(SignatureProfile.B_BES);
-			
-			container.addDataFile(sourceFile, "text/plain");
-			
-			container.sign(new PKCS12Signer("/tmp/JuanHilario.p12", "123456".toCharArray()));
-		    container.save("/tmp/signed.bdoc");
-		    ValidationResult results = container.validate();
-		    System.out.println(results.getReport());
-			
-			/*
-			cf = CertificateFactory.getInstance("X.509");
-		
-			InputStream in = new ByteArrayInputStream(hexStringToByteArray(certHex));
-			
-			signerCert = (X509Certificate) cf.generateCertificate(in);
-			
-			signedInfo = container.prepareSigning(signerCert);
-			
-			String hashToSign = byteArrayToHexString(signedInfo.getDigest());
-			//System.out.println("presignBdoc - hash: " + byteArrayToHexString(signedInfo.getDigest()));
-			System.out.println("presignBdoc - hash: " + hashToSign);
-			
-			
-			//container.save("/tmp/containerTmp.bdoc");
-			serialize(container, "/tmp/containerSerialized");
-			*/
-			
-			String hashToSign = "firma exitosa";
-			
-			// creacion del json
-			JSONObject jsonHash = new JSONObject();
-			jsonHash.put("hashToSign", hashToSign);
-						
-			result = jsonHash.toString();
-						
-			presignHash.setHash(hashToSign);
-			
-			
-/*			
-		} catch (CertificateException e1) {
-			// TODO Auto-generated catch block
-			e1.printStackTrace();
-		} catch (IOException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		}
-*/		
-		
-		return presignHash;
-		
-	}
-	
-	
-	@GET
-	@Path("/testbdoc/")
-	public String testBdoc() {
-		
-		Security.addProvider(new BouncyCastleProvider());
-		
-		Configuration configuration = new Configuration(Configuration.Mode.PROD);
-		
-		configuration.loadConfiguration("/tmp/digidoc4j.yaml");
-		//configuration.setTslLocation("http://localhost/trusted-test-mp.xml");
-		configuration.setTslLocation("file:///tmp/venezuela-tsl.xml");
-		
-	    Container container = Container.create(configuration);
-	    SignatureParameters signatureParameters = new SignatureParameters();
-	    SignatureProductionPlace productionPlace = new SignatureProductionPlace();
-	    productionPlace.setCity("Merida");
-	    signatureParameters.setProductionPlace(productionPlace);
-	    signatureParameters.setRoles(asList("Desarrollador"));
-	    container.setSignatureParameters(signatureParameters);
-	    container.setSignatureProfile(SignatureProfile.B_BES);
-	    container.addDataFile("/tmp/salida.txt", "text/plain");
-	    container.sign(new PKCS12Signer("/tmp/tibisay.p12", "123456".toCharArray()));
-//	    Container container = Container.open("util/faulty/bdoc21-bad-nonce-content.bdoc");
-	    container.save("/tmp/signed.bdoc");
-	    ValidationResult result = container.validate();
-	    System.out.println(result.getReport());
-		
-		return "test";
-	}
-	
-	/**
-	 * Prueba de agregar una firma electrónica a un contenedor existente.
-	 * 
-	 * NOTA: A un contenedor que posee una firma no se le pueden agregar nuevos DataFiles.
-	 * @return
-	 */
-	@GET
-	@Path("/addsignaturebdoc/")
-	public String addSignatureBdoc() {
-		logger.debug("/addsignaturebdoc/");
-		
-		Security.addProvider(new BouncyCastleProvider());
-		
-		Configuration configuration = new Configuration(Configuration.Mode.PROD);
-		
-		configuration.loadConfiguration(DIGIDOC4J_CONFIGURATION);
-		
-		configuration.setTslLocation(DIGIDOC4J_TSL_LOCATION);
-				
-		//String bdocFile = "/tmp/c1d099ad-44b3-4227-82fa-8c8f03746787.bdoc";
-		String bdocFile = "/tmp/twoSignatures.bdoc";
-		
-		Container container = Container.open(bdocFile, configuration);
-		logger.debug("open container: "+ bdocFile);
-		
-	    SignatureParameters signatureParameters = new SignatureParameters();
-	    
-	    SignatureProductionPlace productionPlace = new SignatureProductionPlace();
-	    productionPlace.setCity("Merida");
-	    productionPlace.setStateOrProvince("Merida");
-	    productionPlace.setPostalCode("5101");
-	    productionPlace.setCountry("Venezuela");
-	    
-	    signatureParameters.setProductionPlace(productionPlace);
-	    
-	    signatureParameters.setRoles(asList("Desarrollador"));
-	    
-	    container.setSignatureParameters(signatureParameters);
-	    
-	    container.setSignatureProfile(SignatureProfile.B_BES);
-	    	    
-	    logger.debug("signing: "+ bdocFile);
-	    container.sign(new PKCS12Signer("/tmp/tibisay.p12", "123456".toCharArray()));
-
-	    String outputFile = "/tmp/threeSignatures.bdoc";
-	    container.save(outputFile);
-	    logger.debug("saved file in : "+ outputFile);
-	    
-	    ValidationResult result = container.validate();
-	    System.out.println(result.getReport());
-		
-		return "success";
-	}
-	
-	
-	
-	/**
-	 * Prueba de ejecucion de programa desde consola. Incompleta
-	 * @return
-	 * @throws InterruptedException
-	 */
-	@GET
-	@Path("/ejecutar")
-	@Produces("text/plain")
-	public String executeProcess() throws InterruptedException {
-		
-		String s = "9712f235-4dd4-4b09-957d-b06c33af482b-serialized.bin";
-		String[] array = s.split("-serialized\\.bin");
-		
-		return array[0];
-		
-		
-		
-		/*
-		String line = "";
-		OutputStream stdin = null;
-		InputStream stderr = null;
-		InputStream stdout = null;
-		
-		try {
-			System.out.print("...a crear el proceso");
-			Process process = Runtime.getRuntime().exec("/usr/java/jdk1.7.0_21/bin/java -jar /home/aaraujo/desarrollo/2015/servicioVerificacion/testsigningpdf/holamundopdf.jar /tmp/589750.pdf /tmp/simonDiaz.pem /tmp/firmadoconsola.pdf");
-			//Process process = Runtime.getRuntime().exec("ls -l");
-			stdin = process.getOutputStream();
-			stderr = process.getErrorStream();
-			stdout = process.getInputStream();
-			
-			InputStreamReader isr = new InputStreamReader(stdout);
-			BufferedReader buff = new BufferedReader (isr);
-
-			
-			while((line = buff.readLine()) != null)
-				System.out.print(line+"\n");
-			int exitValue = process.waitFor();
-			if (exitValue != 0) {
-			    System.out.println("Abnormal process termination");
-			}	
-			
-		} catch (IOException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		}
-		System.out.print("...saliendo");
-		return line;
-		*/
-	}
-	
-	
-	
-	
-	
-	/**
-	 * 
-	 * @param certHex
-	 * @param httpHeaders
-	 * @param req
-	 * @param resp
-	 */
-	@POST
-	@Path("/presignOld")
-	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
-	public void presignOld(
-			@FormParam("certHexInForm") String certHex,
-			@Context HttpHeaders httpHeaders,
-			@Context HttpServletRequest req,
-			@Context HttpServletResponse resp) {
-		
-
-		String host = httpHeaders.getRequestHeader("host").get(0);
-		
-		String agent = httpHeaders.getRequestHeader("user-agent").get(0);
-		String salida = "User agent :"+ agent +" from host : "+host;
-		System.out.println(host);
-		System.out.println(agent);
-		System.out.println(salida);
-		
-		System.out.println("certificado en Hex: " + certHex);
-		
-		try {
-			CertificateFactory factory = CertificateFactory.getInstance("X.509");
-			Certificate[] chain = new Certificate[1];
-			
-			InputStream in = new ByteArrayInputStream(hexStringToByteArray(certHex));
-			chain[0] = factory.generateCertificate(in);
-			
-			if (chain[0] == null) {
-				System.out.println("error chain[0] == null");
-			}else {
-				
-				System.out.println("se cargo el certificado correctamente");
-				System.out.println(chain[0].toString());
-			}
-			
-			String pdf = SERVER_UPLOAD_LOCATION_FOLDER + "e27a6a90-f955-4191-8e54-580e316a999d";
-			
-			PdfReader reader = new PdfReader(pdf);
-			ByteArrayOutputStream baos = new ByteArrayOutputStream();
-			PdfStamper stamper = PdfStamper.createSignature(reader, baos, '\0');
-			
-			// crear la apariencia de la firma
-	    	PdfSignatureAppearance sap = stamper.getSignatureAppearance();
-	    	sap.setReason("Prueba de firma en dos partes");
-	    	sap.setLocation("Merida, Venezuela");
-	    	sap.setVisibleSignature(new Rectangle(36, 748, 144,780),1, "sig");
-	    	sap.setCertificate(chain[0]);
-	    	
-	    	// crear la estructura de la firma
-	    	PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
-	    	dic.setReason(sap.getReason());
-	    	dic.setLocation(sap.getLocation());
-	    	dic.setContact(sap.getContact());
-	    	dic.setDate(new PdfDate(sap.getSignDate()));
-	    	
-	    	sap.setCryptoDictionary(dic);
-	    	
-	    	HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer> ();
-	    	exc.put(PdfName.CONTENTS, new Integer(8192 * 2 + 2));
-	    	sap.preClose(exc);
-	    	
-	    	ExternalDigest externalDigest = new ExternalDigest() {
-	    		public MessageDigest getMessageDigest(String hashAlgorithm)
-	    		throws GeneralSecurityException {
-	    			return DigestAlgorithms.getMessageDigest(hashAlgorithm, null);
-	    		}
-	    	};
-			
-			
-	    	PdfPKCS7 sgn = new PdfPKCS7(null, chain, "SHA256", null, externalDigest, false);
-	    	
-	    	InputStream data = sap.getRangeStream();
-	    	
-	    	byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest("SHA256"));
-	    	
-	    	Calendar cal = Calendar.getInstance();
-	    	byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, null, null, CryptoStandard.CMS);
-	    	
-	    	sh = DigestAlgorithms.digest(new ByteArrayInputStream(sh), externalDigest.getMessageDigest("SHA256"));
-	    	
-	    	System.out.println("sh length: "+ sh.length);
-	    	    	
-	    	String hashToSign = byteArrayToHexString(sh);
-	    	System.out.println("***************************************************************");
-	    	System.out.println("HASH EN HEXADECIMAL:");
-	    	System.out.println(hashToSign);
-	    	System.out.println("length: " +hashToSign.length());	
-	    	System.out.println("***************************************************************");
-			
-	    	DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
-			Date date = new Date();
-			System.out.println(dateFormat.format(date));
-			String d = dateFormat.format(date);
-			
-			
-			// almacenar los objetos necesarios para realizar el postsign en una sesion
-			HttpSession session = req.getSession(true);
-			session.setAttribute("hashToSign", hashToSign);
-			
-			session.setAttribute("sgn", sgn);
-			session.setAttribute("hash", hash);
-			session.setAttribute("cal", cal);
-			session.setAttribute("sap", sap);
-			session.setAttribute("baos", baos);
-			
-		
-			
-			resp.sendRedirect("http://localhost/murachi2.html");
-			
-			
-		} catch (CertificateException e1) {
-			// TODO Auto-generated catch block
-			e1.printStackTrace();
-		} catch (IOException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		} catch (DocumentException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		} catch (InvalidKeyException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		} catch (NoSuchProviderException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		} catch (NoSuchAlgorithmException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		} catch (GeneralSecurityException e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		}
-		
-		
-	
-	}
-	
-	
-	@POST
-	@Path("/postsign")
-	public String postsignOld(@Context HttpServletRequest req,
-			@Context HttpServletResponse resp) {
-		
-		System.out.println("...postsign()...");
-		
-		HttpSession session = req.getSession(false);
-		Object att = session.getAttribute("hashToSign");
-				
-	
-		String output = "atributo leido de la sesion: " + att.toString();
-		
-		
-		return output;
-		//return Response.status(200).entity(output).build();
-	}
-	
-	
-	@GET
-	@Path("/retornajson")
-	@Produces(MediaType.APPLICATION_JSON)
-	public PresignHash retornajson(@Context HttpServletRequest req) {
-		
-		
-		
-		PresignHash h = new PresignHash();
-		h.setHash("ESTO SERIA UN HASH");
-		
-		System.out.println("...retornajson..."+ h.getHash());
-		
-		return h;
-		
-	}
-	
-	@POST
-	@Path("/enviarjson")
-	@Consumes(MediaType.APPLICATION_JSON)
-	@Produces(MediaType.APPLICATION_JSON)
-	public PresignHash recibejson( PresignParameters par) {
-		
-		String fileId = par.getFileId();
-		System.out.println("...fileId recibido..."+ fileId);
-		
-		String cert = par.getCertificate();
-		System.out.println("...certificate recibido..."+ cert);
-		
-		PresignHash h = new PresignHash();
-		h.setHash("DEBES FIRMAR ESTO");
-		
-		System.out.println("...recibejson..."+ h.getHash());
-		
-		return h;
-		
-	}
-	
-	
-	
+
 	
 	/**
@@ -5359,3 +4389,977 @@
 	  }
 	  
+	  
+	// ************************************************************************
+	// ************************************************************************
+	// ************************************************************************
+	  
+	  
+	
+
+	// pruebas de funciones para gestionar un contenedor BDOC
+		
+		@GET
+		@Path("/pruebaBDOC")
+		@Produces("text/plain")
+		public String testBDOCFunctions()  {
+			
+			Security.addProvider(new BouncyCastleProvider());
+			
+			Container c = createBDOCContainer();
+			
+			String containerId = UUID.randomUUID().toString();
+			System.out.println(containerId);
+			
+			if (c==null)
+			{
+				System.out.println("container == null");
+			}
+			else
+			{
+				System.out.println("container != null");
+			}
+			
+			addFileToBDOCContainer("/tmp/slides-93-cfrg-9.pdf", c);
+			
+			System.out.println("numero de archivos en el contenedor: " + Integer.toString(c.getDataFiles().size()));
+			
+			PKCS12Signer PKCS12_SIGNER = new PKCS12Signer("/tmp/tibisay.p12", "123456".toCharArray());
+			
+			SignatureParameters signatureParameters = new SignatureParameters();
+			SignatureProductionPlace productionPlace = new SignatureProductionPlace();
+			productionPlace.setCity("Merida");
+			productionPlace.setStateOrProvince("Merida");
+			productionPlace.setPostalCode("5101");
+			productionPlace.setCountry("Venezuela");
+			signatureParameters.setProductionPlace(productionPlace);
+			logger.debug("container setProductionPlace");
+			signatureParameters.setRoles(asList("Desarrollador"));
+			c.setSignatureParameters(signatureParameters);
+			c.setSignatureProfile(SignatureProfile.B_BES);
+			
+			c.sign(PKCS12_SIGNER);
+			
+			
+			if (deleteDataFileFromBDOCContainer("/tmp/slides-93-cfrg-9.pdf", c))
+			{
+				System.out.println("eliminado archivo del contenedor");
+			}
+			else
+			{
+				System.out.println("NO se eliminó el archivo del contenedor");
+			}
+				
+			if (deleteSignatureFromBDOCContainer(0, c))
+			{
+				System.out.println("SE ELIMINO la firma 2");
+			}
+			else
+			{
+				System.out.println("no se pudo eliminar la firma 0");
+			}
+			
+			System.out.println("numero de firmas restantes: "+ Integer.toString(c.getSignatures().size()));
+			
+			c.save("/tmp/prueba.bdoc");
+			
+			return "prueba exitosa";
+		}
+		
+		@GET
+		@Path("/serializar")
+		@Produces("text/plain")
+		public String serialize()  {
+			
+			logger.debug("recurso /serializar");
+			
+			Security.addProvider(new BouncyCastleProvider());
+			
+			Container c;
+			try {
+				c = deserialize("/tmp/container.bin");
+				logger.debug("deserializado contenedor");
+				
+				logger.debug("numero de firmas: "+ Integer.toString(c.getSignatures().size()));
+				
+				Security.addProvider(new BouncyCastleProvider());
+				
+				//c.sign(new PKCS12Signer("/tmp/ayzarra.p12", "ayzarra".toCharArray()));
+							
+				//c.save("/tmp/deserializado.bdoc");
+				
+				if (c.getSignatures().size() > 0) {
+			    	ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
+			        c.save(byteOut);
+			        ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
+			        
+			        //Configuration configuration = initConfig(); // also need to re-initialize configuration settings
+			        
+			        Configuration configuration = new Configuration(Configuration.Mode.PROD);		
+			    	configuration.loadConfiguration("/tmp/digidoc4j.yaml");
+			    	configuration.setTslLocation("file:///tmp/venezuela-tsl.xml");        
+			        
+			        Container container2 = Container.open(byteIn, configuration);
+			        container2.sign(new PKCS12Signer("/tmp/ayzarra.p12", "ayzarra".toCharArray()));
+			        
+			        System.out.println("********numero de firmas deserialize : "+ Integer.toString(container2.getSignatures().size()));
+			        container2.save("/tmp/deserializado2.bdoc");
+
+			    }
+				
+				
+				
+			} catch (ClassNotFoundException | IOException e) {
+				e.printStackTrace();
+				
+				logger.error("ClassNotFoundException | IOException e");
+				return "error ClassNotFoundException | IOException e";
+				
+			}
+			
+				
+			return "prueba exitosa";
+		}
+	  
+	  
+	  /**
+		 * Verifica si un archivo posee firmas electronicas y retorna informacion
+		 * de las mismas en un json
+		 * @param idFile
+		 * @return
+		 */
+		@GET
+		@Path("/verificar/{idFile}")
+		//@Produces("application/json")
+		@Produces("text/plain")
+		public String verifyFile(@PathParam("idFile") String idFile) {
+			
+			String file = SERVER_UPLOAD_LOCATION_FOLDER + idFile;
+		
+			//return getMimeType(file);
+			
+					
+			File tmpFile = new File(file);
+			String result = "";
+
+			
+			
+			
+			if (tmpFile.exists()) {
+				result = "El archivo existe.";
+				
+				try {
+					PdfReader reader = new PdfReader(file);
+					AcroFields af = reader.getAcroFields();
+					ArrayList<String> names = af.getSignatureNames();
+					if (names.size() > 0) {
+						result = "el archivo PDF posee "+ names.size() +" firma(s).\n";
+						
+						// sin esto explota: se debe agregar una implementacion del provider en tiempo de ejecucion
+						//http://www.cs.berkeley.edu/~jonah/bc/org/bouncycastle/jce/provider/BouncyCastleProvider.html
+						Security.addProvider(new BouncyCastleProvider());
+						
+						for (String name: names) {
+							result = result +"Nombre de la firma: "+ name + "\n";
+							System.out.println("Nombre de la firma: "+ name);
+							
+							PdfPKCS7 pk = af.verifySignature(name);
+							
+							Certificate[] pkc = pk.getCertificates();
+							
+							String tmpSignerName = pk.getSigningCertificate().getSubjectX500Principal().toString();
+							
+							
+							result = result + "Sujeto del certificado firmante: " + tmpSignerName + "\n"; 
+							//pk.getSigningCertificate().getSubjectX500Principal().getName() + "\n";
+							System.out.println("Sujeto del certificado firmante: " + 
+									pk.getSigningCertificate().getSubjectX500Principal().toString());
+							  
+							Calendar cal = pk.getSignDate();
+							
+							SimpleDateFormat date_format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
+							
+							//result = result + "Fecha de la firma: " + cal.toString() + "\n";
+							result = result + "Fecha de la firma: " + date_format.format(cal.getTime()) + "\n";
+							
+							/*
+							System.out.println("año: "+ cal.get(Calendar.YEAR));
+							System.out.println("mes: "+ (cal.get(Calendar.MONTH) + 1));
+							System.out.println("día: "+ cal.get(Calendar.DAY_OF_MONTH));
+							System.out.println("hora: "+ cal.get(Calendar.HOUR));
+							System.out.println("minuto: "+ cal.get(Calendar.MINUTE));
+							System.out.println("segundo: "+ cal.get(Calendar.SECOND));
+							*/
+							//SimpleDateFormat date_format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
+						    System.out.println(date_format.format(cal.getTime()));
+
+						}
+						
+						
+					}else{
+						result = "el archivo PDF no posee firmas";
+					}
+					
+					
+					
+				} catch (IOException e) {
+
+					e.printStackTrace();
+				}
+				
+				
+			}else {
+				result = "El archivo NO existe.";
+			}
+			
+			
+			return result;
+			
+			
+		}  
+	  
+	
+	
+	/**
+	 * Ejecuta el proceso de presign o preparacion de firma de documento pdf
+	 * @param presignPar
+	 * @param req objeto request para crear una sesion y mantener elementos del 
+	 * pdf en la misma
+	 * @param resp
+	 */
+	@POST
+	@Path("/prepararfirmapdf")
+	@Consumes(MediaType.APPLICATION_JSON)
+	@Produces(MediaType.APPLICATION_JSON)
+	//public Response presign(PresignParameters presignPar, @Context HttpServletRequest req) {
+	public PresignHash presign(PresignParameters presignPar, @Context HttpServletRequest req) {
+		
+
+		// cadena resultado de la funcion
+		String result = "";
+		
+		PresignHash presignHash = new PresignHash();
+		
+		
+		// cadena con el certificado
+		String certHex = presignPar.getCertificate();
+		System.out.println("certificado en Hex: " + certHex);
+		
+		// obtener el id del archivo 
+		String fileId = presignPar.getFileId();
+				
+		try {
+			CertificateFactory factory = CertificateFactory.getInstance("X.509");
+			Certificate[] chain = new Certificate[1];
+			
+			InputStream in = new ByteArrayInputStream(hexStringToByteArray(certHex));
+			chain[0] = factory.generateCertificate(in);
+			
+			if (chain[0] == null) {
+				System.out.println("error chain[0] == null");
+			}else {
+				
+				System.out.println("se cargo el certificado correctamente");
+				System.out.println(chain[0].toString());
+			}
+			
+			//String pdf = SERVER_UPLOAD_LOCATION_FOLDER + "e27a6a90-f955-4191-8e54-580e316a999d";
+			String pdf = SERVER_UPLOAD_LOCATION_FOLDER + fileId;
+			System.out.println("archivo a firmar: " + pdf);
+			
+			PdfReader reader = new PdfReader(pdf);
+			
+			ByteArrayOutputStream baos = new ByteArrayOutputStream();
+			
+			//FileOutputStream baos = new FileOutputStream(pdf+"-signed.pdf");
+			
+			PdfStamper stamper = PdfStamper.createSignature(reader, baos, '\0');
+			
+			// crear la apariencia de la firma
+	    	PdfSignatureAppearance sap = stamper.getSignatureAppearance();
+	    	sap.setReason("Prueba de firma en dos partes");
+	    	sap.setLocation("Merida, Venezuela");
+	    	sap.setVisibleSignature(new Rectangle(36, 748, 144,780),1, "sig");
+	    	sap.setCertificate(chain[0]);
+	    	
+	    	// crear la estructura de la firma
+	    	PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
+	    	dic.setReason(sap.getReason());
+	    	dic.setLocation(sap.getLocation());
+	    	dic.setContact(sap.getContact());
+	    	dic.setDate(new PdfDate(sap.getSignDate()));
+	    	
+	    	sap.setCryptoDictionary(dic);
+	    	
+	    	HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer> ();
+	    	exc.put(PdfName.CONTENTS, new Integer(8192 * 2 + 2));
+	    	sap.preClose(exc);
+	    	
+	    	ExternalDigest externalDigest = new ExternalDigest() {
+	    		public MessageDigest getMessageDigest(String hashAlgorithm)
+	    		throws GeneralSecurityException {
+	    			return DigestAlgorithms.getMessageDigest(hashAlgorithm, null);
+	    		}
+	    	};
+			
+			
+	    	PdfPKCS7 sgn = new PdfPKCS7(null, chain, "SHA256", null, externalDigest, false);
+	    	
+	    	InputStream data = sap.getRangeStream();
+	    	
+	    	byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest("SHA256"));
+	    	
+	    	Calendar cal = Calendar.getInstance();
+	    	byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, null, null, CryptoStandard.CMS);
+	    	
+	    	sh = DigestAlgorithms.digest(new ByteArrayInputStream(sh), externalDigest.getMessageDigest("SHA256"));
+	    	
+	    	System.out.println("sh length: "+ sh.length);
+	    	    	
+	    	String hashToSign = byteArrayToHexString(sh);
+	    	System.out.println("***************************************************************");
+	    	System.out.println("HASH EN HEXADECIMAL:");
+	    	System.out.println(hashToSign);
+	    	System.out.println("length: " +hashToSign.length());	
+	    	System.out.println("***************************************************************");
+			
+	    	DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
+			Date date = new Date();
+			System.out.println(dateFormat.format(date));
+			//String d = dateFormat.format(date);
+			
+			
+			// almacenar los objetos necesarios para realizar el postsign en una sesion
+			HttpSession session = req.getSession(true);
+			session.setAttribute("hashToSign", hashToSign);
+			
+			session.setAttribute("stamper", stamper);
+			session.setAttribute("sgn", sgn);
+			session.setAttribute("hash", hash);
+			session.setAttribute("cal", cal);
+			session.setAttribute("sap", sap);
+			session.setAttribute("baos", baos);
+			session.setAttribute("fileId", fileId);
+			
+			// creacion del json
+			JSONObject jsonHash = new JSONObject();
+			jsonHash.put("hashToSign", hashToSign);
+			
+			result = jsonHash.toString();
+			
+			presignHash.setHash(hashToSign);
+				
+			
+		} catch (CertificateException e1) {
+			// TODO Auto-generated catch block
+			e1.printStackTrace();
+		} catch (IOException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		} catch (DocumentException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		} catch (InvalidKeyException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		} catch (NoSuchProviderException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		} catch (NoSuchAlgorithmException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		} catch (GeneralSecurityException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+		
+		//return Response.status(200).entity(result).build();
+		return presignHash;
+			
+	}
+	
+	
+	/**
+	 * Ejecuta el proceso de postsign o completacion de firma de documento pdf
+	 * @param postsignPar
+	 * @param req objeto request para crear una sesion y mantener elementos del 
+	 * pdf en la misma
+	 * @param resp
+	 * @throws IOException 
+	 */
+	@POST
+	@Path("/completarfirmapdf")
+	@Consumes(MediaType.APPLICATION_JSON)
+	@Produces(MediaType.APPLICATION_JSON)
+	public Response postsign(PostsignParameters postsignPar, @Context HttpServletRequest req) throws IOException {
+		
+		
+		// cadena resultado de la funcion
+		String result = "";
+				
+		// cadena con la firma
+		String signature = postsignPar.getSignature();
+		System.out.println("firma en Hex: " + signature);
+		
+		HttpSession session = req.getSession(false);
+		
+		String fileId = (String) session.getAttribute("fileId");
+		System.out.println("fileId: " + fileId);
+		
+		PdfStamper stamper = (PdfStamper) session.getAttribute("stamper");
+		
+		PdfPKCS7 sgn = (PdfPKCS7) session.getAttribute("sgn");
+		
+		byte[] hash = (byte[]) session.getAttribute("hash");
+		
+		Calendar cal = (Calendar) session.getAttribute("cal");
+		
+		PdfSignatureAppearance sap = (PdfSignatureAppearance) session.getAttribute("sap");
+		
+		ByteArrayOutputStream os = (ByteArrayOutputStream) session.getAttribute("baos");
+		
+		if (sgn == null) {
+			System.out.println("sgn == null");
+		}
+		if (hash == null) {
+			System.out.println("hash == null");
+		}
+		if (cal == null) {
+			System.out.println("cal == null");
+		}
+		if (sap == null) {
+			System.out.println("sap == null");
+		}
+		if (os == null) {
+			System.out.println("os == null");
+		}
+		
+		
+		
+		// convertir signature en bytes		
+		byte[] signatureInBytes = hexStringToByteArray(signature);
+				
+		// completar el proceso de firma
+		sgn.setExternalDigest(signatureInBytes, null, RSA_DIGEST_ENCRYPTION_ALGORITHM);
+		byte[] encodeSig = sgn.getEncodedPKCS7(hash, cal, null, null, null, CryptoStandard.CMS);
+		byte[] paddedSig = new byte[8192];
+		System.arraycopy(encodeSig, 0, paddedSig, 0, encodeSig.length);
+		PdfDictionary dic2 = new PdfDictionary();
+		dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
+		try {
+			sap.close(dic2);
+			
+			stamper.close();
+			System.out.println("stamper.close");
+			
+		}catch(DocumentException e) {
+			
+			System.out.println("throw new IOException");
+			throw new IOException(e);
+			
+		} catch (IOException e) {
+			// TODO Auto-generated catch block
+			System.out.println("IOException e");
+			e.printStackTrace();
+			
+		}
+		
+		String signedPdf = SERVER_UPLOAD_LOCATION_FOLDER + fileId + "-signed.pdf";
+		
+		FileOutputStream signedFile = new FileOutputStream(signedPdf);
+		
+		os.writeTo(signedFile);
+		os.flush();
+		
+		
+		
+		// en este punto el archivo pdf debe estar disponible en la ruta
+		// SERVER_UPLOAD_LOCATION_FOLDER + fileId;
+		
+		// llamar a una funcion que permita descargar el archivo
+		
+		result = "Archivo firmado correctamente";
+		System.out.println("Archivo firmado correctamente");
+		
+		return Response.status(200).entity(result).build();
+	}
+	
+	/**
+	 * Ejecuta el proceso de presign o preparacion de firma de documento en formato BDOC
+	 * 
+	 * @param presignPar
+	 * @param req
+	 * @return
+	 */
+	@POST
+	@Path("/bdoc/")
+	@Consumes(MediaType.APPLICATION_JSON)
+	@Produces(MediaType.APPLICATION_JSON)
+	public PresignHash presignBdoc2(PresignParameters presignPar, @Context HttpServletRequest req) {
+		
+		System.out.println("presignBdoc2: ");
+		
+		
+		String fileId;
+		String certHex;
+		
+		CertificateFactory cf;
+		X509Certificate signerCert;
+		
+		// cadena resultado de la funcion
+		String result = "";
+				
+		PresignHash presignHash = new PresignHash();
+		
+		SignedInfo signedInfo;
+		
+		fileId = presignPar.getFileId();
+		String sourceFile = SERVER_UPLOAD_LOCATION_FOLDER + fileId;
+		
+		certHex = presignPar.getCertificate();
+		System.out.println("certificado en Hex: " + certHex);
+		
+//		try {
+			/*		
+			Configuration configuration = new Configuration(Configuration.Mode.TEST);
+			
+			configuration.loadConfiguration("/home/aaraujo/desarrollo/2015/workspace-luna/JAXRS-Murachi/WebContent/WEB-INF/lib/digidoc4j.yaml");
+			configuration.setTslLocation("http://localhost/trusted-test-mp.xml");
+		    
+			Container container = Container.create(configuration);
+		    SignatureParameters signatureParameters = new SignatureParameters();
+		    SignatureProductionPlace productionPlace = new SignatureProductionPlace();
+		    productionPlace.setCity("Merida");
+		    signatureParameters.setProductionPlace(productionPlace);
+		    signatureParameters.setRoles(asList("Desarrollador"));
+		    container.setSignatureParameters(signatureParameters);
+		    container.setSignatureProfile(SignatureProfile.B_BES);
+		    container.addDataFile("/tmp/215d6ef7-d639-4191-87a1-ef68a91b2b27", "text/plain");
+		    container.sign(new PKCS12Signer("/tmp/JuanHilario.p12", "123456".toCharArray()));
+//		    Container container = Container.open("util/faulty/bdoc21-bad-nonce-content.bdoc");
+		    container.save("/tmp/signed.bdoc");
+		    ValidationResult results = container.validate();
+		    System.out.println(results.getReport());
+			*/
+
+			
+		Security.addProvider(new BouncyCastleProvider());
+			System.setProperty("digidoc4j.mode", "TEST");
+			
+			Configuration configuration;
+			configuration = new Configuration(Configuration.Mode.TEST);
+			//configuration.loadConfiguration("/home/aaraujo/desarrollo/2015/workspace-luna/JAXRS-Murachi/WebContent/WEB-INF/lib/digidoc4j.yaml");
+			
+			//configuration.setTslLocation("https://tibisay.cenditel.gob.ve/murachi/raw-attachment/wiki/WikiStart/trusted-test-mp.xml");
+			configuration.setTslLocation("http://localhost/trusted-test-mp.xml");
+			
+			Container container;
+			
+			container = Container.create(Container.DocumentType.BDOC, configuration);
+			
+			SignatureParameters signatureParameters = new SignatureParameters();
+		    SignatureProductionPlace productionPlace = new SignatureProductionPlace();
+		    productionPlace.setCity("Merida");
+		    signatureParameters.setProductionPlace(productionPlace);
+		    signatureParameters.setRoles(asList("Desarrollador"));
+		    container.setSignatureParameters(signatureParameters);
+		    container.setSignatureProfile(SignatureProfile.B_BES);
+			
+			container.addDataFile(sourceFile, "text/plain");
+			
+			container.sign(new PKCS12Signer("/tmp/JuanHilario.p12", "123456".toCharArray()));
+		    container.save("/tmp/signed.bdoc");
+		    ValidationResult results = container.validate();
+		    System.out.println(results.getReport());
+			
+			/*
+			cf = CertificateFactory.getInstance("X.509");
+		
+			InputStream in = new ByteArrayInputStream(hexStringToByteArray(certHex));
+			
+			signerCert = (X509Certificate) cf.generateCertificate(in);
+			
+			signedInfo = container.prepareSigning(signerCert);
+			
+			String hashToSign = byteArrayToHexString(signedInfo.getDigest());
+			//System.out.println("presignBdoc - hash: " + byteArrayToHexString(signedInfo.getDigest()));
+			System.out.println("presignBdoc - hash: " + hashToSign);
+			
+			
+			//container.save("/tmp/containerTmp.bdoc");
+			serialize(container, "/tmp/containerSerialized");
+			*/
+			
+			String hashToSign = "firma exitosa";
+			
+			// creacion del json
+			JSONObject jsonHash = new JSONObject();
+			jsonHash.put("hashToSign", hashToSign);
+						
+			result = jsonHash.toString();
+						
+			presignHash.setHash(hashToSign);
+			
+			
+/*			
+		} catch (CertificateException e1) {
+			// TODO Auto-generated catch block
+			e1.printStackTrace();
+		} catch (IOException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+*/		
+		
+		return presignHash;
+		
+	}
+	
+	
+	@GET
+	@Path("/testbdoc/")
+	public String testBdoc() {
+		
+		Security.addProvider(new BouncyCastleProvider());
+		
+		Configuration configuration = new Configuration(Configuration.Mode.PROD);
+		
+		configuration.loadConfiguration("/tmp/digidoc4j.yaml");
+		//configuration.setTslLocation("http://localhost/trusted-test-mp.xml");
+		configuration.setTslLocation("file:///tmp/venezuela-tsl.xml");
+		
+	    Container container = Container.create(configuration);
+	    SignatureParameters signatureParameters = new SignatureParameters();
+	    SignatureProductionPlace productionPlace = new SignatureProductionPlace();
+	    productionPlace.setCity("Merida");
+	    signatureParameters.setProductionPlace(productionPlace);
+	    signatureParameters.setRoles(asList("Desarrollador"));
+	    container.setSignatureParameters(signatureParameters);
+	    container.setSignatureProfile(SignatureProfile.B_BES);
+	    container.addDataFile("/tmp/salida.txt", "text/plain");
+	    container.sign(new PKCS12Signer("/tmp/tibisay.p12", "123456".toCharArray()));
+//	    Container container = Container.open("util/faulty/bdoc21-bad-nonce-content.bdoc");
+	    container.save("/tmp/signed.bdoc");
+	    ValidationResult result = container.validate();
+	    System.out.println(result.getReport());
+		
+		return "test";
+	}
+	
+	/**
+	 * Prueba de agregar una firma electrónica a un contenedor existente.
+	 * 
+	 * NOTA: A un contenedor que posee una firma no se le pueden agregar nuevos DataFiles.
+	 * @return
+	 */
+	@GET
+	@Path("/addsignaturebdoc/")
+	public String addSignatureBdoc() {
+		logger.debug("/addsignaturebdoc/");
+		
+		Security.addProvider(new BouncyCastleProvider());
+		
+		Configuration configuration = new Configuration(Configuration.Mode.PROD);
+		
+		configuration.loadConfiguration(DIGIDOC4J_CONFIGURATION);
+		
+		configuration.setTslLocation(DIGIDOC4J_TSL_LOCATION);
+				
+		//String bdocFile = "/tmp/c1d099ad-44b3-4227-82fa-8c8f03746787.bdoc";
+		String bdocFile = "/tmp/twoSignatures.bdoc";
+		
+		Container container = Container.open(bdocFile, configuration);
+		logger.debug("open container: "+ bdocFile);
+		
+	    SignatureParameters signatureParameters = new SignatureParameters();
+	    
+	    SignatureProductionPlace productionPlace = new SignatureProductionPlace();
+	    productionPlace.setCity("Merida");
+	    productionPlace.setStateOrProvince("Merida");
+	    productionPlace.setPostalCode("5101");
+	    productionPlace.setCountry("Venezuela");
+	    
+	    signatureParameters.setProductionPlace(productionPlace);
+	    
+	    signatureParameters.setRoles(asList("Desarrollador"));
+	    
+	    container.setSignatureParameters(signatureParameters);
+	    
+	    container.setSignatureProfile(SignatureProfile.B_BES);
+	    	    
+	    logger.debug("signing: "+ bdocFile);
+	    container.sign(new PKCS12Signer("/tmp/tibisay.p12", "123456".toCharArray()));
+
+	    String outputFile = "/tmp/threeSignatures.bdoc";
+	    container.save(outputFile);
+	    logger.debug("saved file in : "+ outputFile);
+	    
+	    ValidationResult result = container.validate();
+	    System.out.println(result.getReport());
+		
+		return "success";
+	}
+	
+	
+	
+	/**
+	 * Prueba de ejecucion de programa desde consola. Incompleta
+	 * @return
+	 * @throws InterruptedException
+	 */
+	@GET
+	@Path("/ejecutar")
+	@Produces("text/plain")
+	public String executeProcess() throws InterruptedException {
+		
+		String s = "9712f235-4dd4-4b09-957d-b06c33af482b-serialized.bin";
+		String[] array = s.split("-serialized\\.bin");
+		
+		return array[0];
+		
+		
+		
+		/*
+		String line = "";
+		OutputStream stdin = null;
+		InputStream stderr = null;
+		InputStream stdout = null;
+		
+		try {
+			System.out.print("...a crear el proceso");
+			Process process = Runtime.getRuntime().exec("/usr/java/jdk1.7.0_21/bin/java -jar /home/aaraujo/desarrollo/2015/servicioVerificacion/testsigningpdf/holamundopdf.jar /tmp/589750.pdf /tmp/simonDiaz.pem /tmp/firmadoconsola.pdf");
+			//Process process = Runtime.getRuntime().exec("ls -l");
+			stdin = process.getOutputStream();
+			stderr = process.getErrorStream();
+			stdout = process.getInputStream();
+			
+			InputStreamReader isr = new InputStreamReader(stdout);
+			BufferedReader buff = new BufferedReader (isr);
+
+			
+			while((line = buff.readLine()) != null)
+				System.out.print(line+"\n");
+			int exitValue = process.waitFor();
+			if (exitValue != 0) {
+			    System.out.println("Abnormal process termination");
+			}	
+			
+		} catch (IOException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+		System.out.print("...saliendo");
+		return line;
+		*/
+	}
+	
+	
+	
+	
+	
+	/**
+	 * 
+	 * @param certHex
+	 * @param httpHeaders
+	 * @param req
+	 * @param resp
+	 */
+	@POST
+	@Path("/presignOld")
+	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
+	public void presignOld(
+			@FormParam("certHexInForm") String certHex,
+			@Context HttpHeaders httpHeaders,
+			@Context HttpServletRequest req,
+			@Context HttpServletResponse resp) {
+		
+
+		String host = httpHeaders.getRequestHeader("host").get(0);
+		
+		String agent = httpHeaders.getRequestHeader("user-agent").get(0);
+		String salida = "User agent :"+ agent +" from host : "+host;
+		System.out.println(host);
+		System.out.println(agent);
+		System.out.println(salida);
+		
+		System.out.println("certificado en Hex: " + certHex);
+		
+		try {
+			CertificateFactory factory = CertificateFactory.getInstance("X.509");
+			Certificate[] chain = new Certificate[1];
+			
+			InputStream in = new ByteArrayInputStream(hexStringToByteArray(certHex));
+			chain[0] = factory.generateCertificate(in);
+			
+			if (chain[0] == null) {
+				System.out.println("error chain[0] == null");
+			}else {
+				
+				System.out.println("se cargo el certificado correctamente");
+				System.out.println(chain[0].toString());
+			}
+			
+			String pdf = SERVER_UPLOAD_LOCATION_FOLDER + "e27a6a90-f955-4191-8e54-580e316a999d";
+			
+			PdfReader reader = new PdfReader(pdf);
+			ByteArrayOutputStream baos = new ByteArrayOutputStream();
+			PdfStamper stamper = PdfStamper.createSignature(reader, baos, '\0');
+			
+			// crear la apariencia de la firma
+	    	PdfSignatureAppearance sap = stamper.getSignatureAppearance();
+	    	sap.setReason("Prueba de firma en dos partes");
+	    	sap.setLocation("Merida, Venezuela");
+	    	sap.setVisibleSignature(new Rectangle(36, 748, 144,780),1, "sig");
+	    	sap.setCertificate(chain[0]);
+	    	
+	    	// crear la estructura de la firma
+	    	PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
+	    	dic.setReason(sap.getReason());
+	    	dic.setLocation(sap.getLocation());
+	    	dic.setContact(sap.getContact());
+	    	dic.setDate(new PdfDate(sap.getSignDate()));
+	    	
+	    	sap.setCryptoDictionary(dic);
+	    	
+	    	HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer> ();
+	    	exc.put(PdfName.CONTENTS, new Integer(8192 * 2 + 2));
+	    	sap.preClose(exc);
+	    	
+	    	ExternalDigest externalDigest = new ExternalDigest() {
+	    		public MessageDigest getMessageDigest(String hashAlgorithm)
+	    		throws GeneralSecurityException {
+	    			return DigestAlgorithms.getMessageDigest(hashAlgorithm, null);
+	    		}
+	    	};
+			
+			
+	    	PdfPKCS7 sgn = new PdfPKCS7(null, chain, "SHA256", null, externalDigest, false);
+	    	
+	    	InputStream data = sap.getRangeStream();
+	    	
+	    	byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest("SHA256"));
+	    	
+	    	Calendar cal = Calendar.getInstance();
+	    	byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, null, null, CryptoStandard.CMS);
+	    	
+	    	sh = DigestAlgorithms.digest(new ByteArrayInputStream(sh), externalDigest.getMessageDigest("SHA256"));
+	    	
+	    	System.out.println("sh length: "+ sh.length);
+	    	    	
+	    	String hashToSign = byteArrayToHexString(sh);
+	    	System.out.println("***************************************************************");
+	    	System.out.println("HASH EN HEXADECIMAL:");
+	    	System.out.println(hashToSign);
+	    	System.out.println("length: " +hashToSign.length());	
+	    	System.out.println("***************************************************************");
+			
+	    	DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
+			Date date = new Date();
+			System.out.println(dateFormat.format(date));
+			String d = dateFormat.format(date);
+			
+			
+			// almacenar los objetos necesarios para realizar el postsign en una sesion
+			HttpSession session = req.getSession(true);
+			session.setAttribute("hashToSign", hashToSign);
+			
+			session.setAttribute("sgn", sgn);
+			session.setAttribute("hash", hash);
+			session.setAttribute("cal", cal);
+			session.setAttribute("sap", sap);
+			session.setAttribute("baos", baos);
+			
+		
+			
+			resp.sendRedirect("http://localhost/murachi2.html");
+			
+			
+		} catch (CertificateException e1) {
+			// TODO Auto-generated catch block
+			e1.printStackTrace();
+		} catch (IOException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		} catch (DocumentException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		} catch (InvalidKeyException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		} catch (NoSuchProviderException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		} catch (NoSuchAlgorithmException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		} catch (GeneralSecurityException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+		
+		
+	
+	}
+	
+	
+	@POST
+	@Path("/postsign")
+	public String postsignOld(@Context HttpServletRequest req,
+			@Context HttpServletResponse resp) {
+		
+		System.out.println("...postsign()...");
+		
+		HttpSession session = req.getSession(false);
+		Object att = session.getAttribute("hashToSign");
+				
+	
+		String output = "atributo leido de la sesion: " + att.toString();
+		
+		
+		return output;
+		//return Response.status(200).entity(output).build();
+	}
+	
+	
+	@GET
+	@Path("/retornajson")
+	@Produces(MediaType.APPLICATION_JSON)
+	public PresignHash retornajson(@Context HttpServletRequest req) {
+		
+		
+		
+		PresignHash h = new PresignHash();
+		h.setHash("ESTO SERIA UN HASH");
+		
+		System.out.println("...retornajson..."+ h.getHash());
+		
+		return h;
+		
+	}
+	
+	@POST
+	@Path("/enviarjson")
+	@Consumes(MediaType.APPLICATION_JSON)
+	@Produces(MediaType.APPLICATION_JSON)
+	public PresignHash recibejson( PresignParameters par) {
+		
+		String fileId = par.getFileId();
+		System.out.println("...fileId recibido..."+ fileId);
+		
+		String cert = par.getCertificate();
+		System.out.println("...certificate recibido..."+ cert);
+		
+		PresignHash h = new PresignHash();
+		h.setHash("DEBES FIRMAR ESTO");
+		
+		System.out.println("...recibejson..."+ h.getHash());
+		
+		return h;
+		
+	}
+	
+	
+	
+	
+	
+	  
 }
