package com.ieci.aries;

import java.net.*;
import java.io.*;
import java.util.*;
//Incluir en el classpath:
//	- xml-apis.jar
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;

//Incluir en el classpath:
//	- xercesImpl.jar
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import org.apache.xml.serialize.*;

import sun.misc.BASE64Encoder;


public class Rttest {
	public static void main(String args[]) {
		 URL url;
		 URLConnection urlConn=null;
		 DataOutputStream printout;
         ByteArrayOutputStream fos = new ByteArrayOutputStream( );
         printout = new DataOutputStream (fos);
		 
		 String registroXML;
		 
		 //Datos que son fijos para cada aplicacion
		 String usuario="XXXX"; //Usuario de registro telematico
		 String clave="XXXX"; //Contraseña
		 String destino="XXXX/XXXXX/XXXXX"; //Destino (unidad)
		 String asunto="XXXX"; //Codigo de Asunto
		 
		 //Datos Variables
		 String remitente="PRIMERO SEGUNDO,NOMBRE";    //El nombre recogido del certificado
		 String nif="29999999D";          //El NIF recogido del certificado  
		 String datosSellar="HASH DE LA FIRMA";  //Cadena con la que obtener del Notario un TS (puede ser el hash de la operación de firmado, el id de la transaccion de firmado ,etc
		 String resumen="El resumen.....";  //Breve descripción del documento que se presenta 
		 //Opcional
		 String filePath="";
		 //String filePath="ftp://magico.cjap.junta-andalucia.es/reposftp/teleweb/Interfaz.pdf";
		
		 
		 //Datos que Devuelve
		 String errorCode="";
		 String errorDesc="";
		 String nRegistro="";
		 String fRegistro="";
		 String sTiempo="";

		 
	     //Componer el contenido del XML 
	     
	        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	        DocumentBuilder builder=null;
			try {
				builder = factory.newDocumentBuilder();
			} catch (ParserConfigurationException e) {
					e.printStackTrace();
			}
			 Document document = builder.newDocument();  
			
	        Element root = (Element) document.createElement("Informacion"); 
	        document.appendChild (root);

	        //Datos de Conexion
	        Element conex = (Element) root.appendChild(document.createElement("Datos_Conexion"));
	        Node user =   (Node) conex.appendChild(document.createElement("Nombre_Usuario"));
	        user.appendChild(document.createTextNode(usuario));
	        Node pass =   (Node) conex.appendChild(document.createElement("Clave_Usuario"));
	        pass.appendChild(document.createTextNode(clave));
	        
	        //Datos a Registrar
	        Element datos = (Element) root.appendChild(document.createElement("Datos_Registrar"));
	        Node sender =   (Node) datos.appendChild(document.createElement("Remitente"));
	        sender.appendChild(document.createTextNode(remitente));
	        Node ident =   (Node) datos.appendChild(document.createElement("Id_Remitente"));
	        ident.appendChild(document.createTextNode(nif));
	        Node subject =   (Node) datos.appendChild(document.createElement("Codigo_Asunto"));
	        subject.appendChild(document.createTextNode(asunto));
	        Node destination =   (Node) datos.appendChild(document.createElement("Codigo_Destinatario"));
	        destination.appendChild(document.createTextNode(destino));
	        Node sAbstract =   (Node) datos.appendChild(document.createElement("Extracto"));
	        sAbstract.appendChild(document.createTextNode(resumen));
	        Node sDoc = (Node) datos.appendChild(document.createElement("Documentos")); 
	        /*
	        //Anexado de documentos Opcional
	        Node docItem =   (Node) sDoc.appendChild(document.createElement("Documento"));
	        Node docName = (Node) docItem.appendChild(document.createElement("Nombre"));
	        docName.appendChild(document.createTextNode("Documento de pruebas"));
	        Node docPath = (Node) docItem.appendChild(document.createElement("Path"));
	        docPath.appendChild(document.createTextNode(filePath));*/
	        
	        Node tstamp =   (Node) datos.appendChild(document.createElement("Sellado_de_Tiempo"));
	       
	        
	        //Sellado de tiempo Opcional
	        Node tsText= (Node) tstamp.appendChild(document.createElement("Datos_a_Firmar"));
	        tsText.appendChild(document.createTextNode(datosSellar));
            
	       
	        //Estructura donde se reciben los datos 
	        Element respuesta = (Element) root.appendChild(document.createElement("Datos_Registro"));
	        respuesta.appendChild(document.createElement("Numero_Registro"));
	        respuesta.appendChild(document.createElement("Fecha_Registro"));
	        respuesta.appendChild(document.createElement("Sello_de_Tiempo"));
	        respuesta.appendChild(document.createElement("Error_Code"));
	        respuesta.appendChild(document.createElement("Error_Desc"));

	        
	        //Convertir el documento a String
	        OutputFormat format = new OutputFormat(document);
	        StringWriter strOut = new StringWriter();
	        XMLSerializer xmlSerial = new XMLSerializer(strOut,format);
	        try {
				xmlSerial.serialize(document.getDocumentElement());
			} catch (IOException e1) {
				e1.printStackTrace();
			}
	        registroXML = strOut.toString();
	        
	        
	        try {
				//Preparar el contenido para enviarlo como binario
				printout.writeUTF (registroXML);
			} catch (IOException e2) {
				e2.printStackTrace();
			}
	        
	        byte[] barray = fos.toByteArray();
	        byte[] barray1 = new byte[barray.length-2];
	        System.arraycopy(barray, 2, barray1, 0, barray.length-2);

	        //Enviar al servicio de Registro Telematico la informacion
	        try {
				url = new URL ("http://ariesdes.cjap.junta-andalucia.es/serviceAries/regService3l.asp");
//	        	url = new URL ("http://cefiro.upo.es/rt/actas.asp");
	        	
	        	/* Si esta detras de un proxy ....
	        	 * Properties properties = System.getProperties();
	        	properties.put("proxySet", "true");
	        	properties.put("http.proxyHost", "128.90.0.155");
	        	properties.put("http.proxyPort", "8080");
	        	Authenticator.setDefault(new MyAuthenticator());*/

	        	
				urlConn = url.openConnection();
				urlConn.setDoInput (true);
				urlConn.setDoOutput (true);
				urlConn.setUseCaches (false);
				urlConn.setRequestProperty("Content-Type", "text/plain");
				printout = new DataOutputStream (urlConn.getOutputStream ());
				printout.write (barray1);
				printout.flush ();
				printout.close ();
			} catch (MalformedURLException e3) {
				e3.printStackTrace();
			} catch (IOException e3) {
				e3.printStackTrace();
			}


	        //Leer la respuesta del Registro Telematico    
	        Document docRes=null;
			try {
				docRes = builder.parse(urlConn.getInputStream ());
			} catch (SAXException e4) {
				e4.printStackTrace();
			} catch (IOException e4) {
				e4.printStackTrace();
			}
			Element element = docRes.getDocumentElement();
	        NodeList nodelist1 = element.getElementsByTagName("Error_Code");
	        if(nodelist1.item(0).hasChildNodes())
	           {
	              errorCode = nodelist1.item(0).getFirstChild().getNodeValue();
	           }
 
	        NodeList nodelist2 = element.getElementsByTagName("Error_Desc");
	        if(nodelist2.item(0).hasChildNodes())
	           {
	              errorDesc = nodelist2.item(0).getFirstChild().getNodeValue();
	           }
	        if( errorCode.equals("0") || errorCode.equals("97") || errorCode.equals("98") || errorCode.equals("99")){
		        NodeList nodelist3 = element.getElementsByTagName("Numero_Registro");
                nRegistro = nodelist3.item(0).getFirstChild().getNodeValue();              
		        NodeList nodelist4 = element.getElementsByTagName("Fecha_Registro");
                fRegistro = nodelist4.item(0).getFirstChild().getNodeValue();
                System.out.println("Numero:"+nRegistro+"\tFecha/hora:"+fRegistro);
		        NodeList nodelist5 = element.getElementsByTagName("Sello_de_Tiempo");
		        if(nodelist5.item(0).hasChildNodes())
		           {
		              sTiempo = nodelist5.item(0).getFirstChild().getNodeValue();
		              System.out.println("TimeStamp: "+sTiempo);
		           }	        	
		        if (Integer.parseInt(errorCode)>96){
		        	  System.out.println("Aviso:"+errorDesc);
		        }
	        }else{
	        	System.out.println("Error:"+errorCode+"->"+errorDesc);
	        	
	        }
	        
	        

		
	}
}	
class MyAuthenticator extends Authenticator{
	protected PasswordAuthentication
	getPasswordAuthentication(){
	return new PasswordAuthentication("proxyuser","proxypass".toCharArray());
	}}