
package dblpconverter;

/**
 * @author Gersk
 * 
 * SaxThread manage the external application SaxParser and SaxCount. It's pass the 
 * output of SaxParser to XMLManager object.
 */

import java.io.*;
import java.util.StringTokenizer;

public class SaxThread implements Runnable {
    
    private Window window;
    private XMLManager xmlManager;
    private DatabaseManager dbManager;
    
    private Runtime rt;
    private Process proc;
    
    private File xmlFile;
    
    private String saxCounter, saxParser;
    
    private StringTokenizer tokenizer;
    
    public SaxThread(String saxCounter, String saxParser)
    {   
        rt = Runtime.getRuntime();
        this.saxCounter = saxCounter;
        this.saxParser = saxParser;
    }
    
    public void setWindow(Window window)
    {
        this.window = window;
    }
    
    public void setXMLManager(XMLManager xmlManager) 
    {
        this.xmlManager = xmlManager;
    }
    
    public void setDbManager(DatabaseManager dbManager) 
    {
        this.dbManager = dbManager;
    }
    
    public void setFile(File xmlFile)
    {
        this.xmlFile = xmlFile;
    } 
    
    public void run() //start the parsing precess 
    {
        window.append("Estimate dimension...");
        try {
            proc = rt.exec(saxCounter + " " + xmlFile.getPath());
            countParser(proc.getInputStream());
        } catch(IOException e) {
            window.append("Error execute process : " + e);
          }
        
        window.append("Start parsing...");
        
        try {
            proc = rt.exec(saxParser + " " + xmlFile.getPath());
        } catch(IOException e) {
            window.append("Error execute process : " + e);
          }
        
        xmlManager.parse(proc.getInputStream());
        
    }
    
    public void stop()
    {
        proc.destroy();
    }
    
    public void countParser(InputStream is)
    {
        BufferedReader nin = new BufferedReader( new InputStreamReader(is));
        String [] buffer = new String[11];
        
        try {
            tokenizer = new StringTokenizer(nin.readLine());
        } catch(Exception e) {
            window.append("Error in countParser: " + e );
        }
        
        for(int i = 0; tokenizer.hasMoreTokens() ; i++) 
        {
            buffer[i] = tokenizer.nextToken();    
        } 
        
        window.setValue(Integer.parseInt(buffer[3].replace("(", "")), Integer.parseInt(buffer[5]), Integer.parseInt(buffer[9]));  

    }
}
