import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;

import jet.cs.util.APIConst;
import jet.server.api.rmi.RemoteReportServerToolkit;
import jet.server.api.rmi.RemoteRptServer;
import jet.server.api.RemoteFileService;
/**
 * This demo is created to demonstrate the usage of the JReport Server API methods to run large reports remotely and not wait for them to finish.
 * The remote server may be on the same computer but running in a different JVM.
 * 
 * This creates a PDF report then copies it to the local disk on the client.
 *
 * This is the normal way to make requests to a stand-alone JReport Server.
 *
 * Assume that there is a catalog SampleReports.cat, a report CustomerAnalysis.cls 
 * already deployed to /SampleReports in Public Reports.
 */

public class RemoteAPIDemoRunReportWithTimeout {

	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";		// Default host value
			String port = "1129";			// Default port value
			String archivePath = null;
			boolean copyResult = false;
			RemoteFileService fileService = null;
			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'");
			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();
			
			System.out.println("*****************************************************************************");
			System.out.println("Please input a local path to archive the result. For example 'D:\\result'"); 
			System.out.println("if the path you input not correct, result file will not be saved to local!");
			System.out.println("*****************************************************************************");
			//get local arvhice path by user
			BufferedReader inputPath = new BufferedReader(new InputStreamReader(System.in));
			archivePath = inputPath.readLine();
			
			// get a RemoteRptServer instance
			RemoteRptServer server = RemoteReportServerToolkit.getRemoteRptServer(host, port);
			System.out.println("========server="+server);
			
			if(archivePath!=null&&archivePath.length()!=0) {
				File archiveFile = new File(archivePath);
				if(archiveFile.exists()&&archiveFile.isDirectory()){
				        copyResult = true;
				        fileService = RemoteReportServerToolkit.getRemoteFileService(host, port);
				}
			}

			String catalog = "/SampleReports/SampleReports.cat";
			String rptName = "/SampleReports/CustomerAnalysis.cls";

			//set report properties
			Properties props = new Properties();
			
			//set result type as .pdf format.
			props.put(APIConst.TAG_RESULT_TYPE, String.valueOf(APIConst.PDF));

			System.out.println("\n========to pdf="+props);

			//The pdf result can be accessed by the url 
			//"http://host:port/jrservlet_path/SampleReports/SampleReports.cat/CustomerAnalysis.cls/result/temp_result_filename".
			//For example: If tempResult is "c:\JReport\Server\temp\6323848938.pdf", 
			//then the url is:
			//"http://localhost:8888/jrserver/SampleReports/SampleReports.cat/CustomerAnalysis.cls/result/6323848938.pdf".

			//The parameter "1L" represents 1 millisecond.
			String tempResult = server.runReportWithTimeouts("admin", catalog, rptName, props, 1L);

			File rstFile = new File(tempResult);
			String rstName = rstFile.getName();
			System.out.println("========tempResult="+tempResult);

			System.out.println("========isFinished="+server.isTempResultReady(rstName));

			//If the run report task can't be done within a certain time period (1 millisecond here),
			//the report will be regarded as a large report.
			if (!server.isTempResultReady(rstName)) {
				// wait until the task is done
				System.out.print(">");
				server.waitTempResultReady(rstName);
			}
			
			//copy temp result to local 
			if(copyResult) {
			        boolean ret = copyResultFromRemote(tempResult, archivePath, fileService, APIConst.PDF);
			        if(ret) System.out.println("Temp Result copy to: "+archivePath); 
			}						
            
			//register the result owner to pass security check
			//for accessing by the url 
			//"http://localhost:8888/jrserver/SampleReports/SampleReports.cat/CustomerAnalysis.cls/result/6323848938.pdf".
			//server.getTempResultOwnerManager().registerOwner("admin", BaseHttpUtil.getTempResultKey(new File(tempResult).getName()));

			props = new Properties();

			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);

			//set result type as html format.
			//html result filenames is 
			//"temp_name*.*".
			//html result files include temp_name.css, temp_name_*.html etc.
			props.put(APIConst.TAG_RESULT_TYPE, String.valueOf(APIConst.HTML));

			System.out.println("\n========to html="+props);

			//The html result can be accessed by the url 
			//"http://host:port/jrservlet_path/SampleReports/SampleReports.cat/CustomerAnalysis.cls/result/temp_result_filename".
			//For example: If tempResult is "c:\JReport\Server\temp\6323848938_1.html", 
			//then the url is:
			//"http://localhost:8888/jrserver/SampleReports/SampleReports.cat/CustomerAnalysis.cls/result/6323848938_1.html".

			//The parameter "1L" represents 1 millisecond.
			tempResult = server.runReportWithTimeouts("admin", catalog, rptName, props, 1L);

			rstFile = new File(tempResult);
			rstName = rstFile.getName();

			//The tempResult is the first html page. If you want to get all html files, 
			//please see RemoteAPIDemoRunAndExportReport.java.
			System.out.println("========tempResult="+tempResult);

			//Here, it is easy to see the process of running the report until it is finished.
			while (!server.isTempResultReady(rstName)) {
				System.out.print(">");
				Thread.sleep(100L);
			}
			System.out.println("========isFinished="+server.isTempResultReady(rstName));			

			if(copyResult) {
			        boolean ret = copyResultFromRemote(tempResult, archivePath, fileService, APIConst.HTML);
			        if(ret) System.out.println("Temp Result copy to: "+archivePath); 
			}

			//register the result owner to pass security check
			//for accessing by the url 
			//"http://localhost:8888/jrserver/SampleReports/SampleReports.cat/CustomerAnalysis.cls/result/6323848938_1.html".
			//server.getTempResultOwnerManager().registerOwner("admin", BaseHttpUtil.getTempResultKey(new File(tempResult).getName()));

			server = null;
			System.out.println("\n========after exit, server=" + server);
		} catch (Throwable t) {
			t.printStackTrace();
		}
		System.exit(0);
	}
	
	public static boolean copyResultFromRemote(String remoteFileName, String localPath, RemoteFileService remoteFileService, int resultType) {
	        if(remoteFileName==null||remoteFileName.length()==0) return false;
	        int idx = -1;
	        if(resultType==APIConst.HTML) {
	        	idx = remoteFileName.lastIndexOf("_");
	        } else {
	        	idx = remoteFileName.lastIndexOf(".");
	        }
	        StringBuffer sb = new StringBuffer();
	        if(idx > 1) {
	                sb.append(remoteFileName.substring(0, idx-1)).append("*");
	        } else {
	        	sb.append(remoteFileName);
	        }
	        try {
	                remoteFileService.copyFromRemote(sb.toString(), localPath);
	                return true;
	        } catch (Exception e) {
	        	return false;
	        }
	}
}
