Example Resource Closer

// One use of the events is to setup closing resources from the same script
// in which they were initialized

import com.screenscraper.events.*;
import com.screenscraper.events.session.*;

CsvWriter writer = new CsvWriter("output/my_csv_file.csv");
writer.setHeader(new String[]{"NAME", "ADDRESS"});

session.setVariable("_WRITER", writer);

// Setup a call to close the writer when the scrape ends (called regardless
// of whether the scrape was stopped mid run or completed normally)
EventHandler handler = new EventHandler()
{
    public String getHandlerName()
    {
        return "Close resources";
    }

    public Object handleEvent(EventFireTime fireTime, SessionEventData data)
    {
        // Note that in the interpreter, directly referencing variables that
        // were set external to the script (ie session, scrapeableFile, etc...)
        // will cause an error.  If they are needed, get them from the data object
        data.getSession().logInfo("Closing resources...");
        try
        {
            writer.close();
        }
        catch(Exception e)
        {
            // Do nothing
        }
        return data.getLastReturnValue();
    }
};

// Set the event to be fired at a specific time
session.addEventCallback(SessionEventFireTime.AfterEndScripts, handler);