1    package com.instantbank.lettertemplate.control.web.handlers;
2    
3    import java.util.HashMap;
4    import java.util.ArrayList;
5    import java.util.Enumeration;
6    import java.util.Locale;
7    import java.util.Hashtable;
8    import java.text.SimpleDateFormat;
9    import java.text.ParsePosition;
10   
11   import javax.servlet.http.HttpServletRequest;
12   import javax.servlet.ServletContext;
13   
14   import oracle.xml.parser.v2.*;
15   import org.w3c.dom.*;
16   import org.xml.sax.*;
17   
18   import com.instantbank.lettertemplate.control.event.SetLetterJobEvent;
19   import com.instantbank.lettertemplate.control.util.JSPUtil;
20   import com.instantbank.lettertemplate.control.util.WebKeys;
21   import com.instantbank.common.utilcomponents.Debug;
22   import com.instantbank.common.utilcomponents.CommonUtil;
23   import com.instantbank.common.utilcomponents.LetterTemplateExceptionMessage;
24   import com.instantbank.common.utilcomponents.LetterTemplateGlobals;
25   import com.instantbank.lettertemplate.control.LetterTemplateEventException;
26   import com.instantbank.lettertemplate.control.event.LetterTemplateEvent;
27   
28   import com.instantbank.component.job.model.JobModel;
29   import com.instantbank.component.job.model.JobSELECTelement;
30   import com.instantbank.component.job.model.JobWHEREelement;
31   import com.instantbank.component.job.model.JobORDERelement;
32   import com.instantbank.lettertemplate.control.web.handlers.JobWebImpl;
33   
34   /**
35    *  Set letter Job usecase: handler of user requests in the Application layer
36    *
37    * @author Instant-bank (Consuelo Franky)
38    * @created November 2002
39    */
40   public class SetLetterJobHandler extends RequestHandlerSupport {
41   
42     private Debug debug = null;
43     ServletContext context;
44     private boolean gotoDB;
45     String companyId;
46     Long userId;
47   
48   
49     /**
50      *  principal method that process a user request instantiating a SetLetterJobEvent
51      *  with the user request data
52      *
53      * @param request of MainServlet
54      * @param context of MainServlet
55      * @return SetLetterJobEvent with the user
56      *      request data
57      * @exception LetterTemplateEventException
58      */
59     public LetterTemplateEvent processRequest(HttpServletRequest request,
60                                               ServletContext context)
61        throws LetterTemplateEventException {
62       debug = new Debug();
63       debug.setDebugginOn(true);
64       debug.setPreMessage("** SetLetterJobHandler-application tier: ");
65   
66       gotoDB = true;
67       this.context = context;
68       String action = request.getParameter("action");
69       debug.println("Creation of an SetLetterJob Event; "
70         + "SetLetterJobHandler (web): action=" + action);
71   
72       this.companyId = (String)request.getSession()
73         .getAttribute(WebKeys.CompanyId);
74   
75       if(action == null) {
76         throw new LetterTemplateEventException
77           (LetterTemplateExceptionMessage.SERVICE_NOT_SELECTED);
78       }
79       else if(action.equals("listJobs")) {
80         return createListSetLetterJobEvent(request);
81       }
82       else if(action.equals("getTemplateFields")) {
83         ;
84         return createGetTemplateFieldsEvent(request);
85       }
86       else if(action.equals("getJob")) {
87         return createGetSetLetterJobEvent(request);
88       }
89       else if(action.equals("saveJob")) {
90         return createSaveSetLetterJobEvent(request);
91       }
92       else if(action.equals("removeJob")) {
93         return createRemoveSetLetterJobEvent(request);
94       }
95       return null;
96     }
97   
98   
99     /**
100     *  method for instantiating a SetLetterJobEvent demanding a service of getting the
101     *  letter jobs list
102     *
103     * @param request of MainServlet
104     * @return SetLetterJobEvent with the user request data
105     * @exception LetterTemplateEventException
106     */
107    private LetterTemplateEvent createListSetLetterJobEvent
108      (HttpServletRequest request) throws LetterTemplateEventException {
109      debug.println("createListSetLetterJobEvent");
110      try {
111  
112        // instantiating SetLetterJobEvent:
113        SetLetterJobEvent event = new SetLetterJobEvent
114          (SetLetterJobEvent.LIST_JOBS,
115          (String)request.getSession()
116          .getAttribute(WebKeys.CompanyId),
117          (Long)request.getSession()
118          .getAttribute(WebKeys.UserId),
119          null,
120          null,
121          null);
122  
123        debug.println("event=" + event);
124        request.setAttribute(WebKeys.SetLetterJobEvent, event);
125        return event;
126      }
127      catch(Exception e) {
128        throw new LetterTemplateEventException
129          (LetterTemplateExceptionMessage.PROBLEM_PARSING + e.getMessage()
130          + LetterTemplateExceptionMessage.RETRY);
131      }
132    }
133  
134  
135    /**
136     *  method for instantiating a SetLetterJobEvent demanding a service of getting
137     *  the fields of a specific letter template
138     *
139     * @param request of MainServlet
140     * @return SetLetterJobEvent with the user request data
141     * @exception LetterTemplateEventException
142     */
143    private LetterTemplateEvent createGetTemplateFieldsEvent
144      (HttpServletRequest request) throws LetterTemplateEventException {
145      debug.println("createGetTemplateFieldsEvent");
146      try {
147        // getting HTML parameters :
148        Long templateId = new Long(request.getParameter("templateId").trim());
149        JobWebImpl jobView = (JobWebImpl)request.getSession()
150          .getAttribute(WebKeys.JobModelKey);
151        jobView.setTemplateCode(templateId.longValue());
152  
153        // instantiating SetLetterJobEvent:
154        SetLetterJobEvent event
155           = new SetLetterJobEvent
156          (SetLetterJobEvent.GET_TEMPLATE_FIELDS,
157          (String)request.getSession()
158          .getAttribute(WebKeys.CompanyId),
159          (Long)request.getSession()
160          .getAttribute(WebKeys.UserId),
161          templateId,
162          null,
163          null);
164        request.setAttribute(WebKeys.SetLetterJobEvent, event);
165        return event;
166      }
167      catch(Exception e) {
168        throw new LetterTemplateEventException
169          (LetterTemplateExceptionMessage.PROBLEM_PARSING + e.getMessage()
170          + LetterTemplateExceptionMessage.RETRY);
171      }
172    }
173  
174  
175    /**
176     *  method for instantiating a SetLetterJobEvent demanding a service of getting
177     *  a specific job
178     *
179     * @param request of MainServlet
180     * @return SetLetterJobEvent with the user request data
181     * @exception LetterTemplateEventException
182     */
183    private LetterTemplateEvent createGetSetLetterJobEvent
184      (HttpServletRequest request) throws LetterTemplateEventException {
185      debug.println("createGetSetLetterJobEvent");
186      try {
187        // getting HTML parameters :
188        Long jobId = new Long(request.getParameter("jobId").trim());
189        JobWebImpl jobView = (JobWebImpl)request.getSession()
190          .getAttribute(WebKeys.JobModelKey);
191        jobView.setJobId(jobId);
192  
193        // instantiating SetLetterJobEvent:
194        SetLetterJobEvent event
195           = new SetLetterJobEvent
196          (SetLetterJobEvent.GET_JOB,
197          (String)request.getSession()
198          .getAttribute(WebKeys.CompanyId),
199          (Long)request.getSession()
200          .getAttribute(WebKeys.UserId),
201          null,
202          jobId,
203          null);
204        request.setAttribute(WebKeys.SetLetterJobEvent, event);
205        return event;
206      }
207      catch(Exception e) {
208        throw new LetterTemplateEventException
209          (LetterTemplateExceptionMessage.PROBLEM_PARSING + e.getMessage()
210          + LetterTemplateExceptionMessage.RETRY);
211      }
212    }
213  
214  
215    /**
216     *  method for instantiating a SetLetterJobEvent demanding a service of
217     *  saving a job
218     *
219     * @param request of MainServlet
220     * @return SetLetterJobEvent with the user request data
221     * @exception LetterTemplateEventException
222     */
223    private LetterTemplateEvent createSaveSetLetterJobEvent
224      (HttpServletRequest request) throws LetterTemplateEventException {
225      debug.println("createSaveSetLetterJobEvent");
226      JobModel jobModel = null;
227  
228      try {
229        this.userId = (Long)request.getSession().getAttribute(WebKeys.UserId);
230        JobWebImpl jobView = (JobWebImpl)request.getSession()
231          .getAttribute(WebKeys.JobModelKey);
232  
233        // getting HTML parameters :
234        String xmlJob = request.getParameter("xmlJob").trim();
235  
236        // parsing XML of xmlJob resulting a JobModel for the job to save:
237        jobModel = parseXMLJob(xmlJob, jobView);  // jobView was updated
238        request.getSession().setAttribute(WebKeys.JobModelKey, jobView);
239  
240        // instantiating SetLetterEvent
241        SetLetterJobEvent event
242           = new SetLetterJobEvent
243          (SetLetterJobEvent.SAVE_JOB,
244          (String)request.getSession()
245          .getAttribute(WebKeys.CompanyId),
246          (Long)request.getSession()
247          .getAttribute(WebKeys.UserId),
248          null,
249          jobModel.getJobId(),
250          jobModel);
251        request.setAttribute(WebKeys.SetLetterJobEvent, event);
252        return event;
253      }
254      catch(Exception e) {
255        throw new LetterTemplateEventException
256          (LetterTemplateExceptionMessage.PROBLEM_PARSING + e.getMessage()
257          + LetterTemplateExceptionMessage.RETRY);
258      }
259    }
260  
261  
262    /**
263     *  method for instantiating a SetLetterJobEvent demanding a service of removing
264     *  a specif job
265     *
266     * @param request of MainServlet
267     * @return SetLetterJobEvent with the user request data
268     * @exception LetterTemplateEventException
269     */
270    private LetterTemplateEvent createRemoveSetLetterJobEvent
271      (HttpServletRequest request) throws LetterTemplateEventException {
272      debug.println("createRemoveSetLetterJobEvent");
273      try {
274        // getting HTML parameters :
275        Long jobId = new Long(request.getParameter("jobId").trim());
276  
277        // instantiating SetLetterJobEvent:
278        SetLetterJobEvent event
279           = new SetLetterJobEvent
280          (SetLetterJobEvent.REMOVE_JOB,
281          (String)request.getSession()
282          .getAttribute(WebKeys.CompanyId),
283          (Long)request.getSession()
284          .getAttribute(WebKeys.UserId),
285          null,
286          jobId,
287          null);
288        request.setAttribute(WebKeys.SetLetterJobEvent, event);
289        return event;
290      }
291      catch(Exception e) {
292        throw new LetterTemplateEventException
293          (LetterTemplateExceptionMessage.PROBLEM_PARSING + e.getMessage()
294          + LetterTemplateExceptionMessage.RETRY);
295      }
296    }
297  
298  
299    /**
300     *  auxiliary method for parsing a XML string containing data of a job to save
301     *
302     * @param xmlJob is the XML string
303     * @param jobView javaBean view of Job EJB
304     * @return a JobModel of the job to save
305     * @throws LetterTemplateEventException Description of the Exception
306     * @throws Exception Description of the Exception
307     */
308    private JobModel parseXMLJob(String xmlJob, JobWebImpl jobView)
309       throws LetterTemplateEventException, Exception {
310      debug.println("parseXMLJob");
311  
312      Long jobId = null;
313      String jobIdStr = null;
314      String status;
315      String name;
316      String description;
317      String frequency;
318      status = name = description = frequency = null;
319  
320      long ftpPrimaryId;
321  
322      long ftpAlternateId;
323  
324      long templateCode;
325  
326      long queueTypeId;
327      ftpPrimaryId = ftpAlternateId = LetterTemplateGlobals.UNDEF;
328      templateCode = queueTypeId = LetterTemplateGlobals.UNDEF;
329  
330      String startDateStr = null;
331      java.sql.Date activationDate = null;
332      SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
333  
334      Element root;
335      XMLNode node;
336      NodeList nodeList;
337      JobModel jobModel;
338      ArrayList jobSELECT;
339      ArrayList jobWHERE;
340      ArrayList jobORDER;
341      jobSELECT = jobWHERE = jobORDER = null;
342  
343      XMLDocument inxml = CommonUtil.parseInfo(xmlJob);
344  
345      root = inxml.getDocumentElement();
346      nodeList = root.getChildNodes();
347      for(int i = 0; i < nodeList.getLength(); i++) {
348        node = (XMLNode)nodeList.item(i);
349        if(node.getNodeName().equals("DownloadFields")) {
350          jobIdStr = node.valueOf("./id");
351          jobId = (jobIdStr.equals("-1")) ? null : new Long(jobIdStr);
352          ;
353          templateCode = Long.parseLong(node.valueOf("./templateCode"));
354          name = CommonUtil.toSafeOracleString(node.valueOf("./name"));
355          queueTypeId = Long.parseLong(node.valueOf("./type"));
356          status = node.valueOf("./status");
357          description
358            = CommonUtil.toSafeOracleString(node.valueOf("./description"));
359          frequency = node.valueOf("./frequency");
360          startDateStr = node.valueOf("./startdate");
361          ParsePosition pos = new ParsePosition(0);
362          java.util.Date activationDateU = sdf.parse(startDateStr, pos);
363          activationDate = new java.sql.Date(activationDateU.getTime());
364  
365          //debug.println("node DownloadFields parsed");
366          jobView.setMaster(jobId, companyId, name, frequency,
367            status, activationDate, LetterTemplateGlobals.UNDEF,
368            LetterTemplateGlobals.UNDEF, userId, null,
369            templateCode, queueTypeId, description, "", null);
370  
371          if(jobId == null) {
372            jobView.setJobNull();
373          }
374          //debug.println("jobView.setMaster (jobId=" + jobId);
375        }
376  
377        else if(node.getNodeName().equals("RulesList")) {
378          //NodeList nodeListRules = xmlDoc.selectNodes("/Download/RulesList/Rule");
379          NodeList nodeListWHERE = node.getChildNodes();
380          XMLNode nodeRule;
381          jobWHERE = new ArrayList();
382          JobWHEREelement element = null;
383          for(int k = 0; k < nodeListWHERE.getLength(); k++) {
384            nodeRule = (XMLNode)nodeListWHERE.item(k);
385            int clause = Integer.parseInt(nodeRule.valueOf("./test"));
386            long fieldId = Long.parseLong(nodeRule.valueOf("./fieldId"));
387            String ruleOperator = nodeRule.valueOf("./operator");
388            String value
389               = CommonUtil.toSafeOracleString(nodeRule.valueOf("./value"));
390            if((ruleOperator.equals("=")) && (value.indexOf(",") > 0)) {
391              ruleOperator = "IN";
392            }
393            String connector = nodeRule.valueOf("./connector");  // it can be ""
394            int sequence = k + 1;
395            element = new JobWHEREelement(sequence, clause, fieldId,
396              ruleOperator, value, connector);
397            jobWHERE.add(element);
398          }
399          //debug.println("node RulesList parsed");
400          jobView.setJobWHERE(jobWHERE);
401        }
402  
403        else if(node.getNodeName().equals("SortList")) {
404          NodeList nodeListORDER = node.getChildNodes();
405          XMLNode nodeSort;
406          jobORDER = new ArrayList();
407          JobORDERelement element = null;
408          for(int k = 0; k < nodeListORDER.getLength(); k++) {
409            nodeSort = (XMLNode)nodeListORDER.item(k);
410            long fieldId = Long.parseLong(nodeSort.valueOf("./fieldId"));
411            String direction = nodeSort.valueOf("./direction");
412            String unicityMember = nodeSort.valueOf("./unicityMember");
413            int sequence = k + 1;
414            element = new JobORDERelement
415              (sequence, fieldId, direction, unicityMember);
416            jobORDER.add(element);
417          }
418          //debug.println("node SortList parsed");
419          jobView.setJobORDER(jobORDER);
420        }
421  
422        else if(node.getNodeName().equals("FieldsList")) {
423          NodeList nodeListSELECT = node.getChildNodes();
424          XMLNode nodeField;
425          jobSELECT = new ArrayList();
426          JobSELECTelement element = null;
427          for(int k = 0; k < nodeListSELECT.getLength(); k++) {
428            nodeField = (XMLNode)nodeListSELECT.item(k);
429            long fieldId = Long.parseLong(nodeField.valueOf("./fieldId"));
430            int sequence = k + 1;
431            element = new JobSELECTelement(sequence, fieldId);
432            jobSELECT.add(element);
433          }
434          //debug.println("node FieldsList parsed");
435          jobView.setJobSELECT(jobSELECT);
436        }
437  
438        else if(node.getNodeName().equals("Distribution")) {
439          NodeList nodeListFTP = node.getChildNodes();
440          XMLNode nodeLocations;
441          nodeLocations = (XMLNode)nodeListFTP.item(0);
442          ftpPrimaryId = Long.parseLong(nodeLocations.valueOf("./primaryid"));
443          ftpAlternateId = Long.parseLong(nodeLocations.valueOf("./secondaryid"));
444          //debug.println("node Distribution parsed");
445          jobView.setFtpPrimaryId(ftpPrimaryId);
446          jobView.setFtpAlternateId(ftpAlternateId);
447        }
448      }
449  
450      // calculs current date in String MM-dd-yyyy :
451      java.util.Date todayU = new java.util.Date();
452      String todayString = sdf.format(todayU);
453      java.sql.Date today = new java.sql.Date(todayU.getTime());
454  
455      if(jobIdStr.equals("-1") && (!startDateStr.equals(todayString))
456        && (activationDate.compareTo(today) < 0)) {
457        // new job has incorrect activation date:
458        throw new LetterTemplateEventException
459          (LetterTemplateExceptionMessage.INCORRECT_ACTIVATION_DATE);
460      }
461  
462      jobModel = new JobModel
463        (jobId, this.companyId, name, frequency, status, activationDate,
464        ftpPrimaryId, ftpAlternateId, this.userId,
465        null /* version */, templateCode, queueTypeId, description,
466        "" /* sqlText */, null /* lastExecutionDate */,
467        jobSELECT, jobWHERE, jobORDER);
468      return jobModel;
469    }
470  }
471  
472