KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openbravo > base > secureApp > HttpSecureAppServlet


1 /*
2  ************************************************************************************
3  * Copyright (C) 2001-2006 Openbravo S.L.
4  * Licensed under the Apache Software License version 2.0
5  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6  * Unless required by applicable law or agreed to in writing, software distributed
7  * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
8  * CONDITIONS OF ANY KIND, either express or implied. See the License for the
9  * specific language governing permissions and limitations under the License.
10  ************************************************************************************
11 */

12 package org.openbravo.base.secureApp;
13
14 import org.openbravo.base.HttpBaseServlet;
15 import org.openbravo.base.HttpBaseUtils;
16 import org.openbravo.xmlEngine.XmlDocument;
17 import org.openbravo.erpCommon.utility.*;
18 import org.openbravo.erpCommon.ad_background.*;
19 import org.openbravo.utils.Replace;
20
21 import java.io.*;
22 import javax.servlet.*;
23 import javax.servlet.http.*;
24 import java.util.*;
25 import java.sql.Connection JavaDoc;
26 import org.openbravo.authentication.AuthenticationException;
27 import org.openbravo.authentication.AuthenticationManager;
28 import org.openbravo.authentication.basic.DefaultAuthenticationManager;
29 import org.openbravo.erpCommon.security.SessionLogin;
30 import org.openbravo.erpCommon.security.SessionLoginData;
31 import org.openbravo.data.FieldProvider;
32
33 import net.sf.jasperreports.engine.*;
34 import net.sf.jasperreports.engine.design.JasperDesign;
35 import net.sf.jasperreports.engine.export.JExcelApiExporter;
36 import net.sf.jasperreports.engine.export.JRHtmlExporter;
37 import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
38 import net.sf.jasperreports.engine.export.JRCsvExporter;
39 import net.sf.jasperreports.engine.xml.JRXmlLoader;
40 import net.sf.jasperreports.engine.export.JExcelApiExporterParameter;
41
42 public class HttpSecureAppServlet extends HttpBaseServlet{
43   public boolean boolHist = true;
44   String JavaDoc strServletIdentificacion;
45   String JavaDoc strServletSinIdentificar;
46   public String JavaDoc strServletGoBack;
47   public String JavaDoc strFTPDirectory;
48   public String JavaDoc strPeriodicBackgroundTime;
49   public String JavaDoc strLogFileAcctServer;
50   public ClassInfoData classInfo;
51   protected AuthenticationManager m_AuthManager = null;
52
53   String JavaDoc servletClass = this.getClass().getName();
54   protected static Hashtable<String JavaDoc, PeriodicBackground> backgroundProcess;
55
56   public class Variables extends VariablesHistory {
57     public Variables(HttpServletRequest request) {
58       super(request);
59     }
60
61     public void updateHistory(HttpServletRequest request) {
62       if (boolHist) {
63         String JavaDoc sufix = getCurrentHistoryIndex();
64         if (!(servletClass.equals(getSessionValue("reqHistory.servlet" + sufix,"")))) {
65           upCurrentHistoryIndex();
66           sufix = getCurrentHistoryIndex();
67           setSessionValue("reqHistory.servlet" + sufix, servletClass);
68           setSessionValue("reqHistory.path" + sufix, request.getServletPath());
69           setSessionValue("reqHistory.command" + sufix, "DEFAULT");
70         }
71       }
72     }
73     public void setHistoryCommand(String JavaDoc strCommand) {
74       String JavaDoc sufix = getCurrentHistoryIndex();
75       setSessionValue("reqHistory.command" + sufix, strCommand);
76     }
77   }
78
79   public void init (ServletConfig config) {
80     super.init(config);
81
82     // Authentication manager load
83
String JavaDoc sAuthManagerClass = config.getServletContext().getInitParameter("AuthenticationManager");
84     if (sAuthManagerClass == null || sAuthManagerClass.equals("")) {
85         // If not defined, load default
86
sAuthManagerClass = "org.openbravo.authentication.basic.DefaultAuthenticationManager";
87     }
88     
89     try {
90         m_AuthManager = (AuthenticationManager) Class.forName(sAuthManagerClass).newInstance();
91     } catch (Exception JavaDoc e) {
92         log4j.error("Authentication manager not defined", e);
93         m_AuthManager = new DefaultAuthenticationManager();
94     }
95     strServletIdentificacion = config.getServletContext().getInitParameter("LoginServlet");
96     strServletSinIdentificar = config.getServletContext().getInitParameter("ServletSinIdentificar");
97     if (log4j.isDebugEnabled()) log4j.debug("strdireccion: " + strDireccion);
98     strServletGoBack = config.getServletContext().getInitParameter("ServletGoBack");
99     strFTPDirectory = config.getServletContext().getInitParameter("AttachmentDirectory");
100     strFTPDirectory = strFTPDirectory.replace("@actual_path_context@", prefix);
101     try {
102       File f = new File(strFTPDirectory);
103       if (!f.exists()) f.mkdir();
104     } catch (Exception JavaDoc e) {
105       e.printStackTrace();
106     }
107     if (log4j.isDebugEnabled()) log4j.debug("strServletGoBack: " + strServletGoBack);
108     strPeriodicBackgroundTime = config.getServletContext().getInitParameter("PeriodicBackgroundTime");
109     strLogFileAcctServer = config.getServletContext().getInitParameter("LogFileAcctServer");
110     strLogFileAcctServer = prefix + "/" + strBaseConfigPath + "/" + strLogFileAcctServer;
111     if (backgroundProcess == null && strPeriodicBackgroundTime!=null && !strPeriodicBackgroundTime.equals("") && strLogFileAcctServer!=null && !strLogFileAcctServer.equals("")) {
112       backgroundProcess = new Hashtable<String JavaDoc, PeriodicBackground>();
113       SystemPreferencesData[] backgroundData = null;
114       try {
115         backgroundData = SystemPreferencesData.selectBackground(this);
116       } catch (ServletException sex) {
117         sex.printStackTrace();
118       }
119       if (backgroundData!=null && backgroundData.length>0) {
120         for (int countBack = 0;countBack<backgroundData.length;countBack++) {
121           PeriodicBackground object = null;
122           try {
123           object = new PeriodicBackground(this, Long.parseLong(strPeriodicBackgroundTime), strLogFileAcctServer, backgroundData[countBack].id, backgroundData[countBack].classname);
124           } catch (IOException ioe) {
125             ioe.printStackTrace();
126           }
127           if (object!=null) {
128             object.start();
129             backgroundProcess.put(backgroundData[countBack].id, object);
130           }
131         }
132       }
133     }
134   }
135
136   public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
137     String JavaDoc strDireccionLocal = HttpBaseUtils.getLocalAddress(request);
138     Variables variables = new Variables(request);
139     
140     try {
141       if (log4j.isDebugEnabled()) log4j.debug("Servlet request for class info: " + request.getServletPath());
142       ClassInfoData[] classInfoAux = ClassInfoData.select(this, variables.getLanguage(), request.getServletPath());
143       if (classInfoAux!=null && classInfoAux.length>0) classInfo = classInfoAux[0];
144       else {
145         classInfoAux = ClassInfoData.set();
146         classInfo = classInfoAux[0];
147       }
148     } catch (Exception JavaDoc ex) {
149       ex.printStackTrace();
150       ClassInfoData[] classInfoAux = ClassInfoData.set();
151       classInfo = classInfoAux[0];
152     }
153     
154     if (log4j.isDebugEnabled()) log4j.debug("class info type: " + classInfo.type + " - ID: " + classInfo.id + " - NAME: " + classInfo.name);
155     String JavaDoc strAjax = "";
156     String JavaDoc strHidden = "";
157     try {
158       strAjax = request.getParameter("IsAjaxCall");
159     } catch (Exception JavaDoc ignored) {}
160     try {
161       strHidden = request.getParameter("IsHiddenCall");
162     } catch (Exception JavaDoc ignored) {}
163     
164     try {
165       String JavaDoc strUserAuth = m_AuthManager.authenticate(request);
166       if (strUserAuth == null) {
167         String JavaDoc strTarget = request.getRequestURL().toString();
168         if (!strTarget.endsWith("/security/Menu.html")) {
169           variables.setSessionValue("targetmenu", strTarget);
170         }
171         variables.setSessionValue("target", strDireccionLocal + "/security/Menu.html");
172         if (strAjax!=null && !strAjax.equals("")) bdErrorAjax(response, "Error", "", Utility.messageBD(this, "NotLogged", variables.getLanguage()));
173         else response.sendRedirect(strDireccionLocal + strServletSinIdentificar);
174         return;
175       }
176       if (variables.getRole().equals("") || !SeguridadData.loggedOK(this, variables.getDBSession())) {
177         // Read default options
178
DefaultOptionsData options = readDefaultOptions(strUserAuth);
179         if (options == null ) {
180           // Relogin
181
log4j.error("Unable to read default options for: " + strUserAuth);
182           logout(request, response);
183           return;
184         } else {
185           VariablesSecureApp vars = new VariablesSecureApp(request);
186           String JavaDoc strLanguage = options.defaultAdLanguage; // "es_ES"; //variables.getRequiredStringParameter("language");
187
String JavaDoc strRol = options.defaultAdRoleId; // optionsvars.getRequiredStringParameter("role"); // Hardcoded in the login page
188
String JavaDoc strCliente = options.defaultAdClientId; // variables.getRequiredStringParameter("client"); // Hardcoded in the login page
189
String JavaDoc strOrg = options.defaultAdOrgId; // variables.getRequiredStringParameter("org"); // Hardcoded in the login page
190
String JavaDoc strAlmacen = options.defaultMWarehouseId; // ""; // Main Warehouse //variables.getStringParameter("warehouse");
191

192           if (LoginUtils.fillSessionArguments(this, vars, strUserAuth, strLanguage, strRol, strCliente, strOrg, strAlmacen)) {
193             readProperties(vars, prefix + strBaseConfigPath + "/Openbravo.properties");
194             saveLoginBD(request, vars, strCliente, strOrg);
195           } else {
196             // Relogin
197
log4j.error("Unable to fill session Arguments for: " + strUserAuth);
198             logout(request, response);
199             return;
200           }
201         }
202       } else variables.updateHistory(request);
203       log4j.info("Call to HttpBaseServlet.service");
204     } catch (AuthenticationException e) {
205       // Relogin
206
log4j.error(e);
207       logout(request, response);
208       return;
209     }
210     try {
211       super.service(request,response);
212     } catch (ServletException ex) {
213       log4j.error("Error captured: " + ex);
214       ex.printStackTrace();
215       OBError myError = Utility.translateError(this, null, variables.getLanguage(), ex.getMessage());
216       if (strAjax!=null && !strAjax.equals("")) bdErrorAjax(response, myError.getType(), myError.getTitle(), myError.getMessage());
217       else if (strHidden!=null && !strHidden.equals("")) bdErrorHidden(response, myError.getType(), myError.getTitle(), myError.getMessage());
218       else if (!myError.isConnectionAvailable()) bdErrorConnection(response);
219       else bdErrorGeneral(response, myError.getTitle(), myError.getMessage());
220     } catch (Exception JavaDoc e) {
221       log4j.error("Error captured: " + e);
222       e.printStackTrace();
223       bdErrorGeneral(response, "Error", e.toString());
224     }
225   }
226
227   public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
228     VariablesSecureApp vars = new VariablesSecureApp(request);
229
230     vars.clearSession(true);
231     if (log4j.isDebugEnabled()) log4j.debug("Cerrando session");
232     if (!vars.getDBSession().equals("")) SessionLoginData.saveProcessed(this, vars.getUser(), vars.getDBSession());
233     
234     m_AuthManager.logout(request, response);
235   }
236
237   public void setHistoryCommand(HttpServletRequest request, String JavaDoc strCommand) {
238     Variables vars = new Variables(request);
239     vars.setHistoryCommand(strCommand);
240   }
241
242   public void advise(HttpServletResponse response, String JavaDoc strTitulo, String JavaDoc strTexto) throws IOException {
243     XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/Advise").createXmlDocument();
244
245     xmlDocument.setParameter("ParamTitulo", strTitulo);
246     xmlDocument.setParameter("ParamTexto", strTexto);
247     response.setContentType("text/html; charset=UTF-8");
248     PrintWriter out = response.getWriter();
249     out.println(xmlDocument.print());
250     out.close();
251   }
252
253  public void advisePopUp(HttpServletResponse response, String JavaDoc strTitulo, String JavaDoc strTexto) throws IOException {
254     advisePopUp(response, "Error", strTitulo, strTexto);
255   }
256
257   public void advisePopUp(HttpServletResponse response, String JavaDoc strTipo, String JavaDoc strTitulo, String JavaDoc strTexto) throws IOException {
258     XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/AdvisePopUp").createXmlDocument();
259
260     xmlDocument.setParameter("ParamTipo", strTipo.toUpperCase());
261     xmlDocument.setParameter("ParamTitulo", strTitulo);
262     xmlDocument.setParameter("ParamTexto", strTexto);
263     response.setContentType("text/html; charset=UTF-8");
264     PrintWriter out = response.getWriter();
265     out.println(xmlDocument.print());
266     out.close();
267   }
268
269   public void bdError(HttpServletResponse response, String JavaDoc strCode, String JavaDoc strLanguage) throws IOException {
270     XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/Error").createXmlDocument();
271
272     //xmlDocument.setParameter("theme", vars.getTheme());
273
xmlDocument.setParameter("ParamTitulo", strCode);
274     xmlDocument.setParameter("ParamTexto", Utility.messageBD(this, strCode, strLanguage));
275     response.setContentType("text/html; charset=UTF-8");
276     PrintWriter out = response.getWriter();
277     out.println(xmlDocument.print());
278     out.close();
279   }
280
281   public void bdErrorGeneral(HttpServletResponse response, String JavaDoc strTitle, String JavaDoc strText) throws IOException {
282     XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/Error").createXmlDocument();
283
284     xmlDocument.setParameter("ParamTitulo", strTitle);
285     xmlDocument.setParameter("ParamTexto", strText);
286     response.setContentType("text/html; charset=UTF-8");
287     PrintWriter out = response.getWriter();
288     out.println(xmlDocument.print());
289     out.close();
290   }
291
292   public void bdErrorConnection(HttpServletResponse response) throws IOException {
293     if (log4j.isDebugEnabled()) log4j.debug("Output: Error connection");
294     XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/ErrorConnection").createXmlDocument();
295
296     response.setContentType("text/html; charset=UTF-8");
297     PrintWriter out = response.getWriter();
298     out.println(xmlDocument.print());
299     out.close();
300   }
301
302   public void bdErrorAjax(HttpServletResponse response, String JavaDoc strType, String JavaDoc strTitle, String JavaDoc strText) throws IOException {
303     response.setContentType("text/xml; charset=UTF-8");
304     PrintWriter out = response.getWriter();
305     out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
306     out.println("<xml-structure>\n");
307     out.println(" <status>\n");
308     out.println(" <type>" + strType + "</type>\n");
309     out.println(" <title>" + strTitle + "</title>\n");
310     out.println(" <description><![CDATA[" + strText + "]]></description>\n");
311     out.println(" </status>\n");
312     out.println("</xml-structure>\n");
313     out.close();
314   }
315
316   public void bdErrorHidden(HttpServletResponse response, String JavaDoc strType, String JavaDoc strTitle, String JavaDoc strText) throws IOException {
317     XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/erpCommon/ad_callouts/CallOut").createXmlDocument();
318
319     StringBuffer JavaDoc resultado = new StringBuffer JavaDoc();
320     resultado.append("var calloutName='';\n\n");
321     resultado.append("var respuesta = new Array(\n");
322
323     resultado.append("new Array(\"MESSAGE\", \"");
324     resultado.append(strText);
325     resultado.append("\")");
326     resultado.append("\n);");
327
328     xmlDocument.setParameter("array", resultado.toString());
329     response.setContentType("text/html; charset=UTF-8");
330     PrintWriter out = response.getWriter();
331     out.println(xmlDocument.print());
332     out.close();
333   }
334
335   public void pageError(HttpServletResponse response) throws IOException {
336     XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/HtmlError").createXmlDocument();
337
338     response.setContentType("text/html; charset=UTF-8");
339     PrintWriter out = response.getWriter();
340     out.println(xmlDocument.print());
341     out.close();
342   }
343
344   public void pageErrorPopUp(HttpServletResponse response) throws IOException {
345     XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/HtmlErrorPopUp").createXmlDocument();
346
347     response.setContentType("text/html; charset=UTF-8");
348     PrintWriter out = response.getWriter();
349     out.println(xmlDocument.print());
350     out.close();
351   }
352
353   public void whitePage(HttpServletResponse response) throws IOException {
354     whitePage(response, "");
355   }
356
357   public void whitePage(HttpServletResponse response, String JavaDoc strAlert) throws IOException {
358     XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/HtmlWhitePage").createXmlDocument();
359     if (strAlert==null) strAlert="";
360     xmlDocument.setParameter("body", strAlert);
361
362     response.setContentType("text/html; charset=UTF-8");
363     PrintWriter out = response.getWriter();
364     out.println(xmlDocument.print());
365     out.close();
366   }
367
368   public void printPageClosePopUp(HttpServletResponse response, VariablesSecureApp vars, String JavaDoc path) throws IOException, ServletException {
369     if (log4j.isDebugEnabled()) log4j.debug("Output: PopUp Response");
370     XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/PopUp_Response").createXmlDocument();
371     xmlDocument.setParameter("language", "LNG_POR_DEFECTO=\"" + vars.getLanguage() + "\";");
372     xmlDocument.setParameter("href", path.equals("")?"null":"'" + path + "'");
373     response.setContentType("text/html; charset=UTF-8");
374     PrintWriter out = response.getWriter();
375     out.println(xmlDocument.print());
376     out.close();
377   }
378
379   public void printPageClosePopUp(HttpServletResponse response, VariablesSecureApp vars) throws IOException, ServletException {
380     printPageClosePopUp(response, vars, "");
381   }
382
383   public void printPageClosePopUpWindow(HttpServletResponse response, VariablesSecureApp vars) throws IOException, ServletException {
384     if (log4j.isDebugEnabled()) log4j.debug("Output: PopUp Response");
385     XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/PopUp_Close").createXmlDocument();
386     xmlDocument.setParameter("language", "LNG_POR_DEFECTO=\"" + vars.getLanguage() + "\";");
387     response.setContentType("text/html; charset=UTF-8");
388     PrintWriter out = response.getWriter();
389     out.println(xmlDocument.print());
390     out.close();
391   }
392
393   public void pageErrorCallOut(HttpServletResponse response) throws IOException {
394     XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/HtmlErrorCallOut").createXmlDocument();
395
396     response.setContentType("text/html; charset=UTF-8");
397     PrintWriter out = response.getWriter();
398     out.println(xmlDocument.print());
399     out.close();
400   }
401
402   public PeriodicBackground getBackgroundProcess(String JavaDoc id) {
403     if (backgroundProcess == null || backgroundProcess.isEmpty()) return null;
404     PeriodicBackground bg = backgroundProcess.get(id);
405     return bg;
406   }
407   public void updateBackgroundProcess(String JavaDoc id, PeriodicBackground object) {
408     if (backgroundProcess == null) backgroundProcess = new Hashtable<String JavaDoc, PeriodicBackground>();
409     backgroundProcess.remove(id);
410     backgroundProcess.put(id, object);
411   }
412
413   private void readProperties(VariablesSecureApp vars, String JavaDoc strFileProperties) {
414     // Read properties file.
415
Properties properties = new Properties();
416     try {
417       log4j.info("strFileProperties: " + strFileProperties);
418       properties.load(new FileInputStream(strFileProperties));
419       String JavaDoc javaDateFormat = properties.getProperty("dateFormat.java");
420       log4j.info("javaDateFormat: " + javaDateFormat);
421       vars.setSessionValue("#AD_JavaDateFormat", javaDateFormat);
422       String JavaDoc javaDateTimeFormat = properties.getProperty("dateTimeFormat.java");
423       log4j.info("javaDateTimeFormat: " + javaDateTimeFormat);
424       vars.setSessionValue("#AD_JavaDateTimeFormat", javaDateTimeFormat);
425       String JavaDoc jsDateFormat = properties.getProperty("dateFormat.js");
426       log4j.info("jsDateFormat: " + jsDateFormat);
427       vars.setSessionValue("#AD_JsDateFormat", jsDateFormat);
428       String JavaDoc sqlDateFormat = properties.getProperty("dateFormat.sql");
429       log4j.info("sqlDateFormat: " + sqlDateFormat);
430       vars.setSessionValue("#AD_SqlDateFormat", sqlDateFormat);
431     } catch (IOException e) {
432      // catch possible io errors from readLine()
433
System.out.println("Uh oh, got an IOException error!");
434      e.printStackTrace();
435     }
436   }
437
438   private DefaultOptionsData readDefaultOptions(String JavaDoc strUser) throws ServletException {
439     DefaultOptionsData[] options = DefaultOptionsData.getDefaultOptions(this, strUser);
440     if (options == null || options.length == 0) {
441       return null;
442     } else {
443       return options[0];
444     }
445   }
446
447   private void saveLoginBD(HttpServletRequest request, VariablesSecureApp vars, String JavaDoc strCliente, String JavaDoc strOrganizacion) throws ServletException {
448     SessionLogin sl = new SessionLogin(request, strCliente, strOrganizacion, vars.getSessionValue("#AD_User_ID"));
449     sl.save(this);
450     vars.setSessionValue("#AD_Session_ID", sl.getSessionID());
451   }
452
453   public void renderJR(VariablesSecureApp variables, HttpServletResponse response, String JavaDoc strReportName, String JavaDoc strOutputType, HashMap<String JavaDoc, Object JavaDoc> designParameters, FieldProvider[] data, Map<Object JavaDoc, Object JavaDoc> exportParameters) throws ServletException{
454   
455     if (strReportName == null || strReportName.equals("")) strReportName = PrintJRData.getReportName(this, classInfo.id);
456
457     String JavaDoc strAttach = strFTPDirectory + "/284-" +classInfo.id;
458     
459     String JavaDoc strLanguage = variables.getLanguage();
460     if (strBaseDesignPath.endsWith("/")) strDefaultDesignPath = strDefaultDesignPath.substring(0, strDefaultDesignPath.length()-1);
461     String JavaDoc strNewAddBase = strDefaultDesignPath;
462     String JavaDoc strFinal = strBaseDesignPath;
463     if (!strLanguage.equals("") && !strLanguage.equals("en_US")) strNewAddBase = strLanguage;
464     if (!strFinal.endsWith("/" + strNewAddBase)) strFinal += "/" + strNewAddBase;
465     String JavaDoc strBaseDesign = prefix + "/" + strFinal;
466     
467     strReportName = Replace.replace(Replace.replace(strReportName,"@basedesign@",strBaseDesign),"@attach@",strAttach);
468     String JavaDoc strFileName = strReportName.substring(strReportName.lastIndexOf("/")+1);
469     response.setHeader( "Content-disposition","inline; filename=" + strFileName + "." +strOutputType);
470      
471     ServletOutputStream os = null;
472     try {
473       JasperDesign jasperDesign= JRXmlLoader.load(strReportName);
474       JasperReport jasperReport= JasperCompileManager.compileReport(jasperDesign);
475       if (designParameters == null) designParameters = new HashMap<String JavaDoc, Object JavaDoc>();
476
477       Boolean JavaDoc pagination = true;
478       if (strOutputType.equals("pdf")) pagination = false;
479
480       designParameters.put("IS_IGNORE_PAGINATION", pagination );
481       designParameters.put("BASE_WEB", strReplaceWithFull );
482       designParameters.put("BASE_DESIGN", strBaseDesign);
483       designParameters.put("ATTACH", strAttach);
484       designParameters.put("USER_CLIENT", Utility.getContext(this, variables, "#User_Client", ""));
485       designParameters.put("USER_ORG", Utility.getContext(this, variables, "#User_Org", ""));
486       designParameters.put("LANGUAGE", strLanguage);
487
488       if (log4j.isDebugEnabled()) log4j.debug("creating the format factory: " + variables.getJavaDateFormat());
489       JRFormatFactory jrFormatFactory = new JRFormatFactory();
490       jrFormatFactory.setDatePattern(variables.getJavaDateFormat());
491       designParameters.put(JRParameter.REPORT_FORMAT_FACTORY, jrFormatFactory);
492
493       JasperPrint jasperPrint;
494       if (data != null) jasperPrint = JasperFillManager.fillReport(jasperReport, designParameters, new JRFieldProviderDataSource(data, variables.getJavaDateFormat()));
495       else {
496         Connection JavaDoc con = null;
497         try {
498           con = getTransactionConnection();
499           jasperPrint = JasperFillManager.fillReport(jasperReport, designParameters, con);
500         } catch (Exception JavaDoc e){
501           throw new ServletException(e.getMessage());
502         } finally {
503           releaseRollbackConnection(con);
504         }
505       }
506
507       os = response.getOutputStream();
508       if (exportParameters == null) exportParameters = new HashMap<Object JavaDoc, Object JavaDoc>();
509       if (strOutputType == null || strOutputType.equals("")) strOutputType = "html";
510       if (strOutputType.equals("html")){
511         if (log4j.isDebugEnabled()) log4j.debug("JR: Print HTML");
512         JRHtmlExporter exporter = new JRHtmlExporter();
513         exportParameters.put(JRHtmlExporterParameter.JASPER_PRINT, jasperPrint);
514         exportParameters.put(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
515         exportParameters.put(JRHtmlExporterParameter.OUTPUT_STREAM, os);
516         exporter.setParameters(exportParameters);
517         exporter.exportReport();
518       } else if (strOutputType.equals("pdf")){
519         response.setContentType("application/pdf");
520         JasperExportManager.exportReportToPdfStream(jasperPrint, os);
521       } else if (strOutputType.equals("xls")){
522         response.setContentType("application/vnd.ms-excel");
523         JExcelApiExporter exporter = new JExcelApiExporter();
524         Map<Object JavaDoc, Object JavaDoc> p = new HashMap<Object JavaDoc, Object JavaDoc>();
525         exportParameters.put(JRExporterParameter.JASPER_PRINT, jasperPrint);
526         exportParameters.put(JRExporterParameter.OUTPUT_STREAM, os);
527         exportParameters.put(JExcelApiExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
528         exportParameters.put(JExcelApiExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
529     
530         exporter.setParameters(exportParameters);
531         exporter.exportReport();
532       
533       } else {
534         throw new ServletException("Output format no supported");
535       }
536     } catch (JRException e) {
537       if (log4j.isDebugEnabled()) log4j.debug("JR: Error: " + e);
538       e.printStackTrace();
539       throw new ServletException(e.getMessage());
540     } catch (Exception JavaDoc e) {
541       throw new ServletException(e.getMessage());
542     } finally {
543       try {
544         os.close();
545       } catch (Exception JavaDoc e) { }
546     }
547   }
548
549   public String JavaDoc getServletInfo() {
550     return "This servlet add some functions (autentication, privileges, application menu, ...) over HttpBaseServlet";
551   }
552 }
553
Popular Tags