/*
 * IReportCompiler.java
 *
 *  iReport  --  Visual designer for generating JasperReports Documents
 *  Copyright (C) 2002-2003  Giulio Toffoli gt@businesslogic.it
 *
 *  This program is free software; you can redistribute  and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *  Giulio Toffoli
 *  Via T.Aspetti, 233
 *  35100 Padova ITALY
 *  gt@businesslogic.it
 *
 *
 * Created on 6 giugno 2003, 0.44
 */

package it.businesslogic.ireport;
import it.businesslogic.ireport.gui.*;
import it.businesslogic.ireport.gui.logpane.*;
import it.businesslogic.ireport.connection.*;
import it.businesslogic.ireport.util.*;
import java.util.*;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.view.*;
import net.sf.jasperreports.engine.export.*;
import net.sf.jasperreports.engine.query.JRHibernateQueryExecuterFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;

/**
 * Please note that this class is totally different from the old IReportCompiler.class
 * shipped with iReport 1.
 * @author  Administrator
 */
public class IReportCompiler implements Runnable, JRExportProgressMonitor
{
   
   public static final int CMD_COMPILE  = 0x01;
   public static final int CMD_EXPORT   = 0x02;
   public static final int CMD_COMPILE_SCRIPTLET = 0x04;
   
   public static final String OUTPUT_DIRECTORY     = "OUTPUT_DIRECTORY";
   public static final String OUTPUT_FORMAT        = "OUTPUT_FORMAT";
   public static final String USE_EMPTY_DATASOURCE = "USE_EMPTY_DATASOURCE";
   public static final String USE_CONNECTION = "USE_CONNECTION";
   public static final String CONNECTION = "CONNECTION";   
   public static final String SCRIPTLET_OUTPUT_DIRECTORY = "SCRIPTLET_OUTPUT_DIRECTORY";
   public static final String COMPILER = "COMPILER";
   public static final String EMPTY_DATASOURCE_RECORDS = "EMPTY_DATASOURCE_RECORDS";
   
   private String constTabTitle = "";
   private javax.swing.JList threadList = null;
   
   static PrintStream myPrintStream = null;
   int filledpage=0;
   
   
   private String status="Staring";
   private IReportConnection iReportConnection;
   private int statusLevel = 0;
   
   private JReportFrame jrf;
   
   private MainFrame mainFrame;
   
   private int command;
   
   private HashMap properties;
   
   private Thread thread;
   
   private LogTextArea logTextArea = null;
   
   private String javaFile = "";
   static private String outputBuffer = "";
      
   /** Creates a new instance of IReportCompiler */
   public IReportCompiler()
   {
      properties = new HashMap();
      command = 0;
   }
   
   public void stopThread()
   {
       command = 0;
       if (thread != null && thread.isAlive())
       {
           try  {
                thread.interrupt();
           } catch (Exception ex)
           {
               ex.printStackTrace();
           }
       }
       removeThread();

       getLogTextArea().setTitle("Killed" + constTabTitle);
       getLogTextArea().setRemovable(true);
       System.gc();
   }
   
   /** When an object implementing interface <code>Runnable</code> is used
    * to create a thread, starting the thread causes the object's
    * <code>run</code> method to be called in that separately executing
    * thread.
    * <p>
    * The general contract of the method <code>run</code> is that it may
    * take any action whatsoever.
    *
    * @see     java.lang.Thread#run()
    *
    */
   public void run()
   {
      
      if (threadList != null)
      {
         javax.swing.DefaultListModel dlm = (javax.swing.DefaultListModel)threadList.getModel();
         dlm.addElement(this);
         threadList.updateUI();
      }
      
      File f_report_title = new File(this.getJrf().getReport().getFilename());
      constTabTitle = " [" + f_report_title.getName() + "]";
      
      logTextArea = getMainFrame().getLogPane().createNewLog();
      logTextArea.setTitle(status + constTabTitle);
      
      String backupJRClasspath = net.sf.jasperreports.engine.util.JRProperties.getProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_CLASSPATH);
      // System.getProperty("jasper.reports.compile.class.path");
      String backupSystemClasspath = System.getProperty("java.class.path");
      
      boolean compilation_ok = true;
      long start = System.currentTimeMillis();
      // Redirect output stream....
      PrintStream out = System.out;
      PrintStream err = System.err;
      if (myPrintStream == null)
         myPrintStream  =new PrintStream(new FilteredStream(new ByteArrayOutputStream()));
      
      if (out != myPrintStream)
         System.setOut(myPrintStream);
      if (err != myPrintStream)
         System.setErr(myPrintStream);
      
      outputBuffer="";
      
      
	//by Egon - DEBUG: Something is wrong here, please check. ok? thx.
	//1 - Line 148 - srcScriptletFileName = C:\jasperreports-0.5.3\demo\samples\jasper\FirstJasper.jrxmScriptlet.java -> scriptlet filename
	//2 - Line 157 - Misc.nvl( new File(fileName).getParent(), ".") =>  .  -> report directory
      
      // Add an entry in the thread list...
    //by Egon - DEBUG: C:\jasperreports-0.5.3\demo\samples\jasper\FirstJasper.jrxml
      String fileName = jrf.getReport().getFilename();
      
	//by Egon - DEBUG: C:\jasperreports-0.5.3\demo\samples\jasper\FirstJasper.jrxml
      String srcFileName = jrf.getReport().getFilename();
	//by Egon - DEBUG: C:\jasperreports-0.5.3\demo\samples\jasper\FirstJasper.jasper
      fileName = Misc.changeFileExtension(fileName,"jasper");
      
      
      File f = new File(fileName);
      if (properties.get(this.OUTPUT_DIRECTORY) != null)
      {
		//by Egon - DEBUG: .\FirstJasper.jasper
         fileName = (String)properties.get(this.OUTPUT_DIRECTORY);
         if (!fileName.endsWith(f.separator))
         {
         	fileName += f.separator; 
         }
         fileName += f.getName();
      }
      
	//by Egon - DEBUG: C:\jasperreports-0.5.3\demo\samples\jasper\FirstJasper.jrxml
      String scriptletFileName = jrf.getReport().getFilename();
	//by Egon - DEBUG: C:\jasperreports-0.5.3\demo\samples\jasper\FirstJasper.jrxml
      String srcScriptletFileName = jrf.getReport().getFilename();
	//by Egon - DEBUG: .\FirstJasper.
      //fileName = Misc.changeFileExtension(fileName,"");
	//by Egon - DEBUG: C:\jasperreports-0.5.3\demo\samples\jasper\FirstJasper.jrxmScriptlet.java
      scriptletFileName = srcScriptletFileName.substring(0,scriptletFileName.length()-1)+"Scriptlet.java";
	//1 - by Egon - DEBUG: C:\jasperreports-0.5.3\demo\samples\jasper\FirstJasper.jrxmScriptlet.java
      srcScriptletFileName = scriptletFileName;
      
      File f2 = new File(scriptletFileName);
      if (properties.get(this.SCRIPTLET_OUTPUT_DIRECTORY) != null)
      {
         scriptletFileName = (String)properties.get(this.SCRIPTLET_OUTPUT_DIRECTORY) + f2.separatorChar + f2.getName();
      }
            
      
       String reportDirectory = new File(jrf.getReport().getFilename()).getParent();
       //String classpath = System.getProperty("jasper.reports.compile.class.path");
       String classpath = net.sf.jasperreports.engine.util.JRProperties.getProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_CLASSPATH);
      
       
       
       if(classpath != null){
            classpath += File.pathSeparator + reportDirectory; 
            //System.setProperty("jasper.reports.compile.class.path", classpath);
            net.sf.jasperreports.engine.util.JRProperties.setProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_CLASSPATH, classpath);
      } else if (System.getProperty("java.class.path") != null){
        classpath = System.getProperty("java.class.path");
        classpath += File.pathSeparator + reportDirectory; 
        System.setProperty("java.class.path", classpath);
        }
       reportDirectory = reportDirectory.replace('\\', '/');
       if(!reportDirectory.endsWith("/")){
            reportDirectory += "/";//the file path separator must be present
       }
       if(!reportDirectory.startsWith("/")){
            reportDirectory = "/" + reportDirectory;//it's important to JVM 1.4.2 especially if contains windows drive letter
       }
       ReportClassLoader reportClassLoader = new ReportClassLoader();
       reportClassLoader.setRelodablePaths( reportDirectory );
       reportClassLoader.rescanLibDirectory();
       
       /******************/

       try{
            Thread.currentThread().setContextClassLoader(new URLClassLoader(new URL[]{new URL("file://"+reportDirectory)},  reportClassLoader));
       } catch (MalformedURLException mue){
            mue.printStackTrace();
       }

       /******************/
       
       //.setContextClassLoader(reportClassLoader);
       
       if ((command & CMD_COMPILE_SCRIPTLET) != 0)
      {
         status  ="compiling scriptlet";
         updateThreadList();
         start = System.currentTimeMillis();
      
         // Compile the scriptlet class...
         
         //String tempDirStr = System.getProperty("jasper.reports.compile.temp");
         String tempDirStr = net.sf.jasperreports.engine.util.JRProperties.getProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_TEMP_DIR);
         
         String oldCompileTemp  = tempDirStr;
         if (tempDirStr == null || tempDirStr.length() == 0 || mainFrame.isUsingCurrentFilesDirectoryForCompiles())
         {
            tempDirStr = mainFrame.getTranslatedCompileDirectory();
         }
         File tempDirFile = new File(tempDirStr);
         javaFile = srcScriptletFileName;
         javaFile = (new File(tempDirFile,javaFile)).getPath();
         
         javaFile = jrf.getReport().getScriptletFileName();
         
         
         
         if (Misc.getLastWriteTime(javaFile) > Misc.getLastWriteTime(Misc.changeFileExtension(javaFile, "class" )))
         {
         	 getLogTextArea().logOnConsole("<font face=\"SansSerif\" size=\"3\" color=\"#000000\">Compiling scriptlet source file... " + javaFile +"</font>",true);
	         try
	         {
	            //JasperCompileManager.compileReportToFile(srcFileName, fileName);
	            net.sf.jasperreports.engine.design.JRJdk13Compiler compiler = new net.sf.jasperreports.engine.design.JRJdk13Compiler();
	            String errors = compiler.compileClass( new File(javaFile),   Misc.getClassPath() );
	            if (errors != null && errors.length() > 0)
                    {
                        getLogTextArea().logOnConsole("<font face=\"SansSerif\"  size=\"3\" color=\"#CC0000\"><b>Errors compiling "+javaFile+"!</b></font>",true);
                        getLogTextArea().logOnConsole(errors);
                        compilation_ok = false;
                    }
                 } 
	         /*
	         catch (Exception jrex)
	         {
	             
	            getLogTextArea().logOnConsole("<font face=\"SansSerif\"  size=\"3\" color=\"#CC0000\"><b>Errors compiling "+scriptletFileName+"!</b></font>",true);
	            //1. load the java file
	            Vector source = new Vector();
	            try
	            {
	               java.io.BufferedReader is = new java.io.BufferedReader(new java.io.FileReader( javaFile ));
	               while (true)
	               {
	                  String line = is.readLine();
	                  if (line == null) break;
	                  source.addElement(line);
	               }
	               is.close();
	            } catch (Exception ioex)
	            {
	               // No file readed....
	            }
	            //2. write exception in a string
	            StringWriter sw = new StringWriter(0);
	            jrex.printStackTrace(new PrintWriter(sw));
	            
	            System.out.println("\n\n\n");
	            myPrintStream.flush();
	            parseException( outputBuffer+sw.getBuffer()+"", source);
	
	         }
	         */
	         catch (Exception ex)
	         {
	            getLogTextArea().logOnConsole("<font face=\"SansSerif\"  size=\"3\" color=\"#CC0000\"><b>Error compiling the Scriptlet java source!</b></font>",true);
	            StringWriter sw = new StringWriter(0);
	            ex.printStackTrace(new PrintWriter(sw));
	            myPrintStream.flush();
	            parseException( outputBuffer+sw.getBuffer()+"", null);
	            compilation_ok = false;
	         }
	         catch (Throwable ext)
	         {
	            getLogTextArea().logOnConsole("<font face=\"SansSerif\"  size=\"3\" color=\"#CC0000\"><b>Error compiling the Scriptlet java source!</b></font>",true);
	            StringWriter sw = new StringWriter(0);
	            ext.printStackTrace(new PrintWriter(sw));
	            myPrintStream.flush();
	            parseException( outputBuffer+sw.getBuffer()+"", null);
	            compilation_ok = false;
	         }
	         finally
	         {
	            if(mainFrame.isUsingCurrentFilesDirectoryForCompiles())
	            {
	                /*
	               if( oldCompileTemp != null )
	               {
	                  System.setProperty("jasper.reports.compile.temp", oldCompileTemp);
	               }
	               else
	               {
	                  System.setProperty("jasper.reports.compile.temp", "");
	               }
	                 */
	            }//end if using current files directory for compiles
	         }//end finally
	         getLogTextArea().logOnConsole(outputBuffer);
         	 outputBuffer="";
                 getLogTextArea().logOnConsole("<font face=\"SansSerif\"  size=\"3\" color=\"#0000CC\"><b>Compilation running time : " + (System.currentTimeMillis() - start) + "</b></font><hr>",true); 
         }         
      }
      
      if (!compilation_ok) {
          
          removeThread();
          return;
      }
      
      if ((command & CMD_COMPILE) != 0)
      {
         status  ="compiling report";
         updateThreadList();
         
         //System.setProperty("jasper.reports.compile.keep.java.file", "true");
         
         if (mainFrame.getProperties().getProperty("KeepJavaFile","true").equals("false") )
         {
         	net.sf.jasperreports.engine.util.JRProperties.setProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_KEEP_JAVA_FILE, false);
         }
         else
         {
         	net.sf.jasperreports.engine.util.JRProperties.setProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_KEEP_JAVA_FILE, true);
         }
         
         //System.setProperty("jasper.reports.compile.temp", "C:\\");
         // Compile report....
         javaFile = this.jrf.getReport().getName()+".java";
         
         //String tempDirStr = System.getProperty("jasper.reports.compile.temp");
         String tempDirStr = net.sf.jasperreports.engine.util.JRProperties.getProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_TEMP_DIR);
         
         String oldCompileTemp  = tempDirStr;
         if (tempDirStr == null || tempDirStr.length() == 0 || mainFrame.isUsingCurrentFilesDirectoryForCompiles())
         {
            tempDirStr = mainFrame.getTranslatedCompileDirectory();
         }
         File tempDirFile = new File(tempDirStr);
         javaFile = (new File(tempDirFile,javaFile)).getPath();
                  
         URL img_url_comp = this.getClass().getResource("/it/businesslogic/ireport/icons/comp1_mini.jpg");

         getLogTextArea().logOnConsole("<font face=\"SansSerif\" size=\"3\" color=\"#000000\"><img align=\"right\" src=\""+  img_url_comp  +"\"> &nbsp;Compiling to file... " + fileName + " -> "+javaFile+"</font>",true);
         
         //String old_jr_classpath = Misc.nvl( System.getProperty("jasper.reports.compile.class.path"), "");
         //String old_defaul_compiler = Misc.nvl( System.getProperty("jasper.reports.compiler.class"), "");
         String old_jr_classpath = Misc.nvl(net.sf.jasperreports.engine.util.JRProperties.getProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_CLASSPATH), "");
         String old_defaul_compiler = Misc.nvl(net.sf.jasperreports.engine.util.JRProperties.getProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_CLASS), "");
                        
         try
         {
            if( mainFrame.isUsingCurrentFilesDirectoryForCompiles() )
            {
               //System.setProperty("jasper.reports.compile.temp", tempDirStr);
               net.sf.jasperreports.engine.util.JRProperties.setProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_TEMP_DIR, tempDirStr);
         
            }
            
            //System.setProperty("jasper.reports.compile.class.path", Misc.nvl( new File(fileName).getParent(), ".")  + File.pathSeparator  + Misc.getClassPath());
            net.sf.jasperreports.engine.util.JRProperties.setProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_CLASSPATH, Misc.nvl( new File(fileName).getParent(), ".")  + File.pathSeparator  + Misc.getClassPath()); 
           
            //System.out.println("CP:" + System.getProperty("jasper.reports.compile.class.path"));
            //System.out.println("\nOLDCP:" +old_jr_classpath);

            String compiler_name  = "JasperReports default compiler";
            String compiler_code = mainFrame.getProperties().getProperty("DefaultCompiler");
            
            if (this.getProperties().get(COMPILER) != null)
            {
                //System.setProperty("jasper.reports.compiler.class", ""+this.getProperties().get(COMPILER) );
                net.sf.jasperreports.engine.util.JRProperties.setProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_CLASS, ""+this.getProperties().get(COMPILER));
                compiler_name = "Special language compiler (" + this.getProperties().get(COMPILER) + ")";
            }
            else if (compiler_code !=  null && !compiler_code.equals("0") && !compiler_code.equals(""))
            {
                if (compiler_code.equals("1"))
                {
                    //System.setProperty("jasper.reports.compiler.class","net.sf.jasperreports.engine.design.JRJdk13Compiler"  );
                    net.sf.jasperreports.engine.util.JRProperties.setProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_CLASS, "net.sf.jasperreports.engine.design.JRJdk13Compiler");
                    compiler_name = "Java Compiler";
                }
                else if (compiler_code.equals("2"))
                {
                    //System.setProperty("jasper.reports.compiler.class","net.sf.jasperreports.engine.design.JRJdtCompiler"  );
                    net.sf.jasperreports.engine.util.JRProperties.setProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_CLASS, null ); //"net.sf.jasperreports.engine.design.JRJdtCompiler"
                    compiler_name = "JDT Compiler";
                    Thread.currentThread().setContextClassLoader( reportClassLoader );
                    ClassLoader cl = getClassLoader();
                    System.out.println(  cl );
                }
                else if (compiler_code.equals("3"))
                {
                    //System.setProperty("jasper.reports.compiler.class","net.sf.jasperreports.engine.design.JRBshCompiler"  );
                    net.sf.jasperreports.engine.util.JRProperties.setProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_CLASS, "net.sf.jasperreports.engine.design.JRBshCompiler" );
                    compiler_name = "BeanShell Compiler";
                }
                else if (compiler_code.equals("4"))
                {
                    //System.setProperty("jasper.reports.compiler.class","net.sf.jasperreports.engine.design.JRJikesCompiler"  );
                    net.sf.jasperreports.engine.util.JRProperties.setProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_CLASS, "net.sf.jasperreports.engine.design.JRJikesCompiler" );
                    compiler_name = "Jikes Compiler";
                }
            }
            else
            {
                 //System.setProperty("jasper.reports.compiler.class","" );
                 net.sf.jasperreports.engine.util.JRProperties.setProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_CLASS, "" );
                 Thread.currentThread().setContextClassLoader( reportClassLoader );
                    ClassLoader cl = getClassLoader();
                    System.out.println(  cl );
            }
            
            
           // getLogTextArea().logOnConsole("<font face=\"SansSerif\"  size=\"3\" color=\"#000000\"><b>Using compiler "+ compiler_name  + " (" + System.getProperty("jasper.reports.compiler.class","" ) +")</b></font>",true);
            start = System.currentTimeMillis();
            
            JasperCompileManager.compileReportToFile(srcFileName, fileName);
               
            
         } catch (JRException jrex)
         {
             compilation_ok = false;
            getLogTextArea().logOnConsole("<font face=\"SansSerif\"  size=\"3\" color=\"#CC0000\"><b>Errors compiling "+fileName+"!</b></font>",true);
            //1. load the java file
            Vector source = new Vector();
            try
            {
               java.io.BufferedReader is = new java.io.BufferedReader(new java.io.FileReader( javaFile ));
               while (true)
               {
                  String line = is.readLine();
                  if (line == null) break;
                  source.addElement(line);
               }
               is.close();
               
            } catch (Exception ioex)
            {
               // No file readed....
            }
            //2. write exception in a string
            StringWriter sw = new StringWriter(0);
            jrex.printStackTrace(new PrintWriter(sw));
            
            System.out.println("\n\n\n");
            myPrintStream.flush();
            parseException( outputBuffer+sw.getBuffer()+"", source);
            
            
            
         }
         catch (Exception ex)
         {
            getLogTextArea().logOnConsole("<font face=\"SansSerif\"  size=\"3\" color=\"#CC0000\"><b>Error compiling the report java source!</b></font>",true);
            StringWriter sw = new StringWriter(0);
            ex.printStackTrace(new PrintWriter(sw));
            myPrintStream.flush();
            parseException( outputBuffer+sw.getBuffer()+"", null);
            compilation_ok = false;
         }
         catch (Throwable ext)
         {
            getLogTextArea().logOnConsole("<font face=\"SansSerif\"  size=\"3\" color=\"#CC0000\"><b>Error compiling the report java source!</b></font>",true);
            StringWriter sw = new StringWriter(0);
            ext.printStackTrace(new PrintWriter(sw));
            myPrintStream.flush();
            parseException( outputBuffer+sw.getBuffer()+"", null);
            compilation_ok = false;
         }
         finally
         {
            //System.setProperty("jasper.reports.compile.class.path", old_jr_classpath);
            net.sf.jasperreports.engine.util.JRProperties.setProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_CLASSPATH, old_jr_classpath );
            //System.setProperty("jasper.reports.compiler.class", old_defaul_compiler);
            net.sf.jasperreports.engine.util.JRProperties.setProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_CLASS, old_defaul_compiler );
            
            if(mainFrame.isUsingCurrentFilesDirectoryForCompiles())
            {
               if( oldCompileTemp != null )
               {
                  System.setProperty("jasper.reports.compile.temp", oldCompileTemp);
                  net.sf.jasperreports.engine.util.JRProperties.setProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_TEMP_DIR, oldCompileTemp );
               }
               else
               {
                  System.setProperty("jasper.reports.compile.temp", "");
                  net.sf.jasperreports.engine.util.JRProperties.setProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_TEMP_DIR, "" );
               }
               
               File javaSrcFile = new File(javaFile);
               if (  javaSrcFile.exists() )
               if (mainFrame.getProperties().getProperty("KeepJavaFile","true").equals("false") )
               {
                    javaSrcFile.delete();
               }
            }//end if using current files directory for compiles
         }//end finally
         getLogTextArea().logOnConsole(outputBuffer);
         outputBuffer="";
         getLogTextArea().logOnConsole("<font face=\"SansSerif\"  size=\"3\" color=\"#0000CC\"><b>Compilation running time : " + (System.currentTimeMillis() - start) + "</b></font><hr>",true);
         
      }
      
     
      if (!compilation_ok) {
          
          removeThread();
          return;
      }
            
      if  ((command & CMD_EXPORT) != 0)
      {
         
         status  ="generating report";
         updateThreadList();
          
         // Compile report....
         JasperPrint print = null;
         URL img_url = this.getClass().getResource("/it/businesslogic/ireport/icons/rundb1_mini.jpg");

         getLogTextArea().logOnConsole("<font face=\"SansSerif\" size=\"3\" color=\"#000000\"><img align=\"right\" src=\""+  img_url  +"\"> &nbsp;Filling report... </font>",true);
         
         
         
         statusLevel = 5;
         HashMap hm = it.businesslogic.ireport.gui.prompt.Prompter.promptForParameters(this.getJrf().getReport());
         
         hm.put("REPORT_LOCALE",  Misc.getLocaleFromString(mainFrame.getProperties().getProperty("reportLocale")));
         
         img_url = this.getClass().getResource("/it/businesslogic/ireport/icons/world.png");
         getLogTextArea().logOnConsole("<font face=\"SansSerif\" size=\"3\" color=\"#000000\"><img align=\"right\" src=\""+  img_url  +"\"> &nbsp;Locale: <b>" + Misc.getLocaleFromString(mainFrame.getProperties().getProperty("reportLocale")).getDisplayName() + "</b></font>",true);
         
         
         int reportMaxCount = 0;
         try {
            reportMaxCount = Integer.parseInt(mainFrame.getProperties().getProperty("maxRecords","0"));
         } catch (Exception ex) {}
         
         if (reportMaxCount > 0)
         {
             img_url = this.getClass().getResource("/it/businesslogic/ireport/icons/file-info.png");
             getLogTextArea().logOnConsole("<font face=\"SansSerif\" size=\"3\" color=\"#000000\"><img align=\"right\" src=\""+  img_url  +"\"> &nbsp;Max number of records: <b>" + reportMaxCount + "</b></font>",true);
         
             hm.put("REPORT_MAX_COUNT",  new Integer(reportMaxCount) );
         }
         
         
        // Thread.currentThread().setContextClassLoader( reportClassLoader );

         
         
         if (it.businesslogic.ireport.gui.MainFrame.getMainInstance().isIgnorePagination())
         {
             hm.put("IS_IGNORE_PAGINATION",  Boolean.TRUE );
             img_url = this.getClass().getResource("/it/businesslogic/ireport/icons/file-info.png");
             getLogTextArea().logOnConsole("<font face=\"SansSerif\" size=\"3\" color=\"#000000\"><img align=\"right\" src=\""+  img_url  +"\"> &nbsp;Ignoring pagination</font>",true);
         
         }
         if (it.businesslogic.ireport.gui.MainFrame.getMainInstance().isUseReportVirtualizer())
         {
             try {
                 
                 
                 net.sf.jasperreports.engine.JRVirtualizer virtualizer = new net.sf.jasperreports.engine.fill.JRFileVirtualizer(
                            Integer.parseInt( mainFrame.getProperties().getProperty("ReportVirtualizerSize","100")),
                            mainFrame.getProperties().getProperty("ReportVirtualizerDirectory", mainFrame.getTranslatedCompileDirectory() ) );
                 
                 img_url = this.getClass().getResource("/it/businesslogic/ireport/icons/file-info.png");
                 getLogTextArea().logOnConsole("<font face=\"SansSerif\" size=\"3\" color=\"#000000\"><img align=\"right\" src=\""+  img_url  +"\"> &nbsp;Using report virtualizer... Size: " + Integer.parseInt( mainFrame.getProperties().getProperty("ReportVirtualizerSize","100000") ) + " Cache directory: " + mainFrame.getProperties().getProperty("ReportVirtualizerDirectory", mainFrame.getTranslatedCompileDirectory() ) + "</font>",true);
                   
                 
                   
                 hm.put("REPORT_VIRTUALIZER", virtualizer );
                 
             } catch (Throwable ex)
             {
                 getLogTextArea().logOnConsole("<font face=\"SansSerif\" size=\"3\" color=\"#660000\">WARNING: Report virtualizer not available.</font>",true);
         
             }
         }
         
         start = System.currentTimeMillis();
         
         if (properties.get(USE_EMPTY_DATASOURCE) != null && properties.get(USE_EMPTY_DATASOURCE).equals("true"))
         {
            try
            {
               int records = 1;
               try {
                   
                   records = ((Integer)properties.get(EMPTY_DATASOURCE_RECORDS)).intValue();
               } catch (Exception ex)
               {
                   records = 1;
               }
                
               print = JasperFillManager.fillReport(fileName,hm,new JREmptyDataSource(records));
               
            	  
            } catch (Exception ex)
            {
               getLogTextArea().logOnConsole("Error filling print...\n");
               ex.printStackTrace();
               getLogTextArea().logOnConsole(outputBuffer);
               outputBuffer ="";
            }
         }
         else if (properties.get(USE_CONNECTION) != null && properties.get(USE_CONNECTION).equals("true"))
         {
            IReportConnection connection = (IReportConnection)properties.get(CONNECTION);
               
            try
            {
               
               
               if (connection.isJDBCConnection())
               {
                  print = JasperFillManager.fillReport(fileName,hm, connection.getConnection());
               }
               else
               {
                   JRDataSource ds = null;
                   if (connection instanceof JRDataSourceProviderConnection)
                   {
                       
                        JasperReport jasper_report_obj = JasperManager.loadReport(fileName);
                        ds = (JRDataSource)((JRDataSourceProviderConnection)connection).getJRDataSource(jasper_report_obj);
                        
                        if (ds == null) return;
                        print = JasperFillManager.fillReport(jasper_report_obj,hm,ds);
                        
                        try { ((JRDataSourceProviderConnection)connection).disposeDataSource(); } catch (Exception ex) {
                            System.out.println("Error closing datasource: " + ex.getMessage());
                        }
                   }
                   else if (connection instanceof JRHibernateConnection)
                   {
                       Session session = null;
                       Transaction transaction = null;
                       System.out.println("Hibernate session opened");
                       try {
                            session = ((JRHibernateConnection)connection).createSession();
                            transaction = session.beginTransaction();
                            hm.put(JRHibernateQueryExecuterFactory.PARAMETER_HIBERNATE_SESSION, session);
                            print = JasperFillManager.fillReport(fileName,hm);
                            
                       } catch (Exception ex)
                       {
                           throw ex;
                       } finally
                       {
                            if (transaction != null) try {  transaction.rollback(); } catch (Exception ex) { }
                            if (session != null) try {  session.close(); 
                                System.out.println("Hibernate session closed");
                            } catch (Exception ex) { }
                       }
                   }
                   else
                   {
                       ds = (JRDataSource)connection.getJRDataSource();
                       print = JasperFillManager.fillReport(fileName,hm,ds);
                   }
                   
               
               }
               
            } catch (Exception ex)
            {
               getLogTextArea().logOnConsole("Error filling print...\n");
               ex.printStackTrace();
               getLogTextArea().logOnConsole(outputBuffer);
               outputBuffer ="";
            }
            catch (Throwable ext)
            {
               getLogTextArea().logOnConsole("Error filling print...\n");
               ext.printStackTrace();
               getLogTextArea().logOnConsole(outputBuffer);
               outputBuffer ="";
            }
            finally
            {
                if (connection != null && connection instanceof JRDataSourceProviderConnection)
                {
                        try { ((JRDataSourceProviderConnection)connection).disposeDataSource(); } catch (Exception ex) {
                            System.out.println("Error closing datasource: " + ex.getMessage());
                        }
                       
                }
                
            }
         }
         net.sf.jasperreports.view.JRViewer jrv = null;
         net.sf.jasperreports.engine.JRExporter exporter=null;
         
         getLogTextArea().logOnConsole(outputBuffer);
         outputBuffer ="";
         
         if (print != null)
         {
            getLogTextArea().logOnConsole("<font face=\"SansSerif\"  size=\"3\" color=\"#0000CC\"><b>Report fill running time : " + (System.currentTimeMillis() - start) + "</b> (pages generated: " + ((List)print.getPages()).size() + ")</font><hr>",true);
         
            status  ="exporting report";
            updateThreadList();
             
            start = System.currentTimeMillis();
            String  format = Misc.nvl(properties.get(OUTPUT_FORMAT),"pdf");
            String  viewer_program = "";
            
            //getLogTextArea().logOnConsole(properties.get(OUTPUT_FORMAT) + "Exporting\n");
            getLogTextArea().logOnConsole(outputBuffer);
            outputBuffer ="";
            
            String exportingMessage = "";
            
            try
            {
               
               if (format.equalsIgnoreCase("pdf"))
               {
                  exporter = new  net.sf.jasperreports.engine.export.JRPdfExporter();
                  
                  if (this.getMainFrame().getProperties().getProperty("PDF_IS_ENCRYPTED") != null)
                  {
                      exporter.setParameter( JRPdfExporterParameter.IS_ENCRYPTED, new Boolean( this.getMainFrame().getProperties().getProperty("PDF_IS_ENCRYPTED") ) );
                  }
                  if (this.getMainFrame().getProperties().getProperty("PDF_IS_128_BIT_KEY") != null)
                  {
                      exporter.setParameter( JRPdfExporterParameter.IS_128_BIT_KEY, new Boolean( this.getMainFrame().getProperties().getProperty("PDF_IS_128_BIT_KEY") ) );
                  }
                  if (this.getMainFrame().getProperties().getProperty("PDF_USER_PASSWORD") != null)
                  {
                      exporter.setParameter( JRPdfExporterParameter.USER_PASSWORD, this.getMainFrame().getProperties().getProperty("PDF_USER_PASSWORD"));
                  }
                  if (this.getMainFrame().getProperties().getProperty("PDF_OWNER_PASSWORD") != null)
                  {
                      exporter.setParameter( JRPdfExporterParameter.OWNER_PASSWORD, this.getMainFrame().getProperties().getProperty("PDF_OWNER_PASSWORD"));
                  }
                  if (this.getMainFrame().getProperties().getProperty("PDF_PERMISSIONS") != null)
                  {
                      exporter.setParameter( JRPdfExporterParameter.PERMISSIONS, new Integer( this.getMainFrame().getProperties().getProperty("PDF_PERMISSIONS")));
                  }
                  
                  fileName = Misc.changeFileExtension(fileName,"pdf");
                  exportingMessage = "Exporting pdf to file (using iText)... "+fileName+"";
                  viewer_program = mainFrame.getProperties().getProperty("ExternalPDFViewer");
               }
               else if (format.equalsIgnoreCase("csv"))
               {
                  exporter = new  net.sf.jasperreports.engine.export.JRCsvExporter();
                  
                  if (this.getMainFrame().getProperties().getProperty("CSV_FIELD_DELIMITER") != null)
                  {
                      exporter.setParameter( JRCsvExporterParameter.FIELD_DELIMITER, this.getMainFrame().getProperties().getProperty("CSV_FIELD_DELIMITER") );
                  }
                  
                  fileName = Misc.changeFileExtension(fileName,"csv");
                  exportingMessage = "Exporting CSV to file... "+fileName+"";
                  viewer_program = Misc.nvl( mainFrame.getProperties().getProperty("ExternalCSVViewer"), "");
               }
               else if (format.equalsIgnoreCase("html"))
               {
                  exporter = new  net.sf.jasperreports.engine.export.JRHtmlExporter();
                  
                  if (this.getMainFrame().getProperties().getProperty("HTML_IMAGES_DIR_NAME") != null)
                  { exporter.setParameter( JRHtmlExporterParameter.IMAGES_DIR_NAME, this.getMainFrame().getProperties().getProperty("HTML_IMAGES_DIR_NAME") ); }
                  if (this.getMainFrame().getProperties().getProperty("HTML_IS_OUTPUT_IMAGES_TO_DIR") != null)
                  { exporter.setParameter( JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, new Boolean( this.getMainFrame().getProperties().getProperty("HTML_IS_OUTPUT_IMAGES_TO_DIR")) ); }
                  if (this.getMainFrame().getProperties().getProperty("HTML_IMAGES_URI") != null)
                  { exporter.setParameter( JRHtmlExporterParameter.IMAGES_URI, this.getMainFrame().getProperties().getProperty("HTML_IMAGES_URI") ); }
                  if (this.getMainFrame().getProperties().getProperty("HTML_HTML_HEADER") != null)
                  { exporter.setParameter( JRHtmlExporterParameter.HTML_HEADER, this.getMainFrame().getProperties().getProperty("HTML_HTML_HEADER") ); }
                  if (this.getMainFrame().getProperties().getProperty("HTML_BETWEEN_PAGES_HTML") != null)
                  { exporter.setParameter( JRHtmlExporterParameter.BETWEEN_PAGES_HTML, this.getMainFrame().getProperties().getProperty("HTML_BETWEEN_PAGES_HTML") ); }
                  if (this.getMainFrame().getProperties().getProperty("HTML_HTML_FOOTER") != null)
                  { exporter.setParameter( JRHtmlExporterParameter.HTML_FOOTER, this.getMainFrame().getProperties().getProperty("HTML_HTML_FOOTER") ); }
                  if (this.getMainFrame().getProperties().getProperty("HTML_IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS") != null)
                  { exporter.setParameter( JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, new Boolean(this.getMainFrame().getProperties().getProperty("HTML_IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS"))); }
                  if (this.getMainFrame().getProperties().getProperty("HTML_IS_WHITE_PAGE_BACKGROUND") != null)
                  { exporter.setParameter( JRHtmlExporterParameter.IS_WHITE_PAGE_BACKGROUND, new Boolean(this.getMainFrame().getProperties().getProperty("HTML_IS_WHITE_PAGE_BACKGROUND")) ); }
                  if (this.getMainFrame().getProperties().getProperty("HTML_IS_USING_IMAGES_TO_ALIGN") != null)
                  { exporter.setParameter( JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, new Boolean(this.getMainFrame().getProperties().getProperty("HTML_IS_USING_IMAGES_TO_ALIGN")) ); }
                  
                  fileName = Misc.changeFileExtension(fileName,"html");
                  exportingMessage="Exporting HTML to file... "+fileName+"";
                  viewer_program = Misc.nvl( mainFrame.getProperties().getProperty("ExternalHTMLViewer"), "");
               }
               else if (format.equalsIgnoreCase("xls"))
               {
                   
                  exporter = new  net.sf.jasperreports.engine.export.JRXlsExporter();
                          
                  if (this.getMainFrame().getProperties().getProperty("XLS_IS_ONE_PAGE_PER_SHEET") != null)
                  { exporter.setParameter( JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, new Boolean( this.getMainFrame().getProperties().getProperty("XLS_IS_ONE_PAGE_PER_SHEET")) ); }
                  if (this.getMainFrame().getProperties().getProperty("XLS_IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS") != null)
                  { exporter.setParameter( JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, new Boolean(this.getMainFrame().getProperties().getProperty("XLS_IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS"))); }
                  if (this.getMainFrame().getProperties().getProperty("XLS_IS_WHITE_PAGE_BACKGROUND") != null)
                  { exporter.setParameter( JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, new Boolean(this.getMainFrame().getProperties().getProperty("XLS_IS_WHITE_PAGE_BACKGROUND")) ); }
                  if (this.getMainFrame().getProperties().getProperty("XLS_IS_AUTO_DETECT_CELL_TYPE") != null)
                  { exporter.setParameter( JRXlsExporterParameter.IS_AUTO_DETECT_CELL_TYPE, new Boolean(this.getMainFrame().getProperties().getProperty("XLS_IS_AUTO_DETECT_CELL_TYPE")) ); }
                 
                  
                  fileName = Misc.changeFileExtension(fileName,"xls");
                  exportingMessage = "Exporting xls to file (using POI)... "+fileName+"";
                  viewer_program = Misc.nvl( mainFrame.getProperties().getProperty("ExternalXLSViewer"), "");
                  
               }
               else if (format.equalsIgnoreCase("xls2"))
               {
                   
                  exporter = new  net.sf.jasperreports.engine.export.JExcelApiExporter();
                          
                  if (this.getMainFrame().getProperties().getProperty("XLS2_IS_FONT_SIZE_FIX_ENABLED") != null)
                  { exporter.setParameter( JExcelApiExporterParameter.IS_FONT_SIZE_FIX_ENABLED, new Boolean( this.getMainFrame().getProperties().getProperty("XLS2_IS_FONT_SIZE_FIX_ENABLED")) ); }
                  
                  fileName = Misc.changeFileExtension(fileName,"xls");
                  exportingMessage = "Exporting xls to file (using JExcelApi)... "+fileName+"";
                  viewer_program = Misc.nvl( mainFrame.getProperties().getProperty("ExternalXLSViewer"), "");
                  
               }
               else if (format.equalsIgnoreCase("java2D"))
               {
                  
                  exporter = new  net.sf.jasperreports.engine.export.JRGraphics2DExporter();
                  exportingMessage = "Exporting to Java2D ";
                  viewer_program = null;
               }
               else if (format.equalsIgnoreCase("jrviewer"))
               {
                  exportingMessage = "Viewing with JasperReports Viewer";
                  exporter = null;
                  viewer_program = null;
               }
               else if (format.equalsIgnoreCase("txt"))
               {
                  exporter = new  it.businesslogic.ireport.export.JRTxtExporter();
                  
                  if (this.getMainFrame().getProperties().getProperty("TXT_PAGE_ROWS") != null)
                  { exporter.setParameter( it.businesslogic.ireport.export.JRTxtExporterParameter.PAGE_ROWS, this.getMainFrame().getProperties().getProperty("TXT_PAGE_ROWS") ); }
                  if (this.getMainFrame().getProperties().getProperty("TXT_PAGE_COLUMNS") != null)
                  { exporter.setParameter( it.businesslogic.ireport.export.JRTxtExporterParameter.PAGE_COLUMNS, this.getMainFrame().getProperties().getProperty("TXT_PAGE_COLUMNS") ); }
                  if (this.getMainFrame().getProperties().getProperty("TXT_ADD_FORM_FEED") != null)
                  { exporter.setParameter( it.businesslogic.ireport.export.JRTxtExporterParameter.ADD_FORM_FEED, new Boolean(this.getMainFrame().getProperties().getProperty("TXT_ADD_FORM_FEED"))); }
                  
                  fileName = Misc.changeFileExtension(fileName,"txt");
                  exportingMessage = "Exporting txt (iReport) to file... "+fileName+"\n";
                  viewer_program = Misc.nvl( mainFrame.getProperties().getProperty("ExternalTXTViewer"), "");
               }
               else if (format.equalsIgnoreCase("txtjr"))
               {
                  exporter = new  net.sf.jasperreports.engine.export.JRTextExporter();
                  
                  if (this.getMainFrame().getProperties().getProperty("JRTXT_PAGE_WIDTH") != null)
                  { exporter.setParameter( net.sf.jasperreports.engine.export.JRTextExporterParameter.PAGE_WIDTH, new Integer( this.getMainFrame().getProperties().getProperty("JRTXT_PAGE_WIDTH")) ); }
                  if (this.getMainFrame().getProperties().getProperty("JRTXT_PAGE_HEIGHT") != null)
                  { exporter.setParameter( net.sf.jasperreports.engine.export.JRTextExporterParameter.PAGE_HEIGHT, new Integer( this.getMainFrame().getProperties().getProperty("JRTXT_PAGE_HEIGHT")) ); }
                  if (this.getMainFrame().getProperties().getProperty("JRTXT_CHARACTER_WIDTH") != null)
                  { exporter.setParameter( net.sf.jasperreports.engine.export.JRTextExporterParameter.CHARACTER_WIDTH, new Integer( this.getMainFrame().getProperties().getProperty("JRTXT_CHARACTER_WIDTH")) ); }
                  if (this.getMainFrame().getProperties().getProperty("JRTXT_CHARACTER_HEIGHT") != null)
                  { exporter.setParameter( net.sf.jasperreports.engine.export.JRTextExporterParameter.CHARACTER_HEIGHT, new Integer( this.getMainFrame().getProperties().getProperty("JRTXT_CHARACTER_HEIGHT")) ); }
                  if (this.getMainFrame().getProperties().getProperty("JRTXT_BETWEEN_PAGES_TEXT") != null)
                  { exporter.setParameter( net.sf.jasperreports.engine.export.JRTextExporterParameter.BETWEEN_PAGES_TEXT, this.getMainFrame().getProperties().getProperty("JRTXT_BETWEEN_PAGES_TEXT") ); }
                  
                  fileName = Misc.changeFileExtension(fileName,"txt");
                  exportingMessage = "Exporting txt (jasperReports) to file... "+fileName+"";
                  viewer_program = Misc.nvl( mainFrame.getProperties().getProperty("ExternalTXTViewer"), "");
               }
               else if (format.equalsIgnoreCase("rtf"))
               {
                  exporter = new  net.sf.jasperreports.engine.export.JRRtfExporter();
                  
                  fileName = Misc.changeFileExtension(fileName,"rtf");
                  exportingMessage = "Exporting RTF to file... "+fileName+"";
                  viewer_program = Misc.nvl( mainFrame.getProperties().getProperty("ExternalRTFViewer"), "");
               }
               
               img_url = this.getClass().getResource("/it/businesslogic/ireport/icons/printer_mini.png");
         
               getLogTextArea().logOnConsole("<font face=\"SansSerif\"  size=\"3\"><img align=\"right\" src=\""+  img_url  +"\"> &nbsp;" + exportingMessage + "</font>",true);
         
               
               if (exporter != null)
               {
                  exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,fileName);
                  exporter.setParameter(JRExporterParameter.JASPER_PRINT,print);
                  exporter.setParameter(JRExporterParameter.PROGRESS_MONITOR, this);
                  exporter.exportReport();
                  getLogTextArea().logOnConsole(outputBuffer);
            	  outputBuffer ="";
               }
               else if (format.equalsIgnoreCase("jrviewer"))
               {
                  //jrv = new net.sf.jasperreports.view.JRViewer(print);
                  JasperViewer jasperViewer =
                  new JasperViewer(print,false);
                  jasperViewer.setTitle("iReport JasperViewer");
                  // Find JRViewer...
                    /*
                    javax.swing.JComponent button = searchButton( (javax.swing.JComponent)jasperViewer.getRootPane() , "Print");
                    if (button != null) ((javax.swing.JButton)button).setText("Ciccio");
                    button = searchButton( (javax.swing.JComponent)jasperViewer.getRootPane() , "Reload");
                    if (button != null) ((javax.swing.JButton)button).setText("Ricarica");
                     */
                  jasperViewer.setVisible(true);
                  
                  //net.sf.jasperreports.view.JasperViewer.viewReport( print, false);
               }
            } catch (Throwable ex2)
            {
               
               
               getLogTextArea().logOnConsole("Error exporting print...\n");
               ex2.printStackTrace();
               getLogTextArea().logOnConsole(outputBuffer);
               outputBuffer ="";
               
            }
            
            getLogTextArea().logOnConsole("<font face=\"SansSerif\"  size=\"3\" color=\"#0000CC\"><b>Export running time : " + (System.currentTimeMillis() - start) + "</b></font><hr>",true);
           
            // Export using the rigth program....
            
            Runtime rt = Runtime.getRuntime();
            if (viewer_program == null || viewer_program.equals(""))
            {
               
               if (format.equalsIgnoreCase("jrviewer"))
               {
                  
               }
               else
                  getLogTextArea().logOnConsole("<font face=\"SansSerif\"  size=\"3\">No external viewer specified for this type of print. Set it in the options frame!</font>",true);
               
            }
            else
            {
               try
               {
                  String execute_string = viewer_program + " "+fileName+"";
                  getLogTextArea().logOnConsole("<font face=\"SansSerif\"  size=\"3\">Executing: "+ execute_string + "</font>",true);
                  rt.exec( execute_string );
               } catch (Exception ex)
               {
                  
                  getLogTextArea().logOnConsole("Error viewing report...\n");
                  ex.printStackTrace();
                  getLogTextArea().logOnConsole(outputBuffer+"\n");
                  outputBuffer ="";
               }
               //getLogTextArea().logOnConsole("Finished...\n");
            }
         }
         else
         {
            getLogTextArea().logOnConsole("Print not filled. Try to use an EmptyDataSource...!\n");
         }
      }
      
      removeThread();
      
      if (backupJRClasspath != null) {
          //System.setProperty("jasper.reports.compile.class.path",backupJRClasspath);
          net.sf.jasperreports.engine.util.JRProperties.setProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_CLASSPATH, backupJRClasspath );
      }
      else 
      {
          //System.getProperties().remove("jasper.reports.compile.class.path");
          net.sf.jasperreports.engine.util.JRProperties.restoreProperties(); 
      }
      
      if (backupSystemClasspath != null) System.setProperty("java.class.path",backupSystemClasspath);
      else System.getProperties().remove("java.class.path");
      
      System.gc();
      //System.setOut(out);
      //System.setErr(err);
   }
   
   
   public void removeThread()
   {
       if (threadList != null)
      {
         javax.swing.DefaultListModel dlm = (javax.swing.DefaultListModel)threadList.getModel();
         dlm.removeElement(this);
         threadList.updateUI();
         getLogTextArea().setTitle("Finished"+constTabTitle);
         getLogTextArea().setRemovable(true);
      }
       
   }
   /** Getter for property command.
    * @return Value of property command.
    *
    */
   public int getCommand()
   {
      return command;
   }
   
   /** Setter for property command.
    * @param command New value of property command.
    *
    */
   public void setCommand(int command)
   {
      this.command = command;
   }
   
   /** Getter for property iReportConnection.
    * @return Value of property iReportConnection.
    *
    */
   public it.businesslogic.ireport.IReportConnection getIReportConnection()
   {
      return iReportConnection;
   }
   
   /** Setter for property iReportConnection.
    * @param iReportConnection New value of property iReportConnection.
    *
    */
   public void setIReportConnection(it.businesslogic.ireport.IReportConnection iReportConnection)
   {
      this.iReportConnection = iReportConnection;
   }
   
   /** Getter for property jrf.
    * @return Value of property jrf.
    *
    */
   public JReportFrame getJrf()
   {
      return jrf;
   }
   
   /** Setter for property jrf.
    * @param jrf New value of property jrf.
    *
    */
   public void setJrf(JReportFrame jrf)
   {
      this.jrf = jrf;
   }
   
   /** Getter for property mainFrame.
    * @return Value of property mainFrame.
    *
    */
   public MainFrame getMainFrame()
   {
      return mainFrame;
   }
   
   /** Setter for property mainFrame.
    * @param mainFrame New value of property mainFrame.
    *
    */
   public void setMainFrame(MainFrame mainFrame)
   {
      this.mainFrame = mainFrame;
   }
   
   /** Getter for property properties.
    * @return Value of property properties.
    *
    */
   public HashMap getProperties()
   {
      return properties;
   }
   
   /** Setter for property properties.
    * @param properties New value of property properties.
    *
    */
   public void setProperties(HashMap properties)
   {
      this.properties = properties;
   }
   
   public String toString()
   {
      return status;
   }
   
   class FilteredStream extends FilterOutputStream
   {
      public FilteredStream(OutputStream aStream)
      {
         super(aStream);
      }
      
      public void write(byte b[]) throws IOException
      {
         String aString = new String(b);
         outputBuffer += aString;
      }
      
      public void write(byte b[], int off, int len) throws IOException
      {
         String aString = new String(b , off , len);
         outputBuffer += aString;
         
         //getLogTextArea().logOnConsole(aString);
      }
   }
   
   public void start()
   {
      this.thread = new Thread(this);
      
	//using the report directory to load classes and resources
	try{
		  String reportDirectory = new File(jrf.getReport().getFilename()).getParent();
      
		  //set classpath
		  //String classpath = System.getProperty("jasper.reports.compile.class.path");
                  String classpath = net.sf.jasperreports.engine.util.JRProperties.getProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_CLASSPATH );
		  if(classpath != null){
			
			  classpath += File.pathSeparator + reportDirectory; 
			  //System.setProperty("jasper.reports.compile.class.path", classpath);
                          net.sf.jasperreports.engine.util.JRProperties.setProperty(net.sf.jasperreports.engine.util.JRProperties.COMPILER_CLASSPATH, classpath);
			
		  }else if(System.getProperty("java.class.path") != null){
			
			  classpath = System.getProperty("java.class.path");
			  classpath += File.pathSeparator + reportDirectory; 
			  System.setProperty("java.class.path", classpath);
		  }

		  //include report directory for resource search path
		  reportDirectory = reportDirectory.replace('\\', '/');
		  if(!reportDirectory.endsWith("/")){
			  reportDirectory += "/";//the file path separator must be present
		  }
		  if(!reportDirectory.startsWith("/")){
			  reportDirectory = "/" + reportDirectory;//it's important to JVM 1.4.2 especially if contains windows drive letter
		  }
		  
		  thread.setContextClassLoader(new URLClassLoader(new URL[]{
		  	  new URL("file://"+reportDirectory)
		  }));
  
	 } catch (MalformedURLException mue){
	  mue.printStackTrace();
	}
      
      this.thread.start();
   }
   
   public void parseException(String exception, Vector sourceLines)
   {
      
      // Create a single outString...
      String outString = "";
      
      // For each row, looking for a file name followed by a row number...
      //javax.swing.JOptionPane.showMessageDialog(null,exception);
      StringTokenizer st = new StringTokenizer(exception, "\n");
      while (st.hasMoreElements())
      {
         
         String line = st.nextToken();
         if (line.startsWith(this.javaFile))
         {
            // The next line is an expression error....
            //getLogTextArea().logOnConsole(line+"\n");
            outString += Misc.toHTML(line+"\n");
            String lineNumber = line.substring( this.javaFile.length()+1);
            lineNumber = lineNumber.substring(0, lineNumber.indexOf(':'));
            int ln = Integer.parseInt(lineNumber);
            if (ln >= 3) ln -=3;
            
            // Take the element name....
            
            String reference = "";
            if (sourceLines.size() >= ln)
            {
               
               String lineCode = (String)sourceLines.elementAt(ln);
               //getLogTextArea().logOnConsole( "Line: " + ln + "> " + lineCode+"\n");
               if (lineCode.indexOf("            case") == 0 &&
               lineCode.indexOf(" : // ") >0)
               {
                  // We have found the comment where jasperReport puts the expression ref.
                  reference = lineCode.substring(lineCode.indexOf(" : // ")+6).trim();
               }
            }
            
            if (st.hasMoreElements())
            {
               try
               {
                  String error_line = st.nextToken();
                  if (error_line.startsWith("found"))
                  {
                     //getLogTextArea().logOnConsole( error_line+"\n");
                     outString += Misc.toHTML(error_line+"\n");
                     error_line = st.nextToken();
                  }
                  if (error_line.startsWith("required"))
                  {
                     //getLogTextArea().logOnConsole( error_line+"\n");
                     outString += Misc.toHTML(error_line+"\n");
                     error_line = st.nextToken();
                  }
                  if (error_line.startsWith("symbol"))
                  {
                     //getLogTextArea().logOnConsole( error_line+"\n");
                     outString += Misc.toHTML(error_line+"\n");
                     error_line = st.nextToken();
                  }
                  if (error_line.startsWith("location"))
                  {
                     //getLogTextArea().logOnConsole( error_line+"\n");
                     outString += Misc.toHTML(error_line+"\n");
                     error_line = st.nextToken();
                  }
                  
                  // Find the link....
                  // Count space at begin of line...
                  String html = "";
                  for (int i=0; i<error_line.length(); ++i)
                  {
                     if (error_line.charAt(i) == ' ')
                     {
                        html += "&nbsp;";
                     }
                     else break;
                  }
                  error_line = error_line.trim();
                  html += "<a href=\"http://error:"+ jrf.getWindowID()+ "/"+reference+"\">"+Misc.toHTML(error_line)+"</a>";
                  //getLogTextArea().logOnConsole( html,true);
                  outString += html;
               } catch (Exception ex)
               {
                  //getLogTextArea().logOnConsole( "Error parsing\n!");
                  outString += Misc.toHTML("Error parsing\n!");
               }
            }
         }
         else if (line.startsWith("Warning :") && line.indexOf("y=")>0 && line.indexOf("height=")>0 && line.indexOf("band-height=")>0)
         {
            //getLogTextArea().logOnConsole("<a href=\"http://warning\">"+Misc.toHTML(line)+"</a>",true);
            outString += "<a href=\"http://warning:"+ jrf.getWindowID() +"\">"+Misc.toHTML(line)+"</a>";
         }
         else
         {
            //getLogTextArea().logOnConsole(line+"\n");
            outString += Misc.toHTML(line+"\n");
         }
      }
      getLogTextArea().logOnConsole(outString,true);
      //getLogTextArea().logOnConsole( "<a href=\"http://problem\">*****<hr><font face=\"Courier New\" size=\"3\">"+ exception +"</a>", true);
      outputBuffer = "";
   }
   
   public javax.swing.JComponent searchButton(javax.swing.JComponent root, String text)
   {
      if (root instanceof javax.swing.JButton && ((javax.swing.JButton)root).getText()!=null && ((javax.swing.JButton)root).getText().equals(text) ) return root;
      for (int i=0; i<root.getComponentCount(); ++i)
      {
         
         if (root.getComponent(i) instanceof javax.swing.JComponent)
         {
            getLogTextArea().logOnConsole(""+ ((javax.swing.JComponent)root.getComponent(i)) +"\n");
            javax.swing.JComponent res = searchButton((javax.swing.JComponent)root.getComponent(i),  text);
            if (res != null) return res;
         }
      }
      return null;
   }
   
   public void afterPageExport() {
       
       filledpage++;
       if (command == 0)
       {
            
       }
       

   }

    public javax.swing.JList getThreadList() {
        return threadList;
    }

    public void setThreadList(javax.swing.JList threadList) {
        this.threadList = threadList;
    }
    
    public void updateThreadList()
    {
        getLogTextArea().setTitle(status + constTabTitle);
        try {
            
         if (threadList != null) javax.swing.SwingUtilities.invokeAndWait( 
            new java.lang.Runnable() { 
                    public void run() { 
                            threadList.updateUI(); 
                    }
            } );
         } catch (Exception ex) {}
    }
     
    private ClassLoader getClassLoader()
	{
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

		if (classLoader != null)
		{
			//try
			//{
			//	Class.forName(net.sf.jasperreports.engine.design.JRJdtCompiler.class.getName(), true, Thread.currentThread().getContextClassLoader());
			//}
			//catch (ClassNotFoundException e)
			//{
			//	classLoader = null;
			//	//if (log.isWarnEnabled())
			//	//	log.warn("Failure using Thread.currentThread().getContextClassLoader() in JRJdtCompiler class. Using JRJdtCompiler.class.getClassLoader() instead.");
			//}
		}
	
		if (classLoader == null)
		{
			//classLoader = JRClassLoader.class.getClassLoader();
		}

		return classLoader;
	}

    public LogTextArea getLogTextArea() {
        return logTextArea;
    }

    public void setLogTextArea(LogTextArea logTextArea) {
        this.logTextArea = logTextArea;
    }
}

