import java.security.acl.Permission;
import java.util.*;

import jet.cs.util.*;
import jet.server.api.*;
import jet.server.api.http.*;
import jet.server.api.exception.*;

/**
 * This demo is created to demonstrate the usage of the JReport Server API methods of deployment.
 * Users can deploy catalog/reports or folders to server by these methods.
 * Assume that there is a catalog SampleReports.cat, a report CustomerAnalysis.cls 
 * and other files and folders under C:\temp\SampleReports.
 * You can copy these files from c:\JReport\Designer\Demo\Reports\SampleReports where Designer is installed.
 */
public class APIDemoDeployRpt{

	public static void main(String[] args)
	{
		HttpRptServer httpRptServer = null;
		try {
			// Set report home
			System.getProperties().put("reporthome", "C:\\JReport\\Server");

			// Creates instance of RptServer (JReport Server can not be running already)
			HttpUtil.initEnv(System.getProperties());
			httpRptServer = HttpUtil.getHttpRptServer();
			System.out.println(" ========httpRptServer= " + httpRptServer);

			Properties prop = new Properties();
			String user = "admin";
			String realm = "defaultRealm";
			Hashtable[] userprop = null;
			VersionRecord ret = null;

			// check privilege of deployment
			if (!httpRptServer.getHttpUserSessionManager().getAuthenticator().checkPrivilege(realm, user, APIConst.PRIVILEGE_PUBLISH_REPORT)) {
				System.out.println("You do not have privilege to deploy resource!");
				System.exit(0);
				return;
			}

			// define user permissions
			// Set guest user and everyone role read and write permission for newly deployed resources
			userprop = new Hashtable[2];
	    	userprop[0] = new Hashtable();
	    	userprop[1] = new Hashtable();
	    	Vector<Permission> perValues = new Vector<Permission>();
			perValues.addElement(Permissions.P_READ);
			perValues.addElement(Permissions.P_WRITE);
			userprop[0].put("guest", perValues);
			userprop[1].put("everyone", perValues);

			// start deploying resource
			String path = "/SampleReports";
			// check write permission of the path
            if (!httpRptServer.getResourceManager().checkPermission(user, path, Permissions.P_WRITE)) {
			    System.out.println("You do not have write permission of " + path + "!");
				System.exit(0);
				return;
			}

			// -------------------------------------------------------------------------
			// 1.Create a folder called folder1 under /SampleReports by calling createFolder
			// -------------------------------------------------------------------------
			String folderName = "folder1";
			// This is an option: if /SampleReports/folder1 exists, remove it.
			removeResourceFolder(user, path, "/SampleReports/folder1", httpRptServer);

			prop.put(APIConst.TAG_NODE_TYPE, String.valueOf(APIConst.NODE_FOLDER));
			prop.put(APIConst.TAG_NODE_NAME, "folder1");
			prop.put(APIConst.TAG_NODE_DESC, "new folder1");
			prop.put(APIConst.TAG_ENABLE_ARCHIVE_POLICY, "true");
			prop.put(APIConst.TAG_ARCHIVE_NEW_VERSION, "false");
			prop.put(APIConst.TAG_DEFINE_PERMISSION, "true");
			try {
                String s = httpRptServer.getResourceManager().createFolder(user, path, folderName, prop, userprop);
				if (s == null) {
				    System.out.println("Please check resource name and try again.");
				} else {
					System.out.println("The folder " + folderName + " has been created successfully.");
				}				
            } catch (Exception e) {
				e.printStackTrace();
			} finally {
				prop.clear();
			}
			
			// -------------------------------------
			// 2. deploy a catalog/report to server
			// -------------------------------------
			// deploy catalog to /SampleReports/folder1 by calling addResource
			path = "/SampleReports/folder1";
			String catName = "catalog.cat";
            prop.put(APIConst.TAG_DEPLOY_FROM_FILE, "c:\\temp\\SampleReports\\SampleReports.cat");
			prop.put(APIConst.TAG_NODE_TYPE, String.valueOf(APIConst.NODE_CATALOG));
			prop.put(APIConst.TAG_NODE_NAME, catName);
			prop.put(APIConst.TAG_NODE_DESC, "new catalog");
			prop.put(APIConst.TAG_ENABLE_ARCHIVE_POLICY, "true");
			prop.put(APIConst.TAG_ARCHIVE_NEW_VERSION, "false");
			prop.put(APIConst.TAG_DEFINE_PERMISSION, "true");
			try {
                ret = httpRptServer.getResourceManager().addResource(user, path, prop, userprop);
				if (ret == null) {
				    System.out.println("Please check resource name and real name and try again.");
				} else {
					System.out.println("The catalog " + catName + " has been deployed successfully.");
				}
            } catch (Exception e) {
				e.printStackTrace();
		    } finally {
				prop.clear();
			}

			// deploy report to /SampleReports/folder1 by calling addResource
			String rptName = "report.cls";
            prop.put(APIConst.TAG_DEPLOY_FROM_FILE, "c:\\temp\\SampleReports\\CustomerAnalysis.cls");
			prop.put(APIConst.TAG_NODE_TYPE, String.valueOf(APIConst.NODE_REPORT));
			prop.put(APIConst.TAG_NODE_NAME, rptName);
			prop.put(APIConst.TAG_NODE_DESC, "new report");
			prop.put(APIConst.TAG_ENABLE_ARCHIVE_POLICY, "true");
			prop.put(APIConst.TAG_ARCHIVE_NEW_VERSION, "false");
			prop.put(APIConst.TAG_DEFINE_PERMISSION, "true");
			try {
                ret = httpRptServer.getResourceManager().addResource(user, path, prop, userprop);
				if (ret == null) {
				    System.out.println("Please check resource name and real name and try again.");
				} else {
					System.out.println("The report " + rptName + " has been deployed successfully.");
				}
            } catch (Exception e) {
				e.printStackTrace();
		    } finally {
				prop.clear();
			}

			// -------------------------------------------------------------------------
			// 3. create a folder called folder2 and add catalogs, reports and sub-folders 
			//   in a real directory to /SampleReports/folder2 by calling addResourcesToFolder
			// -------------------------------------------------------------------------
			path = "/SampleReports";
			folderName = "folder2";
			// This is an option: if /SampleReports/folder2 exists, remove it.
			removeResourceFolder(user, path, "/SampleReports/folder2", httpRptServer);

			String realPath = "c:\\temp\\SampleReports";
			boolean includeSubDir = true;
			prop.put(APIConst.TAG_NODE_TYPE, String.valueOf(APIConst.NODE_FOLDER));
			prop.put(APIConst.TAG_NODE_NAME, "folder2");
			prop.put(APIConst.TAG_NODE_DESC, "new folder2");
			prop.put(APIConst.TAG_ENABLE_ARCHIVE_POLICY, "true");
			prop.put(APIConst.TAG_ARCHIVE_NEW_VERSION, "false");
			prop.put(APIConst.TAG_DEFINE_PERMISSION, "true");
			try {
				String s = httpRptServer.getResourceManager().createFolder(user, path, folderName, prop, userprop);
				if (s == null) {
				    System.out.println("Please check resource name and try again.");
				} else {
					System.out.println("The folder " + folderName + " has been created successfully.");
				}
				httpRptServer.getResourceManager().addResourcesToFolder(user, path + "/" + folderName, realPath, includeSubDir, new Properties(), null);
			} catch (Exception e) {
				e.printStackTrace();
		    } finally {
				prop.clear();
			}

			// -------------------------------------------------------------------------
			// 4. create a folder called folder3 and only add catalogs and reports in a 
			//   real directory to /SampleReports/folder3 by calling addResourcesToFolder
			// -------------------------------------------------------------------------
			path = "/SampleReports";
			folderName = "folder3";
			// This is an option: if /SampleReports/folder3 exists, remove it.
			removeResourceFolder(user, path, "/SampleReports/folder3", httpRptServer);

			realPath = "c:\\temp\\SampleReports";
			includeSubDir = false;
			prop.put(APIConst.TAG_NODE_TYPE, String.valueOf(APIConst.NODE_FOLDER));
			prop.put(APIConst.TAG_NODE_NAME, "folder3");
			prop.put(APIConst.TAG_NODE_DESC, "new folder3");
			prop.put(APIConst.TAG_ENABLE_ARCHIVE_POLICY, "true");
			prop.put(APIConst.TAG_ARCHIVE_NEW_VERSION, "false");
			prop.put(APIConst.TAG_DEFINE_PERMISSION, "true");
			try {
				String s = httpRptServer.getResourceManager().createFolder(user, path, folderName, prop, userprop);
				if (s == null) {
				    System.out.println("Please check resource name and try again.");
				} else {
					System.out.println("The folder " + folderName + " has been created successfully.");
				}
				httpRptServer.getResourceManager().addResourcesToFolder(user, path + "/" + folderName, realPath, includeSubDir, new Properties(), null);
			} catch (Exception e) {
				e.printStackTrace();
		    } finally {
				prop.clear();
			}
			
		}catch (Throwable t){
			t.printStackTrace();
		}
		finally{
			// Make sure server is shutdown or there will be a 2 minute wait to start again
			httpRptServer.shutdown();
			System.out.println("Server "+ httpRptServer +" shutdown.");
		}
		System.exit(0);
    }

	/** 
	 * remove a folder from resource tree.
	 */
	private static void removeResourceFolder(String user, String path, String folder, HttpRptServer httpRptServer) {
		try {
			httpRptServer.getResourceManager().removeNode(user, folder);
		} catch (UnknownResource ue) {
			return;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


