import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Properties;
import java.util.Vector;

import jet.cs.util.APIConst;
import jet.server.api.CompletedTaskRecord;
import jet.server.api.RemoteFileService;
import jet.server.api.ResultVersionRecord;
import jet.server.api.rmi.RemoteCompletedTaskTable;
import jet.server.api.rmi.RemoteReportServerToolkit;
import jet.server.api.rmi.RemoteResourceManager;
import jet.server.api.rmi.RemoteRptServer;
/**
 * This demo is created to demonstrate the usage of the JReport Server API methods to schedule and publish results
 * using a remote interface to JReport Server.  It may be on the same computer but running in a different JVM.
 *
 * It runs the report in every format and places the results in the JReport Server resource folder
 * It also can email the results if email smtp is set up on the server and you provide a valid email address.
 * This is the normal way to make requests to a standalone JReport Server.
 *
 * Assume that there is a catalog SampleReports.cat, a report CustomerAnalysis.cls 
 * already deployed to /SampleReports in Public Reports.
 */
public class RemoteAPIDemoPublishRpt {

	public static void main(String[] args) {
		try {
			//set report home for logging and location of rmi.auth file for security
			System.getProperties().put("reporthome", "C:\\JReport\\Server");
			System.getProperties().put("jrs.rmi.auth_file", "C:\\JReport\\Server\\bin\\rmi.auth");
			String host = "localhost";	// sample default value
			String port = "1129";		// sample default value
			System.out.println("*******************************************************************************");									
			System.out.println("You must input your server's IP before running the APIDemo!");
			System.out.println("Please input your server's IP, and make sure it is correct! For example '111.111.111.111' or 'localhost'");
			System.out.println("*******************************************************************************");
			// get Server's IP input by user
			BufferedReader inputIP = new BufferedReader(new InputStreamReader(System.in));	    
			host = inputIP.readLine();
			System.out.println();
		    
			// print the note and description
			System.out.println("******************************************************************************");									
			System.out.println("You must input the port to connect server before running the APIDemo!");
			System.out.println("Please input the port, and make sure it is correct! For example '1129'");
			System.out.println("******************************************************************************");
			// get port input by user
			BufferedReader inputPort = new BufferedReader(new InputStreamReader(System.in));	    
			port = inputPort.readLine();
			System.out.println();

			// get a RemoteRptServer instance
			RemoteRptServer server = RemoteReportServerToolkit.getRemoteRptServer(host, port);
			System.out.println("========server="+server);

			// set task properties
			Properties props = new Properties();
			props.put(APIConst.TAG_TASK_CLASS, APIConst.TASK_TO_RPT);
			props.put(APIConst.TAG_LAUNCH_TYPE, String.valueOf(APIConst.IMMEDIATELY));
			props.put(APIConst.TAG_CATALOG, "/SampleReports/SampleReports.cat");
			props.put(APIConst.TAG_REPORT, "/SampleReports/CustomerAnalysis.cls");
			props.put(APIConst.TAG_TO_DISK, "true");
			props.put(APIConst.TAG_TO_VERSION, "true");
			props.put(APIConst.TAG_TO_MAIL, "true");

			// TO DISK
			// set the value of PDF for TO_DISK
			props.put(APIConst.TAG_TO_PDF, "true");

			// set the value of HTML for TO_DISK
			props.put(APIConst.TAG_TO_HTML, "true");

			// set the value of XML for TO_DISK
			props.put(APIConst.TAG_TO_XML, "true");

			// specify the pdf result filename.
			props.put(APIConst.TAG_PDF, "CustomerAnalysis.pdf");

			// specify the html result filename.
			props.put(APIConst.TAG_HTML, "html_CustomerAnalysis");

			// specify the xml result filename.
			props.put(APIConst.TAG_XML, "CustomerAnalysis.xml");

			props.put(APIConst.TAG_REPORT_LANGUAGE, "en_US");
			String today = DateFormat.getDateInstance(DateFormat.LONG, new Locale("en", "US")).format(new Date());
			//set value of parameter "p_StartDate" & "p_EndDate".
			props.put(APIConst.TAG_PARAM_PREFIX + "p_StartDate", "January 1, 2006");
			props.put(APIConst.TAG_PARAM_PREFIX + "p_EndDate", today);


			// Specify the resource directory "/SampleReports" that the result is generated into.
			// The real path of pdf result file is
			// "server_install_root/jreports/SampleReports/CustomerAnalysis.pdf".
			// The pdf result can be accessed by the url
			// "http://host:port/jrservlet_path/SampleReports/CustomerAnalysis.pdf".
			props.put(APIConst.TAG_PDF_DIR, "/SampleReports");

			// Specify the resource directory "/SampleReports" that the result is generated into.
			// The real path of html result files is
			// "server_install_root/jreports/SampleReports/html_CustomerAnalysis*.*".
			// html result files include html_CustomerAnalysis.css, html_CustomerAnalysis_*.html etc.
			// The first html result page can be accessed by the url
			// "http://host:port/jrservlet_path/SampleReports/html_CustomerAnalysis_1.html".
			props.put(APIConst.TAG_HTML_DIR, "/SampleReports");

			// Specify the resource directory "/SampleReports" that the result is generated into.
			// The real path of xml result file is
			// "server_install_root/jreports/SampleReports/CustomerAnalysis.xml".
			// The xml result can be accessed by the url
			// "http://host:port/jrservlet_path/SampleReports/CustomerAnalysis.xml".
			props.put(APIConst.TAG_XML_DIR, "/SampleReports");

			// TO VERSION
			props.put(APIConst.TAG_EXPIRE_DAYS, "1");

			// Set the value of rst for TO_VERSION, and the rst file is named
			// by system, for example "admin1070244954140.rst"(username+currenttime+".rst")
			// The real path of rst file similar to the following
			// "server_install_root/history/1/admin1070244954140/admin1070244954140.rst"
			// The rst result can be accessed by a url similar to
			// "http://host:port/history_path/1/admin1070244954140/admin1070244954140.rst".
			props.put(APIConst.TAG_TO_VERSION_RST, "true");

			// Set the value of pdf for TO_VERSION, and the pdf file is named
			// by system, for example "admin1070244954140.pdf"(username+currenttime+".pdf")
			// The real path of pdf file is something like
			// "server_install_root/history/1/admin1070244954140/admin1070244954140.pdf"
			// The pdf result can be accessed by a url similar to
			// "http://host:port/history_path/1/admin1070244954140/admin1070244954140.pdf".
			props.put(APIConst.TAG_TO_VERSION_PDF, "true");

			// Set the value of xls for TO_VERSION, and the xls file is named
			// by system, for example "admin1070244954140.xls"(username+currenttime+".xls")
			// The real path of xls file is something like
			// "server_install_root/history/1/admin1070244954140/admin1070244954140.xls"
			// The xls result can be accessed by a url similar to
			// "http://host:port/history_path/1/admin1070244954140/admin1070244954140.xls".
			props.put(APIConst.TAG_TO_VERSION_EXCEL, "true");

			// Set the value of txt for TO_VERSION, and the txt file is named
			// by system, for example "admin1070244954140.txt"(username+currenttime+".txt")
			// The real path of txt file is something like
			// "server_install_root/history/1/admin1070244954140/admin1070244954140.txt"
			// The txt result can be accessed by a url similar to
			// "http://host:port/history_path/1/admin1070244954140/admin1070244954140.txt".
			props.put(APIConst.TAG_TO_VERSION_TXT, "true");

			// TO EMAIL
			Properties mail = new Properties();

			// set the first mail properties
			mail.put(APIConst.TAG_MAIL_TO, "user1@mailServer");
			mail.put(APIConst.TAG_MAIL_SUBJECT, "CustomerAnalysis");
			mail.put(APIConst.TAG_MAIL_COMMENT, "to user1.");

			// set APIConst.TAG_JRMAIL property field by using properties of an E-Mail.
			props.put(APIConst.TAG_JRMAIL + "0", jet.server.api.http.HttpUtil.makeQuery(mail));

			mail.clear();
			// set the second mail properties
			mail.put(APIConst.TAG_MAIL_TO, "user2@mailServer");
			mail.put(APIConst.TAG_MAIL_SUBJECT, "CustomerAnalysis");
			mail.put(APIConst.TAG_MAIL_COMMENT, "to user2.");

			// set APIConst.TAG_JRMAIL property field by using properties of an E-Mail.
			props.put(APIConst.TAG_JRMAIL + "1", jet.server.api.http.HttpUtil.makeQuery(mail));

			System.out.println("========submitScheduledTask=" + props);

			String taskID = server.runTask("admin", props);
			System.out.println("========taskID=" + taskID);
			
			//check result files
			RemoteFileService fileService = RemoteReportServerToolkit.getRemoteFileService(host, port);
			RemoteResourceManager resMan = server.getResourceManager();
			String resultPDFDir = resMan.getPathInfo("admin", "/SampleReports").getRealPath();
			if (resultPDFDir.length() == 0) {
				resultPDFDir = resMan.getRoot() + "SampleReports";
			}
			String resultPDF = resultPDFDir + fileService.getRemoteFileSeparator() + "CustomerAnalysis.pdf";
			System.out.println("\n========Created the PDF result file \"" + resultPDF
								+ "\"? - " + fileService.exists(resultPDF));
			String resultHTMLDir = resMan.getPathInfo("admin", "/SampleReports").getRealPath();
			if (resultHTMLDir.length() == 0) {
				resultHTMLDir = resMan.getRoot() + "SampleReports";
			}
			String resultHTML = resultHTMLDir + fileService.getRemoteFileSeparator() + "html_CustomerAnalysis_1.html";
			System.out.println("\n========Created the HTML result file \"" + resultHTML
								+ "\"? - " + fileService.exists(resultHTML));
			String resultXMLDir = resMan.getPathInfo("admin", "/SampleReports").getRealPath();
			if (resultXMLDir.length() == 0) {
				resultXMLDir = resMan.getRoot() + "SampleReports";
			}
			String resultXML = resultXMLDir + fileService.getRemoteFileSeparator() + "CustomerAnalysis.xml";
			System.out.println("\n========Created the XML result file \"" + resultXML
								+ "\"? - " + fileService.exists(resultXML));
			
			// get the completed record
			Vector completeRecords = null;
			RemoteCompletedTaskTable completeTable = server.getCompletedTaskTable();
			completeRecords = completeTable.getCompletedTaskRecordsByTaskID(taskID);

			System.out.println("\n========completeRecords=" + completeRecords);

			CompletedTaskRecord completeRecord = (CompletedTaskRecord)completeRecords.elementAt(0);
			System.out.println("========completeRecord=" + completeRecord);

			if (completeRecord.isSuccessful()) {
				System.out.println("========Result generated! \nResult files=" + completeRecord.getSuccessInfo());
			} else {
				System.out.println("========Fail! Error message: \n" + completeRecord.getErrorMessage());
			}
			
			// get the result version record
			Vector versions = null;
			ResultVersionRecord versionRecord = null;
			versions = resMan.getResultVersions("admin", "/SampleReports/CustomerAnalysis.cls");
			if (versions != null && versions.size() > 0) {
				versionRecord = (ResultVersionRecord)versions.elementAt(versions.size() - 1);
				System.out.println("========resultVersionRecord=" + versionRecord);
				System.out.println("========version number=" + versionRecord.getVersionNumber());
				Hashtable resultFiles = versionRecord.getAllReportResultFiles();
				for (Enumeration e = resultFiles.keys(); e.hasMoreElements();)
				   {
				       String str =  resultFiles.get( e.nextElement()).toString();
				       System.out.println("========version result files=" + str);				   
				   }
			}

            server = null;
			System.out.println("\n========after exit, server=" + server);
		} catch (Throwable t) {
			t.printStackTrace();
		}
		System.exit(0);
	}
}
