1    package com.instantbank.lettertemplate.templatePreview.web;
2    
3    
4    import java.io.IOException;
5    import java.io.ByteArrayOutputStream;
6    import java.io.File;
7    import java.io.FileOutputStream;
8    
9    import java.util.ArrayList;
10   import java.util.Date;
11   import java.util.Set;
12   
13   import javax.servlet.ServletException;
14   import javax.servlet.ServletOutputStream;
15   
16   import javax.servlet.http.HttpServlet;
17   import javax.servlet.http.HttpServletRequest;
18   import javax.servlet.http.HttpServletResponse;
19   import javax.servlet.http.HttpSession;
20   
21   // for working with EJB:
22   import javax.naming.InitialContext;
23   import com.instantbank.lettertemplate.control.util.JSPUtil;
24   import com.instantbank.lettertemplate.control.util.WebKeys;
25   import com.instantbank.lettertemplate.editor.web.TemplateTransformer;
26   
27   import com.instantbank.component.lettertemplate.util.LetterViewable;
28   import com.instantbank.component.lettertemplate.util.Template;
29   
30   import com.instantbank.component.lettertemplate.ejb.LetterTemplate;
31   import com.instantbank.component.lettertemplate.ejb.LetterTemplateHome;
32   
33   // utilities:
34   import com.instantbank.common.utilcomponents.Debug;
35   import com.instantbank.common.utilcomponents.LetterTemplateExceptionMessage;
36   import com.instantbank.common.utilcomponents.LetterTemplateGlobals;
37   import com.instantbank.common.utilcomponents.JNDINames;
38   import com.instantbank.common.utilcomponents.CommonUtil;
39   
40   
41   /**
42    *  Servlet acting as a controller in order to ask ejb services for preview
43    *  of a template or a component for a specified loan (used by several usecases).
44    *
45    * @author InstantBank (Consuelo Franky, Rodrigo Lopez)
46    * @created August 2002
47    */
48   public class PdfShowServlet extends HttpServlet {
49     /**
50      *  Home of ejb that provides the services for this servlet.
51      */
52     private LetterTemplateHome lethome = null;
53   
54     /**
55      *  The ejb that provides the services for this servlet.
56      */
57     private LetterTemplate letejb = null;
58   
59     /**
60      * for debugging
61      */
62     private Debug debug = null;
63   
64   
65     /**
66      *  init of servlet: obtains home ejb reference
67      *
68      * @exception ServletException
69      */
70     public void init() throws ServletException {
71       debug = new Debug();
72       debug.setDebugginOn(true);
73       debug.setPreMessage("** PdfShowServlet: ");
74   
75       //obtain LetterTemplateHome reference:
76       try {
77         // Contact the LetterTemplateHome through JNDI.
78         InitialContext ctx = new InitialContext();
79         lethome = (LetterTemplateHome)ctx.lookup
80           (JNDINames.LETTERTEMPLATE_EJBHOME);
81       }
82       catch(Exception e) {
83         e.printStackTrace();
84         debug.println("Problem instantiating LetterTemplate EJB:"
85           + e.toString());
86         throw new ServletException
87           (LetterTemplateExceptionMessage.PROBLEM_INSTANTIATING_LETTERS_EJB
88           + e.getMessage());
89       }
90     }
91   
92   
93     /**
94      *  Gets the bytes of a dummy letter pdf generated for a template, through
95      *  an ejb service and sends the bytes to the browser
96      *
97      * @param request HTTP request
98      * @param response HTTP response
99      * @exception ServletException
100     * @exception IOException
101     */
102    public void doGet(HttpServletRequest request, HttpServletResponse response)
103       throws ServletException, IOException {
104      HttpSession session = request.getSession();
105      debug.println("new request=========================");
106  
107      if(CommonUtil.controlTimeout(request, response,
108        getServletConfig().getServletContext())) {
109        debug.println("invalidate session and return by timeout");
110        session.invalidate();
111        return;
112        // here there is a forward to /control_web/TimeOutPageOff.jsp
113        // prepared by controlTimeout()
114      }
115  
116      String viewType = request.getParameter("viewableType");
117      String strViewCode = request.getParameter("viewableCode");
118      long viewableCode = Long.parseLong(strViewCode);
119      long loanCode = LetterTemplateGlobals.DUMMY_LOAN;
120      String strLoanCode = request.getParameter("loanCode");
121      if(!strLoanCode.equals("DUMMY")) {
122        loanCode = Long.parseLong(strLoanCode);
123      }
124      TemplateTransformer transf;
125      ServletOutputStream out = null;
126      try {
127        out = response.getOutputStream();
128  
129        // gets variables of web session:
130        String temporalPath = (String)request.getSession()
131          .getAttribute(WebKeys.ImagesTemporalPath);
132        /*String rtf2foConfDir = (String) request.getSession()
133                                        .getAttribute(WebKeys.RtfToFoConfigPath);
134              */
135        // gets LetterTemplate ejb instance reference:
136        letejb = (LetterTemplate)request.getSession()
137          .getAttribute(WebKeys.LetterTemplateEJB);
138  
139        if(letejb == null) {
140          debug.println("creating reference to LetterTemplate EJB");
141          String companyId = (String)request.getSession()
142            .getAttribute(WebKeys.CompanyId);
143          Long userId = (Long)request.getSession()
144            .getAttribute(WebKeys.UserId);
145          letejb = lethome.create(companyId, userId);
146          request.getSession().setAttribute
147            (WebKeys.LetterTemplateEJB, letejb);
148        }
149  
150        // gets the viewable instance through an ejb service:
151        LetterViewable viewable;
152  
153        if(viewType.equals("TEMPLATE")) {
154          viewable = letejb.loadTemplate(viewableCode);
155        }
156        else {
157          viewable = letejb.loadComponent(viewableCode);
158        }
159  
160        if(viewable == null) {
161          throw new Exception
162            (LetterTemplateExceptionMessage.DOCUMENT_NULL);
163        }
164  
165        String foTemplate = viewable.toFoTemplate();
166  
167        if(foTemplate == null) {
168          throw new Exception(LetterTemplateExceptionMessage.PROBLEMS_CALCULATING_FO_TEMPLATE);
169        }
170  
171        ArrayList[] viewImages = viewable.getAllImages();
172        ArrayList[] setOfVars = viewable.setOfVariables();
173        String foFileName = viewable.getName() + new Date().getTime();
174  
175        // instantiates a TemplateTransformer for generating the viewable's
176        // pdf or txt:
177        transf = new TemplateTransformer(temporalPath, foTemplate,
178          viewImages, setOfVars, foFileName, letejb);
179  
180        Set inconsistentVars = transf.offsetConsistency();
181        if(!inconsistentVars.isEmpty()) {
182          String type = "template";
183          if(!viewType.equals("TEMPLATE")) {
184            type = "component";
185          }
186          String msg = "There are date offset inconsistencies in this " +
187            type + ". Please, check with the template editor " +
188            "or with the system administrator.";
189          response.setContentType("text/html");
190          out.println("<H3>WARNING: " + msg + "</H3>");
191          return;
192        }
193  
194        if(viewable.getPrintType() == Template.TYPEWRITTER) {
195          transf.setRenderMode(TemplateTransformer.RENDER_TXT);
196        }
197  
198        //Calculates the value of the variables required by the fo-template.
199        //It uses the answer of ejb service: generatePreviewTemplate():
200        //    ArrayList of one tuple that is an Object[] of Strings;
201        //    each String is the value of a variable for the chosen loan
202        ArrayList varValues = null;
203        if(viewable.hasVariables()) {
204          varValues =
205            letejb.generatePreviewTemplate
206            (viewType.equals("TEMPLATE") ? viewable.getCode() :
207            LetterTemplateGlobals.UNDEF,
208            loanCode,
209            TemplateTransformer.varCodesFromSet(setOfVars));
210        }
211  
212        //debug
213        TemplateTransformer.printSetOfVars(setOfVars);
214        if(varValues != null) {
215          TemplateTransformer.printRawVars(
216            TemplateTransformer.varCodesFromSet(setOfVars),
217            (String[])varValues.get(0));
218        }
219  
220        // generates the document corresponding to the current viewable,
221        // with variables taken from  loanCode:
222        ByteArrayOutputStream letter =
223          transf.transform(varValues == null ?
224          new String[0] :
225          (String[])varValues.get(0));
226  
227        if(letter == null) {
228          throw new Exception("It is impossible the preview of Template, "
229            + "because of problems generating the final document");
230        }
231  
232        // Shows the viewable's preview:
233  
234        byte[] letterBytes = letter.toByteArray();
235        if(viewable.getPrintType() == Template.TYPEWRITTER) {
236          // sends bytes directly to the browser:
237          response.setContentType("text/plain");
238          response.setContentLength(letterBytes.length);
239          out.write(letterBytes, 0, letterBytes.length);
240          out.flush();
241        }
242        else {
243          response.setContentType("application/pdf");
244          response.setContentLength(letterBytes.length);
245          out.write(letterBytes, 0, letterBytes.length);
246          out.flush();
247        }
248  
249        //Erase temporary files (not the pdf file).
250        transf.cleanfiles();
251  
252      }
253      catch(Exception ex) {
254        debug.println(CommonUtil.stackTraceToString(ex));
255        response.setContentType("text/html");
256        out.println("<H3>EXCEPTION: " + ex.getMessage() + "</H3>");
257      }
258    }
259  
260  
261    /**
262     *  doPost has the same effect than doGet
263     *
264     * @param request HTTP request
265     * @param response DHTTP response
266     * @exception ServletException
267     * @exception IOException
268     */
269    public void doPost(HttpServletRequest request, HttpServletResponse response)
270       throws ServletException, IOException {
271      doGet(request, response);
272    }
273  
274  }
275