/*
 * AwbParseSax.java
 *
 * Created on 16 de Dezembro de 2002, 09:30
 */

/**
 *
 * @author  Carlos Zaparoli
 */

import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import org.apache.xerces.parsers.SAXParser;
import java.io.*;
import java.io.File;
import java.net.*;
import java.net.URL;
import java.util.Properties;
import java.util.Date;
import javax.mail.*;
import javax.activation.*;
import javax.mail.internet.*;


public class AwbParseSax extends DefaultHandler{
    
    static int numeroLinhas = 0;
    static String urlMovimento = "http://www.kfcargo.com.br/cadmovimento.php?";
    static String urlCliente   = "http://www.kfcargo.com.br/cadcliente.php?";
    static String urlNotaFiscal= "http://www.kfcargo.com.br/cadnotafiscal.php?";
    static String urlFatura    = "http://www.kfcargo.com.br/cadfatura.php?";
    static String urlWebLogin  = "http://www.kfcargo.com.br/cadweblogin.php?";    
    static String urlEnviada   = null;
    static boolean naoDeuErro = true;
    String nomeTag = null;
    static String listaArquivos[] = null;
    /** Creates a new instance of AwbParseSax */
    public AwbParseSax() {
    }
    public static void main( String args[]){
        System.out.println("Status : sistema rodando... ");
        File diretorio = new File("/windows/WEB/");
        File arq = null;
    
        while(true){
            listaArquivos = diretorio.list(new XmlFileFilter());
            for(int tempo = 0 ; tempo<100000000; tempo++){  
            }
            if(listaArquivos.length>0){
                for(int index = 0 ; index <= listaArquivos.length-1; index++){
                    naoDeuErro = true;
                    percorreDocumento(listaArquivos[index]);
                    arq = new File("/windows/WEB/"+listaArquivos[index]);
                    if (naoDeuErro){
                        if (!arq.delete()){
                            
                        System.out.println("Nao foi possivel apagar o arquivo "+listaArquivos[index]);
                    }
                    }else{
                        File velho = new File("/windows/WEB/"+listaArquivos[index]);
                        int i = 0;
                        for(i = 1; i<velho.length();i++)
                            if(listaArquivos[index].charAt(i)=='.') break;
                        File novo = new File("/windows/WEB/"+listaArquivos[index].subSequence(0, i)+".ERR");
                        velho.renameTo(novo);
                    }
                    
                }
                System.out.println("Status : sistema rodando... ");
            }
            
        }
    }
    
    public void startElement(String url, String localName, String rawName, Attributes attributes){
        nomeTag = rawName;
    }
    public void characters(char characters[], int start, int length){
        String dados = (new String(characters,start, length)).trim();
        if(dados.indexOf("\n")<0 && dados.length()>0){
            urlEnviada += nomeTag+"="+dados + "&";
        }
    }
    public void endDocument(){
       
        String texto = urlEnviada.substring(0,urlEnviada.length()-1);
        String texto2 = "";
        int ind2 = 0;
        for(int ind=0;ind<=texto.length()-1;ind++){
            if(texto.charAt(ind)==' '){
                texto2 += texto.substring(ind2,ind)+"%20";
                ind2 = ind + 1;
            }
        }
        texto2 += texto.substring(ind2);
        texto = texto2;
        texto2 = "";
        ind2 = 0;
        for(int ind=0;ind<=texto.length()-1;ind++){
            if(texto.charAt(ind)=='\\'){
                texto2 += texto.substring(ind2,ind)+"\\&";
                ind2 = ind + 1;
            }
        }
        texto2 += texto.substring(ind2);
        texto = texto2;        
        URLConnection con = null;
        String line = null;
        try{
            URL urlPassada = new URL(texto);
            con = urlPassada.openConnection();
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            System.out.println(con.getURL().toExternalForm());
            
            con.setRequestProperty("CONTENT_LENGTH", "5"); // Not checked

     //       con.setRequestProperty("METHOD", "POST");
     //       con.connect();
        }
        catch(MalformedURLException e){
            naoDeuErro = false;
            e.printStackTrace();
            
            new SendHtml(e.toString());
        }
        catch(UnknownHostException e ){
            naoDeuErro = false;
            e.printStackTrace();
            new SendHtml(e.toString());            
        }
        catch (IOException e ){
            naoDeuErro = false;
            e.printStackTrace();
            new SendHtml(e.toString());            
        }
        try{
            InputStream is = con.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            while ( (line = br.readLine()) != null)
            {
                System.out.println("line: " + line);
            }
        }
        catch (Throwable t){
            naoDeuErro = false;
            t.printStackTrace();
            new SendHtml(t.toString());
        }
    }
    public static void percorreDocumento(String url){
        try{
            System.out.println(url.subSequence(0, 2));
            if (url.subSequence(0, 2).equals((String)"MV")){
                
                urlEnviada = urlMovimento;
            }
            if (url.subSequence(0, 2).equals((String)"CL")){
                urlEnviada = urlCliente;
            }
            if (url.subSequence(0, 2).equals((String)"NF")){
                urlEnviada = urlNotaFiscal;
            }
            if (url.subSequence(0, 2).equals((String)"FT")){
                urlEnviada = urlFatura;
            }
            if (url.subSequence(0, 2).equals((String)"LG")){
                urlEnviada = urlWebLogin;
            }            
            AwbParseSax SAXHandler = new AwbParseSax();
            SAXParser parser = new SAXParser();
            parser.setContentHandler(SAXHandler);
            parser.setErrorHandler(SAXHandler);
//            parser.parse("/WEB/"+url);
            parser.parse("/windows/WEB/"+url);
        }
        catch(Exception e){
            naoDeuErro = false;
            e.printStackTrace();
            new SendHtml(e.toString());
//            new SendHtml(e.toString());            
        }
    }
}
class XmlFileFilter implements FilenameFilter{
    
    /** Tests if a specified file should be included in a file list.
     *
     * @param   dir    the directory in which the file was found.
     * @param   name   the name of the file.
     * @return  <code>true</code> if and only if the name should be
     * included in the file list; <code>false</code> otherwise.
     *
     */
    public boolean accept(File dir, String name) {
        return name.endsWith(".XML");
    }
}
class SendHtml {


    public SendHtml(String body) {

	String  to = "carloszaparoli@terra.com.br", subject = "Erro KF CARGO", from = "kfcargo@kfcargo.com.br", 
		cc = "carloszaparoli@hotmail.com", bcc = null, url = null;
	String mailhost = "smtp.zaparoli.com.br";
	String mailer = "sendhtml";
	String protocol = null, host = "smtp.zaparoli.com.br", user = "kfcargo@kfcargo.com.br", password = "alterar";
	String record = null;	// name of folder in which to record mail
        String textoMail  = body;
	boolean debug = false;
	BufferedReader in =
			new BufferedReader(new InputStreamReader(System.in));
	int optind;

		debug = true;
        
	try {

	    Properties props = System.getProperties();
	    // XXX - could use Session.getTransport() and Transport.connect()
	    // XXX - assume we're using SMTP
	    if (mailhost != null)
		props.put("mail.smtp.host", mailhost);

	    // Get a Session object
	    Session session = Session.getDefaultInstance(props, null);
	    if (debug)
		session.setDebug(true);

	    // construct the message
	    Message msg = new MimeMessage(session);
	    if (from != null)
		msg.setFrom(new InternetAddress(from));
	    else
		msg.setFrom();

	    msg.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(to, false));
	    if (cc != null)
		msg.setRecipients(Message.RecipientType.CC,
					InternetAddress.parse(cc, false));
	    if (bcc != null)
		msg.setRecipients(Message.RecipientType.BCC,
					InternetAddress.parse(bcc, false));

	    msg.setSubject(subject);

	    collect(in, msg, textoMail);

	    msg.setHeader("X-Mailer", mailer);
	    msg.setSentDate(new Date());

	    // send the thing off
	    Transport.send(msg);

	    System.out.println("\nMail was sent successfully.");

	    // Keep a copy, if requested.

	    if (record != null) {
		// Get a Store object
		Store store = null;
		if (url != null) {
		    URLName urln = new URLName(url);
		    store = session.getStore(urln);
		    store.connect();
		} else {
		    if (protocol != null)		
			store = session.getStore(protocol);
		    else
			store = session.getStore();

		    // Connect
		    if (host != null || user != null || password != null)
			store.connect(host, user, password);
		    else
			store.connect();
		}

		// Get record Folder.  Create if it does not exist.
		Folder folder = store.getFolder(record);
		if (folder == null) {
		    System.err.println("Can't get record folder.");
		    System.exit(1);
		}
		if (!folder.exists())
		    folder.create(Folder.HOLDS_MESSAGES);

		Message[] msgs = new Message[1];
		msgs[0] = msg;
		folder.appendMessages(msgs);

		System.out.println("Mail was recorded successfully.");
	    }

	} catch (Exception e) {
	    e.printStackTrace();
	}
    }

    public void collect(BufferedReader in, Message msg, String texto)
					throws MessagingException, IOException {
	String line;
	String subject = msg.getSubject();
	StringBuffer sb = new StringBuffer();
	sb.append("<HTML>\n");
	sb.append("<HEAD>\n");
	sb.append("<TITLE>\n");
	sb.append(subject + "\n");
	sb.append("</TITLE>\n");
	sb.append("</HEAD>\n");

	sb.append("<BODY>\n");
	sb.append("<H1>" + subject + "</H1>" + "\n");

	sb.append(texto);

	sb.append("</BODY>\n");
	sb.append("</HTML>\n");

	msg.setDataHandler(new DataHandler(
		new ByteArrayDataSource(sb.toString(), "text/html")));
    }
}

