1    package com.instantbank.lettertemplate.control.web;
2    
3    import javax.servlet.ServletException;
4    import javax.servlet.ServletContext;
5    import javax.servlet.RequestDispatcher;
6    import javax.servlet.http.HttpServlet;
7    import javax.servlet.http.HttpSession;
8    import javax.servlet.http.HttpServletRequest;
9    import javax.servlet.http.HttpServletResponse;
10   
11   import java.io.PrintWriter;
12   import java.io.StringWriter;
13   import java.io.OutputStreamWriter;
14   import java.io.IOException;
15   
16   import java.beans.Beans;
17   import java.util.HashMap;
18   import java.util.Locale;
19   
20   import com.instantbank.lettertemplate.control.util.WebKeys;
21   import com.instantbank.lettertemplate.control.util.JSPUtil;
22   import com.instantbank.lettertemplate.control.LetterTemplateEventException;
23   
24   import com.instantbank.common.utilcomponents.Debug;
25   import com.instantbank.common.utilcomponents.CommonUtil;
26   import com.instantbank.common.utilcomponents.JNDINames;
27   import com.instantbank.common.utilcomponents.LetterTemplateExceptionMessage;
28   
29   /**
30    *  Main Servlet of the lettertemplate ear: MVC controller in the Application layer
31    *
32    * @author Instant-bank (Consuelo Franky)
33    * @created August 2002
34    */
35   public class MainServlet extends HttpServlet {
36   
37     private Debug debug = null;
38   
39   
40     /**
41      *  unique instances of RequestProcessor and ScreenFlowManager by web
42      *  context
43      */
44     public void init() {
45       debug = new Debug();
46       debug.setDebugginOn(true);
47       debug.setPreMessage("** MainServlet: ");
48       debug.println("MainServlet: Initializing");
49   
50       // we need to initialize the ScreenFlowManager first
51       // because the RequestProcessor depends on the ScreenFlowManager
52       getScreenFlowManager();
53       getRequestProcessor();
54   
55     }
56   
57   
58     /**
59      *  process post request from user
60      *
61      * @param request HTTP user request
62      * @param response HTTP response
63      * @exception IOException
64      * @exception ServletException
65      */
66     public void doPost
67       (HttpServletRequest request, HttpServletResponse response)
68        throws IOException, ServletException {
69       doGet(request, response);
70     }
71   
72   
73     /**
74      *  process get request from user
75      *
76      * @param request HTTP user request
77      * @param response HTTP response
78      * @exception IOException
79      * @exception ServletException
80      */
81     public void doGet
82       (HttpServletRequest request, HttpServletResponse response)
83        throws IOException, ServletException {
84   
85       HttpSession session = request.getSession();
86       debuggingMainServlet(request, response);
87   
88       if(controlTimeout(request, response)) {
89         debug.println("invalidate session and return by timeout");
90         session.invalidate();
91         return;
92         // here there is a forward to /control_web/TimeOutPage.jsp
93         // prepared by controlTimeout()
94       }
95   
96       if(request.getRequestURI().endsWith("passport")) {
97         // It's a selected request by the banner that has gotten timeout passport.
98         // Now the request must be forwarded to MainDispatcher of Instantbank ear
99         // in order to be dispatched:
100        String url
101           = "/Instantbank/main_web/MainDispatcher?externalRequest=true&"
102          + request.getQueryString();
103        //debug.println ("url to Instantbank ear:" + url);
104        response.sendRedirect(url);
105        return;
106      }
107  
108      // treatment of a dispatched request by MainDispatcher of Instantbank ear
109      // or of a lettertemplate local request (non selected by banner):
110      String useCase = request.getParameter("useCase");
111      if(useCase != null) {
112        // request coming from Instantbank ear
113        captureCollectionsVariables(request);
114      }
115  
116      if(session.isNew()) {
117        // first invocation of lettertemplate ear
118        captureEnvironmentVariables(request);
119      }
120  
121      String selectedURL = request.getPathInfo();
122      if(selectedURL.equals("/white")) {
123        return;
124      }
125  
126      ScreenFlowManager screenManager = null;
127      ModelManager modelManager = (ModelManager)request.getSession()
128        .getAttribute(WebKeys.ModelManagerKey);
129      if(modelManager == null) {
130        try {
131          modelManager =
132            (ModelManager)Beans.instantiate
133            (this.getClass().getClassLoader(),
134            "com.instantbank.lettertemplate.control.web.ModelManager");
135        }
136        catch(Exception exc) {
137          throw new ServletException
138            (LetterTemplateExceptionMessage.NOT_MODEL_MANAGER + exc.getMessage());
139        }
140        session.setAttribute(WebKeys.ModelManagerKey, modelManager);
141        modelManager.init(getServletContext(), session);
142      }
143  
144      Object answer = null;
145      try {
146        // invokes RequestProcessor for processing the request and
147        // updating Model View; gets the service answer
148        answer = getRequestProcessor().processRequest(request);
149        debug.println("request has been processed");
150  
151      }
152      catch(LetterTemplateEventException ex) {
153        debug.println("caught LetterTemplateEventException A :" + ex.toString());
154        //request.setAttribute("javax.servlet.jsp.jspException", ex);
155        request.setAttribute(WebKeys.ExceptionOcurred, ex.getMessage());
156        StringWriter sw = new StringWriter();
157        PrintWriter pw = new PrintWriter(sw);
158        ex.printStackTrace(pw);
159        request.setAttribute(WebKeys.ExceptionStackTrace, sw.toString());
160      }
161  
162      try {
163        // invokes ScreenFlowManager for selecting the output screen:
164        getScreenFlowManager().getNextScreen
165          (request, answer, getServletContext());
166  
167      }
168      catch(LetterTemplateEventException ex) {
169        debug.println("caught LetterTemplateEventException B:" + ex.toString());
170        //request.setAttribute("javax.servlet.jsp.jspException", ex);
171        request.setAttribute(WebKeys.ExceptionOcurred, ex.getMessage());
172        StringWriter sw = new StringWriter();
173        PrintWriter pw = new PrintWriter(sw);
174        ex.printStackTrace(pw);
175        request.setAttribute(WebKeys.ExceptionStackTrace, sw.toString());
176        session.setAttribute(WebKeys.CurrentScreen, "ERROR");
177      }
178  
179      // Default to the base language or the site.
180      // If a language is found in the session use that template.
181      Locale locale =
182        (Locale)request.getSession().getAttribute(WebKeys.LanguageKey);
183      if(locale == null) {
184        locale = Locale.US;
185      }
186  
187      // forward to template JSP (template.jsp) for building the
188      // output screen;
189      // "getScreenFlowManager().getTemplate(locale)" is the name of
190      // template JSP corresponding to language (typically template.jsp)
191      getServletConfig().getServletContext()
192        .getRequestDispatcher(getScreenFlowManager().getTemplate(locale))
193        .forward(request, response);
194    }
195  
196  
197    /**
198     *  auxiliary method that instances an unique RequestProcessor by web
199     *  context
200     *
201     * @return The requestProcessor value
202     */
203    private RequestProcessor getRequestProcessor() {
204      RequestProcessor rp = (RequestProcessor)getServletContext()
205        .getAttribute(WebKeys.RequestProcessorKey);
206      if(rp == null) {
207        debug.println("initializing request processor");
208        rp = new RequestProcessor();
209        rp.init(getServletContext());
210        getServletContext().setAttribute
211          (WebKeys.RequestProcessorKey, rp);
212      }
213      return rp;
214    }
215  
216  
217    /**
218     *  auxiliary method that instances an unique ScreenFlowManager by web
219     *  context
220     *
221     * @return The screenFlowManager value
222     */
223    private ScreenFlowManager getScreenFlowManager() {
224      ScreenFlowManager screenManager =
225        (ScreenFlowManager)getServletContext()
226        .getAttribute(WebKeys.ScreenManagerKey);
227      if(screenManager == null) {
228        debug.println
229          ("Loading screen flow definitions");
230        screenManager = new ScreenFlowManager();
231        screenManager.init(getServletContext());
232        getServletContext().setAttribute
233          (WebKeys.ScreenManagerKey, screenManager);
234      }
235      return screenManager;
236    }
237  
238  
239    /**
240     *  debugging MainServlet
241     *
242     * @param request HTTP request
243     * @param response HTTP responser
244     */
245    private void debuggingMainServlet(HttpServletRequest request,
246                                      HttpServletResponse response) {
247      String info = null;
248      debug.println("======= LETTERS NEW REQUEST ========");
249      /*
250           *  info = request.getContextPath();
251           *  debug.println("ContextPath is" + (info==null ? "null" : info));
252           *  info = request.getServletPath();
253           *  debug.println("ServletPath=" + (info==null ? "null" : info));
254           *  info = request.getPathInfo();
255           *  debug.println("PathInfo=" + (info==null ? "null" : info));
256           */
257      info = request.getRequestURI();
258      debug.println("RequestURI is:" + (info == null ? "null" : info));
259      info = request.getQueryString();
260      debug.println("QueryString is:" + (info == null ? "null" : info));
261      /*
262           *  info = request.getPathTranslated();
263           *  debug.println("PathTranslated=" + (info==null ? "null" : info));
264           *  int contentLength = response.getResponseContentLength();
265           *  debug.println("ServletResponseContentLength=" + String.valueOf(contentLength));
266           */
267    }
268  
269  
270    /**
271     *  captures Collections web session variables
272     *
273     * @param request HTTP request
274     */
275    private void captureCollectionsVariables(HttpServletRequest request) {
276      HttpSession session = request.getSession();
277  
278      String companyName = request.getParameter("companyName");
279      String companyId = request.getParameter("companyId");
280      String version = request.getParameter("version");
281      String optionCollections = request.getParameter("optionCollections");
282      String optionCompany = request.getParameter("optionCompany");
283      String hasException = request.getParameter("hasException");
284      String strUserid = request.getParameter("userId");
285      String useCase = request.getParameter("useCase");
286  
287      /*
288             debug.println("request variables:"
289             + "\n -companyName=" + companyName
290             + "\n -version=" + version
291             + "\n -optionCollections=" + optionCollections
292             + "\n -optionCompany=" + optionCompany
293             + "\n -hasException=" + hasException
294             + "\n -strUserid=" + strUserid
295             + "\n -useCase=" + useCase
296             );
297           */
298      session.setAttribute(WebKeys.CompanyName, companyName);
299      session.setAttribute(WebKeys.CompanyId, companyId);
300      session.setAttribute(WebKeys.Version, version);
301      session.setAttribute(WebKeys.OptionCollections, optionCollections);
302      session.setAttribute(WebKeys.OptionCompany, optionCompany);
303      session.setAttribute(WebKeys.HasException, hasException);
304      session.setAttribute(WebKeys.UseCase, useCase);
305  
306      Long userId = null;
307      userId = Long.valueOf(request.getParameter("userId"));
308      session.setAttribute(WebKeys.UserId, userId);
309  
310      //debug.println("pUserName=" + session.getAttribute("_wl_authuser_"));
311      //String pUserName = session.getAttribute("_wl_authuser_").toString();
312      String pUserName = request.getRemoteUser();// QUESTION: See if request.getRemoteUser() works
313      String userName;
314      String companyNumber;
315      if(pUserName.lastIndexOf(new String(":")) != -1) {
316        int pUnderScore = pUserName.lastIndexOf(new String(":"));
317        userName = pUserName.substring(0, pUnderScore);
318        companyNumber = pUserName.substring(pUnderScore + 1, pUserName.length());
319      }
320      else {
321        userName = pUserName;
322        companyNumber = "";
323      }
324      session.setAttribute(WebKeys.UserName, userName);
325      session.setAttribute(WebKeys.CompanyNumber, companyNumber);
326  
327      /*
328           *  debugging:
329           *  String  sesscompanyName = (String)session.getAttribute(WebKeys.CompanyName);
330           *  String  sesscompanyId = (String)session.getAttribute(WebKeys.CompanyId);
331           *  String  sessversion = (String)session.getAttribute(WebKeys.Version);
332           *  String  sessoptionCollections = (String)session.getAttribute(WebKeys.OptionCollections);
333           *  String  sessoptionCompany = (String)session.getAttribute(WebKeys.OptionCompany);
334           *  String  sesshasException = (String)session.getAttribute(WebKeys.HasException);
335           *  String  sessuserName = (String)session.getAttribute(WebKeys.UserName);
336           *  String  sesscompanyNumber = (String)session.getAttribute(WebKeys.CompanyNumber);
337           *  userId = (Long)session.getAttribute(WebKeys.UserId);
338           *  String  sessuserId = (userId != null) ? userId.toString() : "";
339           *  String  sessusecase = (String)session.getAttribute(WebKeys.UseCase);
340           *  debug.println("session variables:"
341           *  + "\n -companyName=" + sesscompanyName
342           *  + "\n -companyId=" + sesscompanyId
343           *  + "\n -version=" + sessversion
344           *  + "\n -optionCollections=" + sessoptionCollections
345           *  + "\n -optionCompany=" + sessoptionCompany
346           *  + "\n -hasException=" + sesshasException
347           *  + "\n -userName=" + sessuserName
348           *  + "\n -companyNumber=" + sesscompanyNumber
349           *  + "\n -userId=" + sessuserId
350           *  + "\n -usecase=" + sessusecase
351           *  );
352           */
353    }
354  
355  
356    /**
357     *  control time out in lettertemplate ear
358     *
359     * @param request HTTP request
360     * @param response HTTP response
361     * @return true if timeout; false otherwise
362     * @exception IOException
363     * @exception ServletException
364     */
365    private boolean controlTimeout
366      (HttpServletRequest request, HttpServletResponse response)
367       throws IOException, ServletException {
368      boolean existsTimeout = false;
369      HttpSession session = request.getSession();
370  
371      debug.println("Session is new ?=" + session.isNew());
372  
373      if(session.isNew()) {
374        // 2 possible reasons: new valid user session
375        // or web server launched new session
376        // because of previous timeout in lettertemplate ear
377        //debug.println("Session Creation time=" + session.getCreationTime());
378        String strCompanySessionTime
379           = request.getParameter("companySessionTime");
380        if((strCompanySessionTime != null)
381          && (!strCompanySessionTime.equals(""))) {
382          // it is a new user session with valid request values:
383          // applies to: first time Instantbank forwards a request to lettertempl ear
384          Long companySessionTime
385             = Long.valueOf(request.getParameter("companySessionTime"));
386          if(companySessionTime.intValue() != 0) {
387            // companySessionTime is in minutes => multiply * 60 for obtaining seconds:
388            session.setMaxInactiveInterval((companySessionTime.intValue()) * 60);
389          }
390          else {  // the session should never timeout :
391            session.setMaxInactiveInterval(-1);
392          }
393        }
394        else {
395          // previous timeout inside lettertemplate ear => null request values
396          debug.println("timeout in lettertemplate ear");
397          getServletConfig().getServletContext()
398            .getRequestDispatcher("/control_web/TimeOutPage.jsp")
399            .forward(request, response);
400  
401          existsTimeout = true;
402          //INDUDATA style:
403          //response.sendRedirect("/lettertemplate/control_web/TimeOutPage.jsp");
404        }
405      }
406      return existsTimeout;
407    }
408  
409  
410    /**
411     *  actions for a new session:
412     *  capture Environment variables,
413     *  set web session variables,
414     *  clean temporal directories
415     *
416     * @param request HTTP request
417     */
418    private void captureEnvironmentVariables(HttpServletRequest request) {
419      HttpSession session = request.getSession();
420  
421      // captures externalDebugMode:
422      String externalDebugMode = CommonUtil.getApplicationProperty
423        (JNDINames.EXTERNAL_DEBUG_MODE);
424      session.setAttribute(WebKeys.ExternalDebugMode, externalDebugMode);
425  
426      // captures imagesTemporalPath:
427      String imagesTemporalPath = CommonUtil.getApplicationProperty
428        (JNDINames.IMAGES_TEMPORAL_PATH);
429      session.setAttribute(WebKeys.ImagesTemporalPath, imagesTemporalPath);
430  
431      // captures rtf2foConfigPath:
432      String rtf2foConfigPath = CommonUtil.getApplicationProperty
433        (JNDINames.RTF2FO_CONFIG_PATH);
434      session.setAttribute
435        (WebKeys.RtfToFoConfigPath, rtf2foConfigPath);
436  
437      // captures WLInitialContextFactory:
438      String WLInitialContextFactory = CommonUtil.getApplicationProperty
439        (JNDINames.WLInitialContextFactory);
440      session.setAttribute
441        (WebKeys.WLInitialContextFactory, WLInitialContextFactory);
442  
443      // captures ZipLettersFileMaxSize:
444      String ZipLettersFileMaxSize = CommonUtil.getApplicationProperty
445        (JNDINames.ZipLettersFileMaxSize);
446      session.setAttribute
447        (WebKeys.ZipLettersFileMaxSize, ZipLettersFileMaxSize);
448  
449      // clean temporal directories:
450      //CommonUtil.cleanTemporaldirectory(imagesTemporalPath);
451    }
452  }
453  
454