package com.ibm.able.examples.rules.templates;


//====================================================================
//
// Licensed Materials - Property of IBM
//
// "Restricted Materials of IBM"
//
// Product: com.ibm.able.examples.rules
//
// (C) Copyright IBM Corp. 2001 All Rights Reserved.
//
// US Government Users Restricted Rights - Use, duplication or
// disclosure restricted by GSA ADP Schedule Contract with
// IBM Corp.
//
//
//                             DISCLAIMER
//                             ----------
//
// This material contains programming source code for your consideration.
// These examples have not been thoroughly tested under all conditions.
// IBM, therefore, cannot guarantee or imply reliability, serviceability,
// performance or function of these programs.  All programs contained
// herein are provided to you "AS IS".  THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE EXPRESSLY
// DISCLAIMED.
//
//====================================================================


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.rmi.RemoteException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ibm.able.data.AbleVariable;
import com.ibm.able.rules.AbleRule;
import com.ibm.able.rules.AbleRuleSet;
import com.ibm.able.rules.AbleRuleSetTemplate;
import com.ibm.able.rules.AbleRuleTemplate;


/**
 *  This servlet and the associated JSP files provide a web interface
 * demonstration of the ABLE Rule Language template support 
 * To get this working in Eclipse/WSAD, you need to perform the following steps 
 * <p>
 * <ol>
 * <li>Change the basePath String in this class to point to the TemplateExample.arl files 
 * </li>
 * <li>Create a Web project and place the servlet in the Java Source folder
 * </li>
 * <li>Copy the JSP files into the Web Content folder
 * </li>
 * <li>Copy the ARL files into the basePath dir 
 * </li>
 * <li>Open a Web Browser on index.jsp  ...
 * </ol>
 * </p>
 * <p>
 * Load one of the example template rulesets by selecting them from the List box and
 * pressing Load.    Click on a Template button to go to a form to create a rule from template.
 * You can press View ARL source, View XML source, to see what gets generated. 
 * </p>
 */
public class AbleWebActions extends HttpServlet {
 
	public String datastoredir;
	
	public static String basePath = "c:\\wsad\\workspace\\ableweb\\" ;
 
	/**
	 * Retrieve either the existing AbleRuleSet bean from the session or else create a new one
	 */
	public static synchronized AbleRuleSet getRuleSetBean(HttpServletRequest req) throws RemoteException {
	    HttpSession hs = req.getSession();
		AbleRuleSet rs = (AbleRuleSet)hs.getAttribute("theRuleSet");
		if (rs == null) rs = new AbleRuleSet("globalRuleSet");
		hs.setAttribute("theRuleSet", rs) ; 
		return rs;
	}

	

	/**
	* @see javax.servlet.GenericServlet#void ()
	*/
	public void destroy() {
		super.destroy();
	}

	/**
	* @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	*/
	public void doDelete(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
		super.doDelete(req, resp);
	}

	public void writeHeader(Writer wtr) throws IOException {
		wtr.write("<html>");
		wtr.write("<HEAD>");
		wtr.write("<META http-equiv=\"Content-Type\"");
		wtr.write("	content=\"text/html; charset=WINDOWS-1252\">");
		wtr.write("<META name=\"GENERATOR\" content=\"IBM WebSphere Studio\">");
		wtr.write(
			"<META http-equiv=\"Content-Style-Type\" content=\"text/css\">");
		wtr.write(
			"<LINK href=\"theme/Master.css\" rel=\"stylesheet\" type=\"text/css\">");
		wtr.write("<TITLE>AbleWebActions.java</TITLE>");
		wtr.write("</HEAD>");
		wtr.write("<BODY>");
	}

	public void writeFooter(Writer wtr) throws IOException {
		wtr.write("<p><a href=index.jsp>Back to Main Page</a></p>");
		wtr.write("</BODY>");
		wtr.write("</html>");
		wtr.close();
	}
	/**
	* @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	*/
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {

        AbleRuleSet rs = getRuleSetBean(req) ; 
        HttpSession hs = req.getSession();
	  	try {
			Writer wtr = resp.getWriter();
			String choice = req.getParameter("option");
			try {
				if (choice == null) {
				} else if (choice.equalsIgnoreCase("loadfile")) {
		 			writeHeader(wtr);
					wtr.write("<H3>Load RuleSet</H3>");
					/* create clean store */
				  
					String fname = req.getParameter("filename");

					if ((fname == null) || (fname.compareTo("") == 0)) {
						wtr.write(
							"<p><b>Empty filename. "
								+ "Please press <a href=index.jsp>here to return to try again</a>"
								+ "</b></p>");
					} else {
						try {
						  rs.parseFromARL(basePath + fname);
						  rs.init();
						  rs.initRuleTemplates();  // get ready to use template APIs
						  wtr.write(
								"<p><b>File: "
									+ fname
									+ " successfully loaded "									 
									+ "</b></p>");									
						} catch (FileNotFoundException e) {
					  				wtr.write(
											"<p><b>File: "
												+ fname
												+ " unable to load. "
												+ "File not found exception."
												+ "</b></p>");										 
						} catch (IOException e)  {
										wtr.write(
											"<p><b>File: "
												+ fname
												+ " unable to be read. "
												+ "IO exception."
												+ "</b></p>");									 				 								 
						} 
						
						try {
						  rs.init() ; // now,  initialize the ruleset 
                		  wtr.write(
 								"<p><b>File: "
									+ fname
									+ " successfully initialized "									 
									+ "</b></p>");
						} catch (Exception e) {
						  wtr.write(
											"<p><b>File: "
												+ fname
												+ " was NOT initialized -- error. <p> "
												+ e.toString()
												+ "</b></p>");	
						}
						
				  	  } // endelse 
					writeFooter(wtr);
				} else if (choice.equalsIgnoreCase("savefile")) {
					writeHeader(wtr);
					wtr.write("<H3>Save RuleSet</H3>");
					String fname = req.getParameter("filename");
					if ((fname == null) || (fname.compareTo("") == 0)) {
						wtr.write(
							"<p><b>Empty filename. "
								+ "Please press <a href=index.jsp>here to return to try again</a>"
								+ "</b></p>");
					} else {
						// rs.saveToFile(fname);  // serialize ???
						 
						 File out = new File(fname) ; 
						 FileWriter fWriter = new FileWriter(out) ;
						 fWriter.write(rs.arlString());
						 fWriter.close();
							 
							wtr.write(
								"<p><b>File: "								 
									+ " Ruleset successfully saved to " + fname 
								 	+ "</b></p>");
						 
					    }
			 
		 
					writeFooter(wtr);
				} else if (choice.equalsIgnoreCase("editruletemplate")) {
		 			
		             String templateName = req.getParameter("templatename");
				 	try {
						AbleRuleTemplate lclRuleTemp = rs.getRuleTemplate(templateName);  
						hs.setAttribute("theRuleTemplate", lclRuleTemp); 
						req.setAttribute("theRuleTemplate", lclRuleTemp); 
						// do whatever else necessary
						ServletContext sc = getServletConfig().getServletContext();						 
						RequestDispatcher rd = sc.getRequestDispatcher("editruletemplate.jsp");
						rd.forward(req, resp);
					} catch (Exception ex) {
						writeHeader(wtr);
						wtr.write(
							"<p><b>Can't get theRuleTemplate from request."
							+ex.toString()
							+"</b></p>");
						writeFooter(wtr);
					}				 
				} else if (choice.equalsIgnoreCase("createrule")) {
					try {
    					hs = req.getSession();
						AbleRuleTemplate template = (AbleRuleTemplate)hs.getAttribute("theRuleTemplate");
						ServletContext sc = getServletConfig().getServletContext();
		 			
					   Object[] vars = template.getTemplateVars() ; 
					   AbleRule newRule = null ; 
					  	 
					   // get parameters and set variable values inside the template 						
					   for (int i=0; i < vars.length; i++) {
						   AbleVariable var = (AbleVariable)vars[i];
						   String value = (String)req.getParameter(var.getName());
						   var.setStringValue(value) ; 
					   }

				 	   newRule = rs.addRuleFromTemplate(template) ; // create the new rule
				 	
    				   req.setAttribute("theRuleTemplate", template);
					
					// do whatever else necessary
					//	RequestDispatcher rd = 
					//		sc.getRequestDispatcher("successfail.jsp");
					//	rd.forward(req, resp);
						
							wtr.write(
								"<p><b>Template: "
									+ template.getName()
									+ " successfully created new rule from template "
									+ "<p>"
					                + newRule.arlString()
								 	+ "</p>"
								 	+ "</b></p>");
						   	 
		 
					writeFooter(wtr);
					} catch (Exception ex) {
						writeHeader(wtr);
						wtr.write(
							"<p><b>Can't instantiate a rule from the template with supplied replacement values.  Please retry.<br>"
							+ex.toString()
							+"</b></p>");
						writeFooter(wtr);
					}
					
				} else if (choice.equalsIgnoreCase("editrulesettemplate")) {
		 			
		             String templateName = req.getParameter("templatename");
				 	try {
						AbleRuleSetTemplate lclRuleSetTemp = rs.getRuleSetTemplate();  
						hs.setAttribute("theRuleSetTemplate", lclRuleSetTemp); 
						req.setAttribute("theRuleSetTemplate", lclRuleSetTemp); 
						// do whatever else necessary
						ServletContext sc = getServletConfig().getServletContext();						 
						RequestDispatcher rd = sc.getRequestDispatcher("editrulesettemplate.jsp");
						rd.forward(req, resp);
					} catch (Exception ex) {
						writeHeader(wtr);
						wtr.write(
							"<p><b>Can't get theRuleSetTemplate from request."
							+ex.toString()
							+"</b></p>");
						writeFooter(wtr);
					}			
					
				} else if (choice.equalsIgnoreCase("createruleset")) {
					try {
						hs = req.getSession();
						AbleRuleSetTemplate template = (AbleRuleSetTemplate)hs.getAttribute("theRuleSetTemplate");
						ServletContext sc = getServletConfig().getServletContext();
							
						// get parameters and set variable values in the template
						Object[] vars = template.getTemplateVars() ;
						for (int i=0; i < vars.length; i++) {
						   AbleVariable var = (AbleVariable)vars[i];
						   String value = (String)req.getParameter(var.getName());
						   var.setStringValue(value) ; 
						}
						// then create the new ruleset instance 	
						AbleRuleSet newRuleSet = rs.createRuleSetFromTemplate(template) ; 
						
						req.setAttribute("theRuleSetTemplate", template);
						// do whatever else necessary
					//	RequestDispatcher rd = 
					//		sc.getRequestDispatcher("successfail.jsp");
					//	rd.forward(req, resp);
						
							wtr.write(
								"<p><b>Template: "
									+ template.getName()
									+ " successfully created new ruleset from template "
									+ "<pre>"
					                + newRuleSet.arlString()
								 	+ "</pre>"
								 	+ "</b></p>");
						   	 
		 
					writeFooter(wtr);
					} catch (Exception ex) {
						writeHeader(wtr);
						wtr.write(
							"<p><b>Can't instantiate a ruleset from the template with supplied replacement values.  Please retry.<br>"
							+ex.toString()
							+"</b></p>");
						writeFooter(wtr);
					}			
					
				} else if (choice.equalsIgnoreCase("editrule")) {
		 			
		             
   	                 String ruleName = req.getParameter("rulename");
				 	try {
						
						AbleRule lclRule = rs.getRule(ruleName) ; 
						hs.setAttribute("theRule", lclRule); 
						req.setAttribute("theRule", lclRule); 
						 
						String lclRuleTempName = lclRule.getTemplateName();
						AbleRuleTemplate lclRuleTemp = rs.getRuleTemplate(lclRuleTempName);  
						hs.setAttribute("theRuleTemplate", lclRuleTemp); 
						req.setAttribute("theRuleTemplate", lclRuleTemp); 
						
						// do whatever else necessary
						ServletContext sc = getServletConfig().getServletContext();						 
						RequestDispatcher rd = sc.getRequestDispatcher("editrule.jsp");
						rd.forward(req, resp);
					} catch (Exception ex) {
						writeHeader(wtr);
						wtr.write(
							"<p><b>Can't get theRule or theRuleTemplate from request."
							+ex.toString()
							+"</b></p>");
						writeFooter(wtr);
					}		
				} else if (choice.equalsIgnoreCase("replacerule")) {
					try {
						hs = req.getSession();
						AbleRuleTemplate template = (AbleRuleTemplate)hs.getAttribute("theRuleTemplate");
						ServletContext sc = getServletConfig().getServletContext();	 			
					 
					   Object[] vars = template.getTemplateVars() ; 
					   AbleRule newRule = null ; 
					 	
					   // get parameters and set variable values						
					   for (int i=0; i < vars.length; i++) {
						   AbleVariable var = (AbleVariable)vars[i];
						   String value = (String)req.getParameter(var.getName());
						   var.setStringValue(value) ; 
					   }
 
				 	   newRule = rs.replaceRuleFromTemplate(template) ; // create and replace the rule						
					   req.setAttribute("theRuleTemplate", template);
					
					// do whatever else necessary
					//	RequestDispatcher rd = 
					//		sc.getRequestDispatcher("successfail.jsp");
					//	rd.forward(req, resp);
						
							wtr.write(
								"<p><b>Template: "
									+ template.getName()
									+ " successfully replaced a rule from template "
									+ "<p>"
					                + newRule.arlString()
								 	+ "</p>"
								 	+ "</b></p>");
						   	 
		 
					writeFooter(wtr);
					} catch (Exception ex) {
						writeHeader(wtr);
						wtr.write(
							"<p><b>Can't instantiate a rule from the template with supplied replacement values.  Please retry.<br>"
							+ex.toString()
							+"</b></p>");
						writeFooter(wtr);
					}		
				} else if (choice.equalsIgnoreCase("viewsource")) {
					writeHeader(wtr);
			        wtr.write("<H3>View RuleSet Source</H3>");
					wtr.write("<pre>" + rs.arlString() + "</pre>");			
					writeFooter(wtr);
				
				
			    } else if (choice.equalsIgnoreCase("viewxml")) {
				    writeHeader(wtr);
					wtr.write("<H3>View RuleSet XML</H3>");			
					wtr.write("<pre><textarea readonly rows=\"30\" cols=\"80\">" + rs.xmlString() + "</textarea></pre>");
					writeFooter(wtr);
				
				} else if (choice.equalsIgnoreCase("reset")) {
					writeHeader(wtr);
					rs.clear();
					wtr.write("<p><b>Reset pressed. Ruleset is cleared from memory" + "</b></p>");
					writeFooter(wtr);
				 		 	   
				} else if (choice.equalsIgnoreCase("cancel")) {
					writeHeader(wtr);
					wtr.write("<p><b>Cancel pressed." + "</b></p>");
					writeFooter(wtr);
				}
			} catch (Throwable e) {
				log(e.toString(), e);
				writeHeader(wtr);
				wtr.write(
					"<p><b>Error processing request "
						+ e.toString()
						+ "</b></p>");
				writeFooter(wtr);
			}
		} catch (IOException e) {
			log(e.toString(), e);
			//log(e);
			//e.printStackTrace();
		}

	}

	/**
	* @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	*/
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {

		doGet(req, resp);
        // super.doPost(req, resp) ; 
	}

	/**
	* @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	*/
	public void doPut(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {

		super.doPut(req, resp);

	}

	/**
	* @see javax.servlet.GenericServlet#java.lang.String ()
	*/
	public String getServletInfo() {

		return super.getServletInfo();

	}

	/**
	* @see javax.servlet.GenericServlet#void ()
	*/
	public void init() throws ServletException {

		super.init();

		datastoredir = System.getProperty("DATA_STORE_DIR");
		if (datastoredir == null) {
			datastoredir = "";
		}
	}

}
