import java.util.logging.Level;

import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.core.exception.BirtException;

public class BirtRunner {
    static String engineHome = "/usr/lib/birt-runtime/ReportEngine";
	public static void main(String[] args) throws BirtException {

        String inputPath = "test1.rptdesign";
        String outputPath = "/tmp/test1.html";

        EngineConfig config = new EngineConfig();
        config.setEngineHome(engineHome);
        //config.setLogConfig("/tmp", Level.FINE)
        config.setLogConfig("/tmp", Level.ALL);
        Platform.startup(config);
        IReportEngineFactory factory = (IReportEngineFactory)Platform.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
        IReportEngine engine = factory.createReportEngine(config);
        //engine.changeLogLevel(Level.FINE)
        engine.changeLogLevel(Level.ALL);

        IReportRunnable design = engine.openReportDesign(inputPath);
                
        IRunAndRenderTask task = engine.createRunAndRenderTask(design);
        
        // this line is taken from the BIRT online examples, but what the heck does it actually do?
        //task.getAppContext().put(EngineConstants.APPCONTEXT_CLASSLOADER_KEY, BirtRunner.class.getClassLoader());

        HTMLRenderOption options = new HTMLRenderOption();
        options.setOutputFileName(outputPath);
        options.setOutputFormat("html");
        task.setRenderOption(options);
        System.out.println("here");
        
        // This call will result in the program terminating with exit code 1.
        // When run on the command-line with 'java BirtRunner' it just quits with no
        // error output...(?)
        
        // However, when run from Eclipse debugger, I can actually see that a BirtException
        // is being raised...
        task.run();
        
        // If I wrap the call to run() in a try/except I *can* successfully
        // catch the error... but printStackTrace() does not print anything...(?)
        //try {
        //	task.run();
        //} catch (Exception e) {
        //	e.printStackTrace(); // 
        //}
        
        // never gets here
        System.out.println("here2");
        task.close();
	}

}

