//This is an example to demonstrate how to implement user's own scripts 
//before and after running tasks and how to get the information about a task.

import java.util.*;
import java.text.DateFormat;

import jet.server.api.TaskListener; 
import jet.server.api.TaskListenerException;
import jet.server.api.ServerInfo;
import jet.server.api.RptServerException;
import jet.cs.util.*;
import jet.formula.ParamDesc;


//Note: First step: Compile your task listener code into a path reachable by JReport Server
//	   for example, c:\JReport\Server\tasklistener, and edit the batch file
// 	   %InstallRoot%\bin\setenv.bat or setenv.sh by adding the path of the class
//     file (c:\JReport\Server\tasklistener) to the ADDCLASSPATH.
//     Second step: start JReport Server and schedule 
//     a report. Check "Add TaskListener to be invoked", and input the class 
//     name, in this example, we input TestTaskListener, and then submit the task.
//     The result will print in the command window before and after the task
//     is run.

public class TestTaskListener implements TaskListener {
	
    private String toVersion = "jet.server.schedule.jrtasks.UpdateRptTask";
	private String toFileSystem = "jet.server.schedule.jrtasks.PublishToDiskTask";
	private String toEmail = "jet.server.schedule.jrtasks.SendJRMailTask";
	private String toPrinter = "jet.server.schedule.jrtasks.PrintRptTask";
	
	
	//This method will be called automatically BEFORE a task is run,
	//which means any scripts added into the method will automatically be executed.

	public boolean beforeRun(ServerInfo serverInfo) {
    	System.out.println("------------- Before Task Running ----------");
    	
        try {

        	//"taskType" will store the task-type info got from TaskProperties.
        	//It can be used to determine what kind of task will start to run. 

       	   	String taskType = (String)serverInfo.getTaskProperties().get(APIConst.TAG_TASK_CLASS);
       	   	
        	if (taskType.equals(toVersion)) {
        		System.out.println("Task Type is: Publish to Versioning System.");
        	} else if (taskType.equals(toFileSystem)) {		 
        	   	System.out.println("Task Type is: Publish to File System.");
			} else if (taskType.equals(toEmail)) {
				System.out.println("Task Type is: Publish to Email.");
 			} else if (taskType.equals(toPrinter)) {
 				System.out.println("Task Type is: Publish to Printer.");
       	    }
       		
       		//"lType" will store the launch-type info got from TaskProperties.
       		//It can be use to determine in which launch type the task will be running.

       		String lType = (String)serverInfo.getTaskProperties().get(APIConst.TAG_LAUNCH_TYPE);  
       		
       		if (lType == null) {
       		  	System.out.println("Launch Type is: Immediately.");
       		} else if (lType.equals(String.valueOf(APIConst.AT_TIME))) {
       		   	System.out.println("Launch Type is: At time.");
       		} else if (lType.equals(String.valueOf(APIConst.PERIODICALLY))) {
       		   	System.out.println("Launch Type is: Repeatedly.");
       		}    
			
			System.out.println("TaskID is: " + serverInfo.getTaskProperties().get(APIConst.TAG_TASK_ID));
			System.out.println("TaskSubmiter is: " + serverInfo.getTaskProperties().get(APIConst.TAG_UID));
			System.out.println("Report is: " + serverInfo.getTaskProperties().get(APIConst.TAG_REPORT));
			System.out.println("Catalog is: " + serverInfo.getTaskProperties().get(APIConst.TAG_CATALOG));
			System.out.println("Submit time is:" + serverInfo.getTaskProperties().get(APIConst.TAG_SUBMIT_TIME));
			
			//Note: Some information will be created only when the task user
			//      who owns them is running the scheduled task.  
			
			//ExeYear, ExeMonth, ExeDay, ExeHour, ExeMin, and ExeSec 
			// only exist when a periodic scheduled task is run.

			if (lType != null && lType.equals(String.valueOf(APIConst.AT_TIME))) {
			    System.out.println ("ExeYear=" + (String) serverInfo.getTaskProperties().get(APIConst.TAG_EXE_YEAR));
				System.out.println ("ExeMonth=" + (String) serverInfo.getTaskProperties().get(APIConst.TAG_EXE_MONTH));
				System.out.println ("ExeDay=" + (String) serverInfo.getTaskProperties().get(APIConst.TAG_EXE_DAY));
				System.out.println ("ExeHour=" + (String) serverInfo.getTaskProperties().get(APIConst.TAG_EXE_HOUR));
				System.out.println ("ExeMin=" + (String) serverInfo.getTaskProperties().get(APIConst.TAG_EXE_MIN));
				System.out.println ("ExeSec=" + (String) serverInfo.getTaskProperties().get(APIConst.TAG_EXE_SEC));
			}
			
			//TaskProperties can provide lots of other useful information,
			//System.out.println(serverInfo.getTaskProperties());
			//By using the script above, you can output all information stored in TaskProperties.

			System.out.println("For more information, please check <TaskProperties>!\n");;
		
		//getTaskProperties and serverInfo.getSchdproperties will throw a RptServerException,
		//which must be caught.

		} catch (RptServerException e) {
			System.out.println("RptServerException throws out!\n" 
									+ "Message in exception object:\n\t" + e.getMessage());
		}
		return true; //if the return value is true, the task will start to run.
		            //if the return value is false, the task will not run.
	}

	//This method will be called automatically AFTER a task is completed.

	public void afterRun(ServerInfo serverInfo) {
		System.out.println("------------- After Task Running ----------");
		
		try {

			//CompleteTime is not stored in TaskProperties, but it can be obtained
			//by calling this method.

			String completeTime = DateFormat.getDateTimeInstance().format(new java.util.Date (System.currentTimeMillis()));
         	System.out.println ("Completed Time=" + String.valueOf(completeTime)); 
			
			System.out.println ("Engine Message =" + (String) serverInfo.getTaskProperties().get(APIConst.TAG_ENG_MSG));
		    
		    //isSuccessful only exists after a task is accomplished or terminated with an
		    //error, so it should be obtained only in afterRun()

		    boolean isSuccessful = APIUtil.getBoolean((String)serverInfo.getScheduleProperties().get(APIConst.TAG_IS_SUCCESSFUL), true);

		    if (!isSuccessful) {

		    	//Task is terminated with errors,
		    	//System.out.println("Error Message =" +(String)serverInfo.getTaskProperties().get(APIConst.TAG_ERROR));
		    	//Another alternative is using the script above to output error details.

		    	System.out.println("Task terminated with some errors. \nFor more information, please check <TAG_ERROR of TaskProperties>!");
		  	} else {
		  		System.out.println("Task accomplished successfully!\n");
		  	}
		  	
		} catch (RptServerException e) {
				System.out.println("RptServerException throws out!\n" 
										+ "Message in exception object:\n\t" + e.getMessage());
		}
	}
	
	//This method will be called automatically before beforeRun() after the parameters are entered.
	//throw TaskListenerException, means some parameters are invalid, will cancel running the task.
	public void validateParameter(ServerInfo serverInfo)
			throws TaskListenerException {
        // for example,
        //   suppose we are running the InvoiceReport.cls page report,
        //   we want to limit the Country(p_Cascading-Country) value to Australia/Belgium/Canada
        //   other values for Country are invalid.
        System.out.println("------------- validateParameter ----------");
        try{
            // get ParamDescs via ServerInfo.getParamDescs()    
            Vector params = serverInfo.getParamDescs();//the element of Vector is jet.formula.ParamDesc
            System.out.println("params="+params);
            for(int i=0; i<params.size(); i++){
                ParamDesc desc = (ParamDesc)params.get(i);
                String value = desc.getDisplayValue(desc.getValue(), Locale.getDefault());
                if(desc.getName().equals("p_Cascading-Country")){
                    if(!"Australia".equals(value)
                        && !"Belgium".equals(value)
                        && !"Canada".equals(value)
                    ){
                        //if the parameter value is invalid,
                        //throw exception, cancel the task.
                        System.out.println("the value:"+value+", is invalid for "+desc.getName()+"("+desc.getPrompt()+")");
                        throw new TaskListenerException(desc.getName()+"("+desc.getPrompt()+"): you must input Australia, Belgium, or Canada");
                    }    
                }
            }
        } catch (RptServerException e) {        
            throw new TaskListenerException(e.getMessage());
        }    
	}
	
}


