f3aad70f7c63b8e30399d346d16d3955c930d6d8
[portal/sdk.git] /
1 /*
2  * ============LICENSE_START==========================================
3  * ONAP Portal SDK
4  * =================================================================== 
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0 
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38
39 /* ===========================================================================================
40  * This class is part of <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I> 
41  * Raptor : This tool is used to generate different kinds of reports with lot of utilities
42  * ===========================================================================================
43  *
44  * -------------------------------------------------------------------------------------------
45  * PdfReportHandler.java - This class is used to generate reports in PDF using iText 
46  * -------------------------------------------------------------------------------------------
47  *
48  *
49  * Changes
50  * -------
51  * 14-Jul-2009 : Version 8.4 (Sundar); <UL> 
52  *                                     <LI> Dashboard reports can be downloaded with each report occupying separate page including its charts. </LI>
53  *                                     </UL>   
54  *
55  */
56 package org.onap.portalsdk.analytics.model.pdf;
57
58 import com.lowagie.text.BadElementException;
59 import com.lowagie.text.Chunk;
60 import com.lowagie.text.Document;
61 import com.lowagie.text.DocumentException;
62 import com.lowagie.text.Element;
63 import com.lowagie.text.ElementTags;
64 import com.lowagie.text.Font;
65 import com.lowagie.text.FontFactory;
66 import com.lowagie.text.Image;
67 import com.lowagie.text.PageSize;
68 import com.lowagie.text.Paragraph;
69 import com.lowagie.text.Phrase;
70 import com.lowagie.text.Rectangle;
71 import com.lowagie.text.html.simpleparser.HTMLWorker;
72 import com.lowagie.text.html.simpleparser.StyleSheet;
73 import com.lowagie.text.pdf.PdfPCell;
74 import com.lowagie.text.pdf.PdfPTable;
75 import com.lowagie.text.pdf.PdfWriter;
76 import java.awt.Color;
77 import java.io.File;
78 import java.io.FileNotFoundException;
79 import java.io.IOException;
80 import java.io.OutputStream;
81 import java.io.StringReader;
82 import java.net.MalformedURLException;
83 import java.sql.Connection;
84 import java.sql.ResultSet;
85 import java.sql.ResultSetMetaData;
86 import java.sql.SQLException;
87 import java.sql.Statement;
88 import java.text.SimpleDateFormat;
89 import java.util.ArrayList;
90 import java.util.Calendar;
91 import java.util.Date;
92 import java.util.HashMap;
93 import java.util.Iterator;
94 import java.util.List;
95 import java.util.Map;
96 import java.util.Map.Entry;
97 import java.util.Set;
98 import java.util.TimeZone;
99 import java.util.TreeMap;
100 import java.util.Vector;
101 import javax.servlet.http.HttpServletRequest;
102 import javax.servlet.http.HttpServletResponse;
103 import javax.servlet.http.HttpSession;
104 import org.onap.portalsdk.analytics.error.RaptorException;
105 import org.onap.portalsdk.analytics.error.ReportSQLException;
106 import org.onap.portalsdk.analytics.model.ReportHandler;
107 import org.onap.portalsdk.analytics.model.ReportLoader;
108 import org.onap.portalsdk.analytics.model.base.IdNameValue;
109 import org.onap.portalsdk.analytics.model.definition.ReportDefinition;
110 import org.onap.portalsdk.analytics.model.runtime.ReportRuntime;
111 import org.onap.portalsdk.analytics.system.AppUtils;
112 import org.onap.portalsdk.analytics.system.ConnectionUtils;
113 import org.onap.portalsdk.analytics.system.Globals;
114 import org.onap.portalsdk.analytics.util.AppConstants;
115 import org.onap.portalsdk.analytics.util.DataSet;
116 import org.onap.portalsdk.analytics.util.HtmlStripper;
117 import org.onap.portalsdk.analytics.util.Utils;
118 import org.onap.portalsdk.analytics.view.ColumnHeader;
119 import org.onap.portalsdk.analytics.view.ColumnHeaderRow;
120 import org.onap.portalsdk.analytics.view.DataRow;
121 import org.onap.portalsdk.analytics.view.DataValue;
122 import org.onap.portalsdk.analytics.view.HtmlFormatter;
123 import org.onap.portalsdk.analytics.view.ReportData;
124 import org.onap.portalsdk.analytics.view.RowHeader;
125 import org.onap.portalsdk.analytics.view.RowHeaderCol;
126 import org.onap.portalsdk.analytics.xmlobj.DataColumnType;
127 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; 
128
129 /**
130  * @author mwliu and sundar
131  *
132  */
133 public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{
134
135         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PdfReportHandler.class);
136
137         private PdfBean pb;
138         private HtmlStripper strip = new HtmlStripper();
139         private static final int RetryCreateNewImage = 3;
140         private int retryCreateNewImageCount=0;
141
142         private String FONT_FAMILY = "Arial";
143         private int FONT_SIZE = 9;
144         
145         public PdfReportHandler() {     }
146
147         public void createPdfFileContent(HttpServletRequest request, HttpServletResponse response, int type) throws IOException, RaptorException {
148
149                 Document document = new Document();
150                 ReportHandler rh = new ReportHandler();
151         String formattedDate = new SimpleDateFormat("MMddyyyyHHmm").format(new Date());
152                 String pdfFName = "";
153                 String user_id = AppUtils.getUserID(request);
154                 response.reset();
155                 response.setContentType("application/pdf");
156                 OutputStream outStream = response.getOutputStream();
157         
158         String formattedReportName = "";
159         PdfWriter writer = null;
160         ReportRuntime firstReportRuntimeObj = null;
161         int returnValue = 0;
162
163         ReportRuntime rr = null;
164         if(rr==null)
165             rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
166         
167         boolean isDashboard = false;
168         if ((request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID)!=null) && ( ((String) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID)).equals(rr.getReportID())) ) {
169                 isDashboard = true;
170         }
171                 if(isDashboard) {
172                         try {
173                                         String reportID = (String) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID);
174                                         ReportRuntime rrDash = rh.loadReportRuntime(request, reportID, true, 1);
175                                         pb = preparePdfBean(request,rrDash);
176                 
177                                         // Setting pb Values
178                                 document.setPageSize(PageSize.getRectangle(pb.getPagesize()));
179                                         if(!pb.isPortrait()) // get this from properties file
180                                                 document.setPageSize(document.getPageSize().rotate());
181                                 
182                                 //                      
183                                         writer = PdfWriter.getInstance(document, response.getOutputStream());
184                                         writer.setPageEvent(new PageEvent(pb));//header,footer,bookmark
185                                         document.open();
186
187                                         formattedReportName = new HtmlStripper().stripSpecialCharacters(rrDash.getReportName());
188                                 if(pb.isAttachmentOfEmail())
189                                         response.setHeader("Content-disposition", "inline");
190                                 else
191                                         response.setHeader("Content-disposition", "attachment;filename="+ formattedReportName+formattedDate+user_id+".pdf");
192                                         
193                                         pdfFName = "dashboard"+formattedReportName+formattedDate+user_id+".pdf";
194                                         Map reportRuntimeMap = null;
195                                         Map reportDataMap = null;
196                                         Map reportDisplayTypeMap = null;
197
198                                         reportRuntimeMap                        = (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP);
199                                         reportDataMap                           = (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP);
200                                         reportDisplayTypeMap            = (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP);
201
202                                         if(reportRuntimeMap!=null) {
203                                                 Set setReportRuntime            = reportRuntimeMap.entrySet();
204                                                 Set setReportDataMap            = reportDataMap.entrySet();
205                                                 Set setReportDisplayTypeMap = reportDisplayTypeMap.entrySet();
206                                                 
207                                                 Iterator iter2 = setReportDataMap.iterator();
208                                                 Iterator iter3 = setReportDisplayTypeMap.iterator();
209                                 int count = 0;
210                                                 for(Iterator iter = setReportRuntime.iterator(); iter.hasNext(); ) {
211                                                         count++;
212                                                         Map.Entry entryData             = (Entry) iter2.next();
213                                                         Map.Entry entry                         = (Entry) iter.next();
214                                                         Map.Entry entryCheckChart       = (Entry) iter3.next();
215                                                         ReportRuntime rrDashRep         = (ReportRuntime) entry.getValue();
216                                                         
217                                                         if(count == 1)  { 
218                                                                 firstReportRuntimeObj = (ReportRuntime) entry.getValue();
219                                                                 if(pb.isCoverPageIncluded()) {
220                                                                         document = paintDashboardCoverPage(document, rrDash, firstReportRuntimeObj, request);
221                                                                 }
222                                                         }
223                                                         ReportData rdDashRep            = (ReportData) entryData.getValue();
224                                                 int col = 0;
225                                                         if( ((rrDashRep.getChartType()).trim().length()>0 && rrDashRep.getDisplayChart()) && entryCheckChart.getValue().toString().equals("c")) {
226                                                                 document.newPage();
227                                                                 pb.setTitle(nvl(rrDashRep.getReportTitle()).length()>0?rrDashRep.getReportTitle():rrDashRep.getReportName());
228                                                                 paintPdfImage(request, document,AppUtils.getTempFolderPath()+"cr_"+  pb.getUserId()+"_"+request.getSession().getId()+"_"+rrDashRep.getReportID()+".png", rrDashRep);
229                                                         } else {
230                                                                 document.newPage();
231                                                                 pb.setTitle(nvl(rrDashRep.getReportTitle()).length()>0?rrDashRep.getReportTitle():rrDashRep.getReportName());
232                                                                 paintPdfData(request, document,rdDashRep,rrDashRep, "");
233                                                         }
234                                                 }
235                                         
236                                 }
237                         } catch (DocumentException dex) {
238                             logger.error(EELFLoggerDelegate.errorLogger, "DocumentException in createPdfFileContent", dex);
239                         }
240                         catch (RaptorException rex) {
241                             logger.error(EELFLoggerDelegate.errorLogger, "RaptorException in createPdfFileContent", rex);
242                         }
243                 } else {
244                         rr = null;
245                         ReportData rd = null;
246                         String parent = "";
247                         int parentFlag = 0;
248                         if(!nvl(request.getParameter("parent"), "").equals("N"))
249                                 parent = nvl(request.getParameter("parent"), "");
250                         if(parent.startsWith("parent_"))
251                                 parentFlag = 1;
252                         if(parentFlag == 1) {
253                                 rr = (ReportRuntime) request.getSession().getAttribute(parent+"_rr");
254                                 rd = (ReportData) request.getSession().getAttribute(parent+"_rd");
255                         }
256                         if(rr==null)
257                                 rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
258                         if(rd==null)
259                                 rd = (ReportData)    request.getSession().getAttribute(AppConstants.RI_REPORT_DATA);
260                         
261                         pb = preparePdfBean(request,rr);
262                         FONT_FAMILY = rr.getPDFFont();
263                         FONT_SIZE = rr.getPDFFontSize();
264                                         
265                         formattedReportName = new HtmlStripper().stripSpecialCharacters(rr.getReportName());
266                         
267                         
268                         
269                 response.setContentType("application/pdf");
270                 if(pb.isAttachmentOfEmail())
271                         response.setHeader("Content-disposition", "inline");
272                 else
273                         response.setHeader("Content-disposition", "attachment;filename="+ formattedReportName+formattedDate+user_id+".pdf");
274                         
275                         document.setPageSize(PageSize.getRectangle(pb.getPagesize()));
276                         
277                         if(!pb.isPortrait()) // get this from properties file
278                                 document.setPageSize(document.getPageSize().rotate());
279         
280                         try {
281                                 
282                                 writer = PdfWriter.getInstance(document, outStream);
283                                 writer.setPageEvent(new PageEvent(pb));//header,footer,bookmark
284                                 document.open();
285                                 
286                                 if(pb.isCoverPageIncluded()) {
287                                         document = paintCoverPage(document, rr, request);
288                                 }
289
290         
291                                 if(pb.isDisplayChart()) {
292                                         paintPdfImage(request, document,AppUtils.getTempFolderPath()+"cr_"+  pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+".png", rr);
293                                 }
294         
295                                 document.newPage();
296                         if(type == 3 && rr.getSemaphoreList()==null && !(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) ) { //type = 3 is whole
297                                 String sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE);
298                                 returnValue = paintPdfData(request, document, rd, rr, sql_whole);
299                         } else if(type == 2) {
300                                 returnValue = paintPdfData(request, document, rd, rr, "");
301                         } else {
302                                         int downloadLimit = (rr.getMaxRowsInExcelDownload()>0)?rr.getMaxRowsInExcelDownload():Globals.getDownloadLimit();
303                                         String action = request.getParameter(AppConstants.RI_ACTION);
304
305                                         if(!(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) && !action.endsWith("session"))
306                                                 rd              = rr.loadReportData(-1, AppUtils.getUserID(request), downloadLimit,request, false /*download*/);
307                                         if(rr.getSemaphoreList()!=null) {
308                                                 rd   =  rr.loadReportData(-1, AppUtils.getUserID(request), downloadLimit,request, true);
309                                                 returnValue = paintPdfData(request, document, rd, rr, "");
310                                         } else {
311                                                 returnValue = paintPdfData(request, document, rd, rr, rr.getWholeSQL());
312                                         }
313                                         
314                                         
315                         }
316                         
317                         
318                         } catch (DocumentException de) {
319                          logger.error(EELFLoggerDelegate.errorLogger, "DocumentException in createPdfFileContent", de);
320                 }
321                         
322                 }
323                 document.close();
324         int mb = 1024*1024;
325         Runtime runtime = Runtime.getRuntime();         
326         logger.debug(EELFLoggerDelegate.debugLogger, ("##### Heap utilization statistics [MB] #####"));
327         logger.debug(EELFLoggerDelegate.debugLogger, ("Used Memory:"
328                         + (runtime.maxMemory() - runtime.freeMemory()) / mb));
329         logger.debug(EELFLoggerDelegate.debugLogger, ("Free Memory:"
330                         + runtime.freeMemory() / mb));
331         logger.debug(EELFLoggerDelegate.debugLogger, ("Total Memory:" + runtime.totalMemory() / mb));
332         logger.debug(EELFLoggerDelegate.debugLogger, ("Max Memory:" + runtime.maxMemory() / mb));
333
334         }
335         
336         private Document paintCoverPage(Document doc, ReportRuntime rr, HttpServletRequest request) throws IOException, DocumentException {
337                 
338                 if(nvl(rr.getPdfImg()).length()>0) {
339                         Image image1 = Image.getInstance(AppUtils.getExcelTemplatePath()+"../../"+AppUtils.getImgFolderURL()+rr.getPdfImg());
340                         image1.scalePercent(20f, 20f);
341                         doc.add(image1);
342                 }
343                 float firstColumnSize = Globals.getCoverPageFirstColumnSize();
344                 float[] relativeWidths = {firstColumnSize,1f-firstColumnSize};
345                 PdfPTable table = new PdfPTable(relativeWidths);
346                 table.getDefaultCell().setBorderWidth(0);
347                 addEmptyRows(table,6);
348                 HTMLWorker worker = new HTMLWorker(doc);
349         StyleSheet style = new StyleSheet();
350         style.loadTagStyle("body", "leading", "16,0");
351         StringBuffer reportDescrBuf = new StringBuffer("");
352         ArrayList descr = HTMLWorker.parseToList(new StringReader(nvl(rr.getReportDescr())), style);
353         ArrayList paraList = null;
354            if(nvl(rr.getReportTitle()).length()>0) {
355                         add2Cells(table,"Report Title   : ",nvl(rr.getReportTitle()));
356                         if(nvl(rr.getReportSubTitle()).length()>0) {
357                                 add2Cells(table,"Report Sub-Title       : ",nvl(rr.getReportSubTitle()));
358                                 System.out.println("Adding the report sub-title ");
359                         }
360                         
361            } else {
362                         add2Cells(table,"Report Name    : ",nvl(rr.getReportName()));
363            }
364                         if((descr!=null && descr.size()>0)) {
365                                 paraList = (com.lowagie.text.Paragraph)descr.get(0);
366                                 for (int i=0 ; i<paraList.size(); i++) {
367                                         reportDescrBuf.append(paraList.get(i));
368                                 }
369                                 
370                         }
371                         add2Cells(table,"Description    : ",reportDescrBuf.toString());
372                 if(Globals.getSessionInfoForTheCoverPage().length()>0) {
373                         String nameValue[] = Globals.getSessionInfoForTheCoverPage().split(",");
374                                 String name=nameValue[0];
375                                 String value=nameValue[1];
376                                 add2Cells(table,name+" : ",(AppUtils.getRequestNvlValue(request, value).length()>0?AppUtils.getRequestNvlValue(request, value):nvl((String)request.getSession().getAttribute(value))));
377                 }
378                 
379                 if(Globals.isCreatedOwnerInfoNeeded()) {
380                         add2Cells(table,"Created By     : ",nvl(AppUtils.getUserName(rr.getCreateID())));
381                         add2Cells(table,"Owner                  : ",nvl(AppUtils.getUserName(rr.getOwnerID())));
382                 }
383                 if(Globals.displayLoginIdForDownloadedBy())
384                         add2Cells(table,"Downloaded by  : ",nvl(AppUtils.getUserBackdoorLoginId(request)));
385                 else
386                         add2Cells(table,"Downloaded by  : ",nvl(AppUtils.getUserName(AppUtils.getUserID(request))));
387                 
388                 addEmptyRows(table,1);
389
390                 boolean isFirstRow = true;
391         ArrayList al = rr.getParamNameValuePairsforPDFExcel(request, 1);
392         if(al.size()<=0) {
393                 al = (ArrayList) request.getSession().getAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO);
394         }
395
396                 Iterator it = al.iterator();
397                 addEmptyRows(table,1);
398                 if(rr.getFormFieldComments(request).length()<=0) {
399                         while(it.hasNext()) {
400                 
401                                 if(isFirstRow) {
402                         add2Cells(table, "Run-time Criteria : ", " ");
403                                         isFirstRow = false;
404                                 }
405                                         
406                                 IdNameValue value = (IdNameValue)it.next();
407                                 if(!value.getId().trim().equals("BLANK"))
408                                         add2Cells(table, value.getId()+" : ",value.getName().replaceAll("~",","));
409                         }
410                         addEmptyRows(table,1);
411                         doc.add(table);
412                         
413                 } else {
414                 it = al.iterator();
415                 if(it.hasNext()) {
416                         addEmptyRows(table,1);                  
417                         doc.add(table);
418                         ArrayList p = HTMLWorker.parseToList(new StringReader(rr.getFormFieldComments(request).replaceAll("~",",")), style);
419                         
420                          for (int k = 0; k < p.size(); ++k){
421                             doc.add((com.lowagie.text.Element)p.get(k));
422                          }
423                 }
424                 } 
425                 
426                 return doc;             
427         }
428         
429
430         private Document paintDashboardCoverPage(Document doc, ReportRuntime rrDashRep, ReportRuntime firstReportRuntimeObj, HttpServletRequest request) throws IOException, DocumentException {
431                 
432                 float firstColumnSize = Globals.getCoverPageFirstColumnSize();
433                 float[] relativeWidths = {firstColumnSize,1f-firstColumnSize};
434                 PdfPTable table = new PdfPTable(relativeWidths);
435                 table.getDefaultCell().setBorderWidth(0);
436                 addEmptyRows(table,6);
437
438                 add2Cells(table,"Report Name : ",rrDashRep.getReportName());
439                 add2Cells(table,"Description : ",rrDashRep.getReportDescr());
440                 if(Globals.getSessionInfoForTheCoverPage().length()>0) {
441                         String nameValue[] = Globals.getSessionInfoForTheCoverPage().split(",");
442                                 String name=nameValue[0];
443                                 String value=nameValue[1];
444                                 add2Cells(table,name+" : ",(AppUtils.getRequestNvlValue(request, value).length()>0?AppUtils.getRequestNvlValue(request, value):nvl((String)request.getSession().getAttribute(value))));
445                 }
446                 
447                 if(Globals.isCreatedOwnerInfoNeeded()) {
448                         add2Cells(table,"Created By : ",AppUtils.getUserName(rrDashRep.getCreateID()));
449                         add2Cells(table,"Owner : ",AppUtils.getUserName(rrDashRep.getOwnerID()));
450                 }
451                 if(Globals.displayLoginIdForDownloadedBy())
452                         add2Cells(table,"Downloaded by : ",AppUtils.getUserBackdoorLoginId(request));
453                 else
454                         add2Cells(table,"Downloaded by : ",AppUtils.getUserName(request));
455                 
456                 addEmptyRows(table,1);
457
458                 boolean isFirstRow = true;
459                 ArrayList al = firstReportRuntimeObj.getParamNameValuePairsforPDFExcel(request, 2);
460                 Iterator it = al.iterator();
461                 addEmptyRows(table,1);
462                 if(firstReportRuntimeObj.getFormFieldComments(request).length()<=0) {
463                         while(it.hasNext()) {
464                 
465                                 if(isFirstRow) {
466                                         add2Cells(table, "Run-time Criteria : ", " ");
467                                         isFirstRow = false;
468                                 }
469                                         
470                                 IdNameValue value = (IdNameValue)it.next();
471                                 if(!value.getId().trim().equals("BLANK"))
472                                         add2Cells(table, value.getId()+" : ",value.getName());
473                         }
474                         addEmptyRows(table,1);
475                         doc.add(table);
476                         
477                 } else {
478                 it = al.iterator();
479                 if(it.hasNext()) {
480                         addEmptyRows(table,1);                  
481                         doc.add(table);
482                         HTMLWorker worker = new HTMLWorker(doc);
483                         StyleSheet style = new StyleSheet();
484                         style.loadTagStyle("body", "leading", "16,0");
485                         ArrayList p = HTMLWorker.parseToList(new StringReader(firstReportRuntimeObj.getFormFieldComments(request)), style);
486                         
487                          for (int k = 0; k < p.size(); ++k){
488                             doc.add((com.lowagie.text.Element)p.get(k));
489                          }
490                 }
491                 } 
492                 
493                 return doc;             
494         }
495         
496         
497         public static void addEmptyRows(PdfPTable table, int rows) throws DocumentException {
498                 for (int i=0; i<rows; i++) 
499                         for(int j=0;j<table.getAbsoluteWidths().length;j++)
500                                 table.addCell(new Paragraph(" "));
501                 
502         }
503         
504         private void add2Cells(PdfPTable table, String key, String value) {
505                 
506                 PdfPCell cell;
507                 cell = new PdfPCell(new Paragraph(key));
508                 cell.setHorizontalAlignment(Rectangle.ALIGN_RIGHT);
509                 cell.setBorderWidth(0f);
510                 table.addCell(cell);
511                 
512                 cell = new PdfPCell(new Paragraph(value));
513                 cell.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
514                 cell.setBorderWidth(0f);
515                 table.addCell(cell);
516         }
517
518         private void paintPdfImage(HttpServletRequest request, Document document, String fileName, ReportRuntime rr) 
519                                 throws DocumentException
520         {
521                 
522                 ArrayList images = getImage(request, fileName,pb.isAttachmentOfEmail()?true:false, rr);
523                 PdfPTable table =  null;
524                 PdfPCell cellValue = null;
525                 if(images!=null) {
526                         
527                 for (int i = 0; i < images.size(); i++) {
528                         table = new PdfPTable(1);
529                         cellValue = new PdfPCell();
530                         cellValue.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
531                 Image image = (Image) images.get(i);                            
532                         image.setAlignment(Image.ALIGN_CENTER);
533                         if(i%2 ==0)
534                         document.newPage();
535                         cellValue.setImage(image);
536                         table.addCell(cellValue);
537                         document.add(table);
538                         }
539                 }
540         }
541         
542         private ArrayList getImage(HttpServletRequest request, String fileName, boolean isGenerateNewImage, ReportRuntime rr) {
543                 ArrayList images = new ArrayList();
544                 if(!isGenerateNewImage) {
545                         try {
546                                 Image image = Image.getInstance(fileName);
547                                 images.add(image);
548                                 return images;
549                         } 
550                         catch (MalformedURLException e) {
551                                 isGenerateNewImage = true;
552                     logger.error(EELFLoggerDelegate.errorLogger, "MalformedURLException in getImage", e);
553                         } 
554                         catch (BadElementException e) {
555                                 isGenerateNewImage = true;
556                     logger.error(EELFLoggerDelegate.errorLogger, "BadElementException in getImage", e);
557                         } catch (FileNotFoundException e) {
558                                 isGenerateNewImage = true;
559                 logger.error(EELFLoggerDelegate.errorLogger, "FileNotFoundException in getImage", e);
560                         } catch (IOException e) {
561                                 isGenerateNewImage = true;
562                 logger.error(EELFLoggerDelegate.errorLogger, "IOException in getImage", e);
563                     }                   
564                 }
565                 
566                 if(isGenerateNewImage && retryCreateNewImageCount<RetryCreateNewImage){
567                         retryCreateNewImageCount++;
568                         return generateNewImage(request, rr);
569                 }
570                 
571                 return null;
572                         
573         }
574
575         private ArrayList generateNewImage(HttpServletRequest request, ReportRuntime rr) {
576                 ArrayList images = new ArrayList();
577                 final String MALFORMEDURLEXCEPTION_MSG = "MalformedURLException in generateNewImage";
578                 final String BADELEMENTEXCEPTION_MSG = "BadElementException in generateNewImage";
579                 final String FILENOTFOUNDEXCEPTION_MSG = "FileNotFoundException in generateNewImage";
580                 final String IOEXCEPTION_MSG = "IOException in generateNewImage";
581                 try {
582                         DataSet ds = null;
583                         if(request.getSession().getAttribute(AppConstants.RI_CHART_DATA)!=null) {
584                                 ds = (DataSet) request.getSession().getAttribute(AppConstants.RI_CHART_DATA);
585                         } else {
586                                 ds = rr.loadChartData(pb.getUserId(),request);
587                         }
588                     String downloadFileName = "";
589                         HashMap additionalChartOptionsMap = new HashMap();
590                         String chartType = nvl(rr.getChartType());
591                         if(chartType.equals(AppConstants.GT_PIE_MULTIPLE)) {
592                                 additionalChartOptionsMap.put("multiplePieOrderRow", new Boolean((AppUtils.getRequestNvlValue(request, "multiplePieOrder").length()>0?AppUtils.getRequestNvlValue(request, "multiplePieOrder").equals("row"):rr.isMultiplePieOrderByRow())) );
593                                 additionalChartOptionsMap.put("multiplePieLabelDisplay", AppUtils.getRequestNvlValue(request, "multiplePieLabelDisplay").length()>0? AppUtils.getRequestNvlValue(request, "multiplePieLabelDisplay"):rr.getMultiplePieLabelDisplay());
594                                 additionalChartOptionsMap.put("chartDisplay", new Boolean(AppUtils.getRequestNvlValue(request, "chartDisplay").length()>0? AppUtils.getRequestNvlValue(request, "chartDisplay").equals("3D"):rr.isChartDisplayIn3D()));
595                         } else if (chartType.equals(AppConstants.GT_BAR_3D)) {
596                                 additionalChartOptionsMap.put("chartOrientation", new Boolean((AppUtils.getRequestNvlValue(request, "chartOrientation").length()>0?AppUtils.getRequestNvlValue(request, "chartOrientation").equals("vertical"):rr.isVerticalOrientation())) );
597                                 additionalChartOptionsMap.put("secondaryChartRenderer", AppUtils.getRequestNvlValue(request, "secondaryChartRenderer").length()>0? AppUtils.getRequestNvlValue(request, "secondaryChartRenderer"):rr.getSecondaryChartRenderer());
598                                 additionalChartOptionsMap.put("chartDisplay", new Boolean(AppUtils.getRequestNvlValue(request, "chartDisplay").length()>0? AppUtils.getRequestNvlValue(request, "chartDisplay").equals("3D"):rr.isChartDisplayIn3D()));
599                                 additionalChartOptionsMap.put("lastSeriesALineChart", new Boolean(rr.isLastSeriesALineChart()));                
600                         } else if (chartType.equals(AppConstants.GT_LINE)) {
601                                 additionalChartOptionsMap.put("chartOrientation", new Boolean((AppUtils.getRequestNvlValue(request, "chartOrientation").length()>0?AppUtils.getRequestNvlValue(request, "chartOrientation").equals("vertical"):rr.isVerticalOrientation())) );
602                                 additionalChartOptionsMap.put("chartDisplay", new Boolean(AppUtils.getRequestNvlValue(request, "chartDisplay").length()>0? AppUtils.getRequestNvlValue(request, "chartDisplay").equals("3D"):rr.isChartDisplayIn3D()));
603                                 additionalChartOptionsMap.put("lastSeriesABarChart", new Boolean(rr.isLastSeriesABarChart()));
604                         } else if (chartType.equals(AppConstants.GT_TIME_DIFFERENCE_CHART)) {
605                                 additionalChartOptionsMap.put("intervalFromDate",AppUtils.getRequestNvlValue(request, "intervalFromDate").length()>0?AppUtils.getRequestNvlValue(request, "intervalFromDate"):rr.getIntervalFromdate());
606                                 additionalChartOptionsMap.put("intervalToDate", AppUtils.getRequestNvlValue(request, "intervalToDate").length()>0? AppUtils.getRequestNvlValue(request, "intervalToDate"):rr.getIntervalTodate());
607                                 additionalChartOptionsMap.put("intervalLabel", AppUtils.getRequestNvlValue(request, "intervalLabel").length()>0? AppUtils.getRequestNvlValue(request, "intervalLabel"):rr.getIntervalLabel());
608                         } else if (chartType.equals(AppConstants.GT_REGRESSION)) {
609                                 additionalChartOptionsMap.put("regressionType",AppUtils.getRequestNvlValue(request, "regressionType").length()>0?AppUtils.getRequestNvlValue(request, "regressionType"):rr.getLinearRegression());
610                                 additionalChartOptionsMap.put("linearRegressionColor",nvl(rr.getLinearRegressionColor()));
611                                 additionalChartOptionsMap.put("expRegressionColor",nvl(rr.getExponentialRegressionColor()));
612                                 additionalChartOptionsMap.put("maxRegression",nvl(rr.getCustomizedRegressionPoint()));
613                         } else if (chartType.equals(AppConstants.GT_STACK_BAR) ||chartType.equals(AppConstants.GT_STACKED_HORIZ_BAR) || chartType.equals(AppConstants.GT_STACKED_HORIZ_BAR_LINES)
614                            || chartType.equals(AppConstants.GT_STACKED_VERT_BAR) || chartType.equals(AppConstants.GT_STACKED_VERT_BAR_LINES)    
615                         ) {
616                                 additionalChartOptionsMap.put("overlayItemValue",new Boolean(nvl(rr.getOverlayItemValueOnStackBar()).equals("Y")));
617                         }
618                         additionalChartOptionsMap.put("legendPosition", nvl(rr.getLegendPosition()));
619                         additionalChartOptionsMap.put("hideToolTips", new Boolean(rr.hideChartToolTips()));
620                         additionalChartOptionsMap.put("hideLegend", new Boolean(AppUtils.getRequestNvlValue(request, "hideLegend").length()>0? AppUtils.getRequestNvlValue(request, "hideLegend").equals("Y"):rr.hideChartLegend()));
621                         additionalChartOptionsMap.put("labelAngle", nvl(rr.getLegendLabelAngle()));
622                         additionalChartOptionsMap.put("maxLabelsInDomainAxis", nvl(rr.getMaxLabelsInDomainAxis()));
623                         additionalChartOptionsMap.put("rangeAxisLowerLimit", nvl(rr.getRangeAxisLowerLimit()));
624                         additionalChartOptionsMap.put("rangeAxisUpperLimit", nvl(rr.getRangeAxisUpperLimit()));
625                         
626                     
627                         boolean totalOnChart = false;
628                         totalOnChart = AppUtils.getRequestNvlValue(request, "totalOnChart").equals("Y");
629                         String filename  = null;
630                         ArrayList graphURL  = new ArrayList();
631                         ArrayList chartNames = new ArrayList();
632                         ArrayList fileNames = new ArrayList(); 
633                     List l = rr.getAllColumns();
634                     List lGroups = rr.getAllChartGroups();
635                     HashMap mapYAxis = rr.getAllChartYAxis(rr.getReportParamValues());
636                     String chartLeftAxisLabel = rr.getFormFieldFilled(nvl(rr.getChartLeftAxisLabel()));
637                 String chartRightAxisLabel = rr.getFormFieldFilled(nvl(rr.getChartRightAxisLabel()));
638                     int displayTotalOnChart = 0;
639                     HashMap formValues = Globals.getRequestParamtersMap(request, false);
640
641                     for (Iterator iterC = l.iterator(); iterC.hasNext();) {
642                                 DataColumnType dc = (DataColumnType) iterC.next();
643                                 if(nvl(dc.getColName()).equals(AppConstants.RI_CHART_TOTAL_COL)) {
644                                         displayTotalOnChart = 1;
645                                 }
646                         }
647                     
648                     String legendColumnName = (rr.getChartLegendColumn()!=null)?rr.getChartLegendColumn().getDisplayName():"Legend Column";
649                     
650                     
651                     
652                         if(ds!=null)
653                         {
654                                    if(rr.hasSeriesColumn() && chartType.equals(AppConstants.GT_TIME_SERIES) && (lGroups==null || lGroups.size() <= 0)) { /** Check whether Report has only category  columns if so then all the columns will open in seperate chart - sundar**/
655                                 for (int i=0; i<rr.getChartValueColumnAxisList(AppConstants.CHART_ALL_COLUMNS, formValues).size();i++) {
656                                 String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():"";
657                                 chartTitle = rr.getFormFieldFilled(chartTitle);
658                                                 downloadFileName = AppUtils.getTempFolderPath()+"cr_"+pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png";
659                                                 filename = null;
660                         try {
661                             Image image = Image.getInstance(downloadFileName);
662                             images.add(image);
663                         } catch (MalformedURLException e) {
664                             logger.error(EELFLoggerDelegate.errorLogger, MALFORMEDURLEXCEPTION_MSG,
665                                     e);
666                         } catch (BadElementException e) {
667                             logger.error(EELFLoggerDelegate.errorLogger, BADELEMENTEXCEPTION_MSG,
668                                     e);
669                         } catch (FileNotFoundException e) {
670                             logger.error(EELFLoggerDelegate.errorLogger, FILENOTFOUNDEXCEPTION_MSG,
671                                     e);
672                         } catch (IOException e) {
673                             logger.error(EELFLoggerDelegate.errorLogger, IOEXCEPTION_MSG, e);
674                         }
675                                 }
676                                            
677                                    } else { /** first check the columns to be opened in new charts and loop around in ChartGen generate chart function  - sundar**/
678                             String tempChartGroupPrev = "";
679                                         String tempChartGroupCurrent = "";
680                                 for (int i=0; i<lGroups.size();i++) {
681                                         String chartGroupOrg = (String) lGroups.get(i);
682                                         String chartYAxis = (String) mapYAxis.get(chartGroupOrg);
683                                         if(nvl(chartGroupOrg).length()>0)
684                                                 tempChartGroupCurrent = chartGroupOrg.substring(0,chartGroupOrg.lastIndexOf("|"));
685                                         if(i>0)
686                                                                 tempChartGroupPrev = ((String) lGroups.get(i-1)).substring(0,((String) lGroups.get(i-1)).lastIndexOf("|"));
687                                         if(tempChartGroupCurrent.equals(tempChartGroupPrev))
688                                                                 continue;
689                                         String chartGroup = chartGroupOrg;
690                                         
691                                                         downloadFileName = AppUtils.getTempFolderPath()+"cr_"+pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png";
692                                                         String chartTitle = (Globals.getDisplayChartTitle()? (chartGroup!=null && chartGroup.indexOf("|") > 0 ?chartGroup.substring(0,chartGroup.lastIndexOf("|")):rr.getReportName()):"");
693                                                         chartTitle = rr.getFormFieldFilled(chartTitle);
694                                                         String leftAxisLabel = "";
695                                                           if(!rr.isMultiSeries()) {
696                                                                 leftAxisLabel = ((chartYAxis!=null && chartYAxis.indexOf("|") > 0) ? chartYAxis.substring(0,chartYAxis.lastIndexOf("|")): chartLeftAxisLabel );
697                                                         } else {
698                                                                 leftAxisLabel = chartLeftAxisLabel;
699                                                         }
700
701                                                 filename = null;
702                         try {
703                             Image image = Image.getInstance(downloadFileName);
704                             images.add(image);
705                         } catch (MalformedURLException e) {
706                             logger.error(EELFLoggerDelegate.errorLogger, MALFORMEDURLEXCEPTION_MSG,
707                                     e);
708                         } catch (BadElementException e) {
709                             logger.error(EELFLoggerDelegate.errorLogger, BADELEMENTEXCEPTION_MSG,
710                                     e);
711                         } catch (FileNotFoundException e) {
712                             logger.error(EELFLoggerDelegate.errorLogger, FILENOTFOUNDEXCEPTION_MSG,
713                                     e);
714                         } catch (IOException e) {
715                             logger.error(EELFLoggerDelegate.errorLogger, IOEXCEPTION_MSG, e);
716                         }
717                                                 }
718                                            
719                             if(!chartType.equals(AppConstants.GT_PIE_MULTIPLE)) {    
720                         for (int i=0; i<rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).size();i++) { 
721
722                                                 downloadFileName = AppUtils.getTempFolderPath()+"cr_"+ pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png";
723                                 String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():"";
724                                 chartTitle = rr.getFormFieldFilled(chartTitle);
725
726                         filename = null; 
727                                 
728                             try {
729                                 Image image = Image.getInstance(downloadFileName);
730                                 images.add(image);
731                             } catch (MalformedURLException e) {
732                                 logger.error(EELFLoggerDelegate.errorLogger,
733                                         MALFORMEDURLEXCEPTION_MSG, e);
734                             } catch (BadElementException e) {
735                                 logger.error(EELFLoggerDelegate.errorLogger,
736                                         BADELEMENTEXCEPTION_MSG, e);
737                             } catch (FileNotFoundException e) {
738                                 logger.error(EELFLoggerDelegate.errorLogger,
739                                         FILENOTFOUNDEXCEPTION_MSG, e);
740                             } catch (IOException e) {
741                                 logger.error(EELFLoggerDelegate.errorLogger, IOEXCEPTION_MSG, e);
742                             }
743                         }
744                             }
745                         /** second rest of the columns are merged to one single chart  - sundar**/
746
747                                           if((!(lGroups!=null && lGroups.size() > 0))) {
748                                                   
749                                            if(/*chartType.equals(AppConstants.GT_TIME_SERIES) && */rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues)!=null && rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues).size()>0) {
750                         downloadFileName = AppUtils.getTempFolderPath()+"cr_"+  pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_All.png";
751                         String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():"";
752                         chartTitle = rr.getFormFieldFilled(chartTitle);
753
754                         filename = null; 
755                         
756                             try {
757                                 Image image = Image.getInstance(downloadFileName);
758                                 images.add(image);
759                             } catch (MalformedURLException e) {
760                                 logger.error(EELFLoggerDelegate.errorLogger,
761                                         MALFORMEDURLEXCEPTION_MSG, e);
762                             } catch (BadElementException e) {
763                                 logger.error(EELFLoggerDelegate.errorLogger,
764                                         BADELEMENTEXCEPTION_MSG, e);
765                             } catch (FileNotFoundException e) {
766                                 logger.error(EELFLoggerDelegate.errorLogger,
767                                         FILENOTFOUNDEXCEPTION_MSG, e);
768                             } catch (IOException e) {
769                                 logger.error(EELFLoggerDelegate.errorLogger, IOEXCEPTION_MSG, e);
770                             }
771                         }
772                     } // Stacked Chart Check
773                 } // else no Series Column
774
775             } // if(ds!=null)
776
777         } catch (Exception e) {
778             logger.error(EELFLoggerDelegate.errorLogger, "Exception in generateNewImage", e);
779         }
780                 return images.size()>0?images:null;
781                 
782         }
783
784
785         private final int DEFAULT_PDF_DISPLAY_WIDTH = 10;
786
787     private int paintPdfData(final HttpServletRequest request, final Document document, final ReportData rd,
788         final ReportRuntime rr, final String sql_whole) throws DocumentException, RaptorException, IOException {
789
790         final int mb = 1024 * 1024;
791         final Runtime runtime = Runtime.getRuntime();
792         int returnValue = 0;
793
794         final float f[] = getRelativeWidths(rd, AppConstants.RT_CROSSTAB.equals(rr.getReportType()));
795         PdfPTable table = new PdfPTable(f);
796         table.setWidthPercentage(100f);
797         table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
798         table.getDefaultCell().setVerticalAlignment(Rectangle.ALIGN_BOTTOM);
799
800         final ReportDefinition rdef = (new ReportHandler()).loadReportDefinition(request, rr.getReportID());
801
802         final List allColumns = rdef.getAllColumns();
803
804         final float[] repotWidths = new float[rdef.getVisibleColumnCount()];
805         int columnIdx = 0;
806         float pdfDisplayWidth = 0;
807         for (final Iterator iter = allColumns.iterator(); iter.hasNext(); ) {
808             final DataColumnType dct = (DataColumnType) iter.next();
809             if (dct.isVisible()) {
810
811                 if (dct.getPdfDisplayWidthInPxls() == null || dct.getPdfDisplayWidthInPxls().isEmpty() || dct
812                     .getPdfDisplayWidthInPxls().startsWith("null")) {
813                     pdfDisplayWidth = DEFAULT_PDF_DISPLAY_WIDTH;
814                 } else {
815                     pdfDisplayWidth = Float.parseFloat(dct.getPdfDisplayWidthInPxls());
816                 }
817
818                 repotWidths[columnIdx++] = pdfDisplayWidth;
819             }
820         }
821
822         table.setWidths(repotWidths);
823
824         //TODO: check title and subtitle
825         final HttpSession session = request.getSession();
826         final String drilldown_index = (String) session.getAttribute("drilldown_index");
827         int index = 0;
828         try {
829             index = Integer.parseInt(drilldown_index);
830         } catch (NumberFormatException ex) {
831             index = 0;
832         }
833         final String titleRep = (String) session.getAttribute("TITLE_" + index);
834         final String subtitle = (String) session.getAttribute("SUBTITLE_" + index);
835
836         if (nvl(titleRep).length() > 0 && nvl(subtitle).length() > 0) {
837             table.setHeaderRows(3);
838         } else if (nvl(titleRep).length() > 0) {
839             table.setHeaderRows(2);
840         } else {
841             table.setHeaderRows(1);
842         }
843         table = paintPdfReportHeader(request, document, table, rr, f);
844         paintPdfTableHeader(document, rd, table);
845
846         int idx = 0;
847         final int fragmentsize = 30; //for memory management
848
849         rd.reportDataRows.resetNext();
850         DataRow dr = rd.reportDataRows.getNext();
851
852         if (nvl(sql_whole).length() > 0 && AppConstants.RT_LINEAR.equals(rr.getReportType())) {
853             try (final Connection conn = ConnectionUtils.getConnection(rr.getDbInfo());
854                 final Statement st = conn.createStatement();
855                 final ResultSet rs = st.executeQuery(sql_whole);) {
856
857                 logger.debug(EELFLoggerDelegate.debugLogger, ("************* Map Whole SQL *************"));
858                 logger.debug(EELFLoggerDelegate.debugLogger, (sql_whole));
859                 logger.debug(EELFLoggerDelegate.debugLogger, ("*****************************************"));
860
861                 final ResultSetMetaData rsmd = rs.getMetaData();
862                 final int numberOfColumns = rsmd.getColumnCount();
863                 dr = null;
864                 int rowCount = 0;
865                 while (rs.next()) {
866
867                     rowCount++;
868                     final Map colHash = new HashMap();
869                     for (int i = 1; i <= numberOfColumns; i++) {
870                         colHash.put(rsmd.getColumnLabel(i).toUpperCase(), rs.getString(i));
871                     }
872                     rd.reportDataRows.resetNext();
873
874                     dr = rd.reportDataRows.getNext();
875
876                     for (dr.resetNext(); dr.hasNext(); ) {
877                         final DataValue dv = dr.getNext();
878
879                         final String value = nvl((String) colHash.get(dv.getColId().toUpperCase()));
880                         if (dv.isVisible()) {
881
882                             final HtmlFormatter cfmt = dv.getCellFormatter();
883                             final HtmlFormatter rfmt = dv.getRowFormatter();
884
885                             final Font cellFont = FontFactory.getFont(FONT_FAMILY,
886                                 FONT_SIZE,
887                                 Font.NORMAL, Color.BLACK);
888                             if (cfmt != null) {
889                                 cellFormatterFont(cfmt, cellFont);
890                             } else if (rfmt != null) {
891                                 cellFormatterFont(rfmt, cellFont);
892                             } else {
893                                 if (dv.isBold()) {
894                                     cellFont.setStyle(Font.BOLD);
895                                 }
896                             }
897
898                             final String cellValue = strip.stripHtml(value.trim());
899                             final PdfPCell cell = new PdfPCell(new Paragraph(cellValue, cellFont));
900
901                             //row background color can be overwritten by cell background color
902                             cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
903
904                             if (nvl(dv.getAlignment()).trim().length() > 0) {
905                                 cell.setHorizontalAlignment(ElementTags.alignmentValue(dv.getAlignment()));
906                             } else {
907                                 cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
908                             }
909
910                             if (cfmt != null) {
911                                 formatterCell(cfmt, cell);
912                             } else if (rfmt != null) {
913                                 formatterCell(rfmt, cell);
914                             }
915
916                             table.addCell(cell);
917
918                         }//if isVisible()
919
920                     }
921
922                 }
923                 if (rd.reportDataTotalRow != null) {
924                     for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext(); idx++) {
925                         dr = rd.reportDataTotalRow.getNext();
926                         table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
927                         final Font rowHeaderFont = FontFactory.getFont(FONT_FAMILY,
928                             FONT_SIZE,
929                             Font.NORMAL, Color.BLACK);
930                         rowHeaderFont.setStyle(Font.BOLD);
931                         rowHeaderFont.setSize(FONT_SIZE + 1f);
932                         table.getDefaultCell().setBackgroundColor(getRowBackgroundColor(dr, idx));
933                         table.addCell(new Paragraph("Total", rowHeaderFont));
934
935                         addTotalRowColumns(table, dr, idx);
936                         if (idx % fragmentsize == fragmentsize - 1) {
937                             document.add(table);
938                             table.deleteBodyRows();
939                             table.setSkipFirstHeader(true);
940                         }
941
942                     }
943                 }
944             } catch (final SQLException | ReportSQLException ex) {
945                 throw new RaptorException(ex);
946             } catch (final Exception ex) {
947                 if (!(ex.getCause() instanceof java.net.SocketException)) {
948                     throw new RaptorException(ex);
949                 }
950             }
951             //document.add(table);
952         } else {
953             if (rr.getReportType().equals(AppConstants.RT_LINEAR)) {
954                 for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext(); idx++) {
955
956                     if (runtime.freeMemory() / mb <= ((runtime.maxMemory() / mb) * Globals.getMemoryThreshold()
957                         / 100)) {
958                         returnValue = 1;
959                     }
960
961                     dr = rd.reportDataRows.getNext();
962
963                     addRowHeader(table, dr, idx, rd);
964
965                     addRowColumns(table, dr, idx);
966
967                     if (idx % fragmentsize == fragmentsize - 1) {
968                         document.add(table);
969                         table.deleteBodyRows();
970                         table.setSkipFirstHeader(true);
971                     }
972                 }
973
974                 if (rd.reportDataTotalRow != null) {
975                     for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext(); idx++) {
976                         dr = rd.reportDataTotalRow.getNext();
977                         table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
978                         Font rowHeaderFont = FontFactory.getFont(FONT_FAMILY,
979                             FONT_SIZE,
980                             Font.NORMAL, Color.BLACK);
981                         rowHeaderFont.setStyle(Font.BOLD);
982                         rowHeaderFont.setSize(FONT_SIZE + 1f);
983                         table.getDefaultCell().setBackgroundColor(getRowBackgroundColor(dr, idx));
984                         table.addCell(new Paragraph("Total", rowHeaderFont));
985
986                         addTotalRowColumns(table, dr, idx);
987                         if (idx % fragmentsize == fragmentsize - 1) {
988                             document.add(table);
989                             table.deleteBodyRows();
990                             table.setSkipFirstHeader(true);
991                         }
992
993                     }
994                 }
995
996             } else if (AppConstants.RT_CROSSTAB.equals(rr.getReportType())) {
997                 int rowCount = 0;
998                 final List l = rd.getReportDataList();
999                 boolean first = true;
1000                 for (int dataRow = 0; dataRow < l.size(); dataRow++) {
1001                     first = true;
1002                     rowCount++;
1003                     dr = (DataRow) l.get(dataRow);
1004                     final Vector<DataValue> rowNames = dr.getRowValues();
1005                     for (dr.resetNext(); dr.hasNext(); ) {
1006
1007                         if (first) {
1008                             HtmlFormatter rfmt = dr.getRowFormatter();
1009
1010                             Font cellFont = FontFactory.getFont(FONT_FAMILY,
1011                                 FONT_SIZE,
1012                                 Font.NORMAL, Color.BLACK);
1013                             if (rfmt != null) {
1014                                 cellFormatterFont(rfmt, cellFont);
1015                             }
1016
1017                             if (rowNames != null) {
1018                                 for (int i = 0; i < rowNames.size(); i++) {
1019                                     final DataValue dv = rowNames.get(i);
1020                                     rfmt = dr.getRowFormatter();
1021
1022                                     cellFont = FontFactory.getFont(FONT_FAMILY,
1023                                         FONT_SIZE,
1024                                         Font.NORMAL, Color.BLACK);
1025                                     if (rfmt != null) {
1026                                         cellFormatterFont(rfmt, cellFont);
1027                                     }
1028                                     String cellValue = dv.getDisplayValue();
1029                                     if (cellValue.indexOf("|#") != -1) {
1030                                         cellValue = cellValue.substring(0, cellValue.indexOf("|"));
1031                                     }
1032
1033                                     final PdfPCell cell = new PdfPCell(new Paragraph(cellValue, cellFont));
1034                                     //row background color can be overwritten by cell background color
1035                                     cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
1036
1037                                     cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1038
1039                                     if (rfmt != null) {
1040                                         formatterCell(rfmt, cell);
1041                                     }
1042                                     table.addCell(cell);
1043                                 }
1044                             }
1045                         }
1046                         first = false;
1047
1048                         if (runtime.freeMemory() / mb <= ((runtime.maxMemory() / mb) * Globals.getMemoryThreshold()
1049                             / 100)) {
1050                             returnValue = 1;
1051                         }
1052
1053                         //addRowHeader(table,dr,idx,rd);
1054
1055                         addRowColumns(table, dr, idx);
1056
1057                         if (idx % fragmentsize == fragmentsize - 1) {
1058                             document.add(table);
1059                             table.deleteBodyRows();
1060                             table.setSkipFirstHeader(true);
1061                         }
1062                     }
1063
1064                 }
1065             }
1066
1067             //document.add(table);
1068
1069         }
1070
1071         document.add(table);
1072         paintPdfReportFooter(request, document, rr, f);
1073
1074         return returnValue;
1075     }
1076
1077         private void addRowHeader(PdfPTable table, DataRow dr, int idx, ReportData rd) {
1078                 
1079                 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);  
1080
1081                 for(rd.reportRowHeaderCols.resetNext();rd.reportRowHeaderCols.hasNext();) {
1082                         RowHeaderCol rhc = rd.reportRowHeaderCols.getNext();
1083                         if(idx==0) 
1084                                 rhc.resetNext();
1085                         RowHeader rh = rhc.getNext();
1086                         //System.out.println(" =============== RowHeader\n "+rh);
1087                         
1088                         Font rowHeaderFont = FontFactory.getFont(FONT_FAMILY, 
1089                                                                                                         FONT_SIZE,
1090                                                                                                         Font.NORMAL, Color.BLACK);
1091                         if(rh.isBold()) {
1092                                 rowHeaderFont.setStyle(Font.BOLD);
1093                                 rowHeaderFont.setSize(FONT_SIZE+1f);
1094                         }
1095                         
1096                         if(rh.getColSpan()>0) {
1097                                 table.getDefaultCell().setColspan(rh.getColSpan());
1098                                 table.getDefaultCell().setBackgroundColor(getRowBackgroundColor(dr, idx));
1099                                 table.addCell(new Paragraph(strip.stripHtml(rh.getRowTitle()),rowHeaderFont));
1100                         }
1101                 }               
1102         }
1103
1104         private void addRowColumns(PdfPTable table, DataRow dr, int idx) {
1105                         
1106                 table.getDefaultCell().setColspan(1);
1107                         
1108                 for(dr.resetNext();dr.hasNext();)
1109                 {
1110                         DataValue dv = dr.getNext();
1111                         //System.out.println(columnCount +" --> "+dv);
1112                         if(dv.isVisible()) {
1113                                 HtmlFormatter cfmt = dv.getCellFormatter();
1114                                 HtmlFormatter rfmt = dv.getRowFormatter();
1115
1116                                 Font cellFont = FontFactory.getFont(FONT_FAMILY, 
1117                                                                                                         FONT_SIZE,
1118                                                                                                         Font.NORMAL, Color.BLACK);
1119                                 if(cfmt!= null) {
1120                                         cellFormatterFont(cfmt,cellFont);
1121                                 }
1122                                 else if(rfmt != null) {
1123                                         cellFormatterFont(rfmt,cellFont);
1124                                 }
1125                                 else {
1126                                         if(dv.isBold()) {
1127                                                 cellFont.setStyle(Font.BOLD);
1128                                         }
1129                                 }
1130                                 
1131                                 String cellValue = strip.stripHtml(dv.getDisplayValue().trim());
1132                                 PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont));
1133                                 
1134                                 //row background color can be overwritten by cell background color
1135                                 cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
1136                                 
1137                                 if(nvl(dv.getAlignment()).trim().length()>0)
1138                                         cell.setHorizontalAlignment(ElementTags.alignmentValue(dv.getAlignment()));
1139                                 else
1140                                         cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1141                                 
1142                                 if(cfmt!= null) {
1143                                         formatterCell(cfmt,cell);
1144                                 }
1145                                 else if(rfmt != null) {
1146                                         formatterCell(rfmt,cell);
1147                                 }
1148                                 
1149                                 table.addCell(cell);
1150                         
1151                         }//if isVisible()
1152                 }                                       
1153         }
1154
1155
1156         private void addTotalRowColumns(PdfPTable table, DataRow dr, int idx) {
1157                 
1158                 table.getDefaultCell().setColspan(1);
1159                 dr.resetNext();
1160                 dr.getNext();
1161                 for(;dr.hasNext();)
1162                 {
1163                         DataValue dv = dr.getNext();
1164                         //System.out.println(columnCount +" --> "+dv);
1165                         if(dv.isVisible()) {
1166                                 HtmlFormatter cfmt = dv.getCellFormatter();
1167                                 HtmlFormatter rfmt = dv.getRowFormatter();
1168
1169                                 Font cellFont = FontFactory.getFont(FONT_FAMILY, 
1170                                                                                                         FONT_SIZE,
1171                                                                                                         Font.NORMAL, Color.BLACK);
1172                                 if(cfmt!= null) {
1173                                         cellFormatterFont(cfmt,cellFont);
1174                                 }
1175                                 else if(rfmt != null) {
1176                                         cellFormatterFont(rfmt,cellFont);
1177                                 }
1178                                 else {
1179                                         if(dv.isBold()) {
1180                                                 cellFont.setStyle(Font.BOLD);
1181                                         }
1182                                 }
1183                                 
1184                                 String cellValue = strip.stripHtml(dv.getDisplayValue().trim());
1185                                 PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont));
1186                                 
1187                                 //row background color can be overwritten by cell background color
1188                                 cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
1189                                 
1190                                 if(nvl(dv.getAlignment()).trim().length()>0)
1191                                         cell.setHorizontalAlignment(ElementTags.alignmentValue(dv.getAlignment()));
1192                                 else
1193                                         cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1194                                 
1195                                 if(cfmt!= null) {
1196                                         formatterCell(cfmt,cell);
1197                                 }
1198                                 else if(rfmt != null) {
1199                                         formatterCell(rfmt,cell);
1200                                 }
1201                                 
1202                                 table.addCell(cell);
1203                         
1204                         }//if isVisible()
1205                 }                                       
1206         }
1207         
1208         
1209         private void formatterCell(HtmlFormatter fmt, PdfPCell cell) {
1210                 
1211                 if(nvl(fmt.getBgColor()).trim().length()>0)
1212                         cell.setBackgroundColor(Color.decode(fmt.getBgColor()));
1213                 if(nvl(fmt.getAlignment()).trim().length()>0)
1214                         cell.setHorizontalAlignment(ElementTags.alignmentValue(fmt.getAlignment()));
1215         }
1216
1217         private void cellFormatterFont(HtmlFormatter fmt, Font font) {
1218                 
1219                 if(fmt.isBold()) 
1220                         font.setStyle(Font.BOLD);
1221                 if(fmt.isItalic()) 
1222                         font.setStyle(Font.ITALIC);
1223                 if(fmt.isUnderline()) 
1224                         font.setStyle(Font.UNDERLINE);
1225                 if(fmt.getFontColor().trim().length()>0)
1226                         font.setColor(Color.decode(fmt.getFontColor()));
1227                 if(fmt.getFontSize().trim().length()>0)
1228                         font.setSize(Float.parseFloat(fmt.getFontSize())-Globals.getDataFontSizeOffset());
1229 //              if(fmt.getFontFace().trim().length()>0)
1230 //                      cellFont.setFamily()
1231                 
1232         }
1233
1234         private Color getRowBackgroundColor(DataRow dr, int idx) {
1235                 
1236                 Color color =  Color.decode(Globals.getDataDefaultBackgroundHexCode());
1237                 
1238                 HtmlFormatter rhf = dr.getRowFormatter();
1239                 if(rhf!=null && nvl(rhf.getBgColor()).trim().length()>0)
1240                         
1241                         color = Color.decode(rhf.getBgColor());
1242                 
1243                 else if(pb.isAlternateColor() && idx%2==0)
1244                         
1245                         color = Color.decode(Globals.getDataBackgroundAlternateHexCode());
1246                 
1247                 return color;           
1248
1249         }
1250
1251         private int getTotalVisbleColumns(ReportData rd) {
1252                 
1253                 int totalVisbleColumn = rd.getTotalColumnCount();
1254                 for(rd.reportDataRows.resetNext();rd.reportDataRows.hasNext();)
1255                 {       
1256                         DataRow dr = rd.reportDataRows.getNext();
1257                         for(dr.resetNext();dr.hasNext();) {
1258                                 DataValue dv = dr.getNext();
1259                                 if(!dv.isVisible())
1260                                     totalVisbleColumn--;
1261                         }
1262                         
1263                         break;
1264                 }
1265                 
1266                 return totalVisbleColumn;
1267         }
1268
1269         /*
1270         private int getFirstRowIndex(ReportRuntime rr) {
1271                 return (pb.getCurrentPage()>0)?pb.getCurrentPage()*rr.getPageSize()+1 : 1;
1272         }
1273         */
1274         private float[] getRelativeWidths(ReportData rd, boolean crosstab){
1275                 
1276                 int totalColumns = getTotalVisbleColumns(rd);
1277                 /*if(rd.reportTotalRowHeaderCols!=null) {
1278                         totalColumns += 1;
1279                 }*/
1280                 if(crosstab) {
1281                         totalColumns += 1;
1282                 }
1283
1284                 if(totalColumns == 0 )
1285                         totalColumns=1;
1286                 
1287                 float[] relativeWidths = new float[totalColumns];
1288                 //initial widths are even
1289                 for(int i=0; i<relativeWidths.length; i++)
1290                         relativeWidths[i] = 10f;
1291                 
1292                 int index=0;
1293                 boolean firstPass = true;
1294                 
1295                 for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) 
1296                 {
1297                         if(firstPass) {
1298                                 /*if(rd.reportTotalRowHeaderCols!=null) { 
1299                                         String columnWidth = "5";
1300                                         
1301                                         if(columnWidth != null && columnWidth.trim().endsWith("%"))
1302                                                 relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
1303                                         
1304                                         index++;
1305                                 }*/
1306                                 
1307                                 for(rd.reportRowHeaderCols.resetNext();rd.reportRowHeaderCols.hasNext();) {
1308                                         String columnWidth = rd.reportRowHeaderCols.getNext().getColumnWidth();
1309                                         
1310                                         if(columnWidth != null && columnWidth.trim().endsWith("%"))
1311                                                 relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
1312                                         
1313                                         index++;
1314                                 }
1315                                 firstPass = false;
1316                         }
1317                 
1318                         ColumnHeaderRow chr = rd.reportColumnHeaderRows.getNext();
1319                         for (chr.resetNext(); chr.hasNext();) {
1320                                 
1321                                 ColumnHeader ch = chr.getNext();
1322
1323                                 if(ch.isVisible()) {
1324                                         
1325                                         String columnWidth = ch.getColumnWidth();
1326                                         
1327                                         if(ch.getColSpan() <= 1){
1328                                                 if(columnWidth != null && columnWidth.trim().endsWith("%")) 
1329                                                         relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
1330                                         } 
1331                                         else {
1332                                                 for(int i=0; i<ch.getColSpan(); i++) {
1333                                                         index += i;
1334                                                         if(columnWidth != null && columnWidth.trim().endsWith("%"))
1335                                                                 relativeWidths[index] = 
1336                                                                         (Float.parseFloat(removeLastCharacter(columnWidth)))/ch.getColSpan();                                                   
1337                                                 }
1338                                         }
1339                                         
1340                                         index++;
1341                                 }
1342                         }
1343                 }
1344                 
1345                 return relativeWidths;
1346         }
1347         
1348         public static String removeLastCharacter(String str) {
1349                 return str.substring(0, str.length()-1);
1350         }
1351         
1352         private PdfPTable paintPdfReportHeader(HttpServletRequest request, Document document, PdfPTable table, ReportRuntime rr, float[] f) 
1353                         throws DocumentException, IOException {
1354                 
1355                 HttpSession session = request.getSession();
1356                 String drilldown_index = (String) session.getAttribute("drilldown_index");
1357                 int index = 0;
1358                 try {
1359                  index = Integer.parseInt(drilldown_index);
1360                 } catch (NumberFormatException ex) {
1361                         index = 0;
1362                 }
1363                 String title = (String) session.getAttribute("TITLE_"+index);
1364                 String subtitle = (String) session.getAttribute("SUBTITLE_"+index);
1365                 if(nvl(title).length()>0) {
1366                         //PdfPTable table = new PdfPTable(1);
1367                         table.setWidthPercentage(100f);
1368                         table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1369                         table.getDefaultCell().setVerticalAlignment(Rectangle.ALIGN_BOTTOM);
1370                 
1371         
1372                         Font font = FontFactory.getFont(FONT_FAMILY, 
1373                                         FONT_SIZE-2f,
1374                                         Font.BOLD, 
1375                                         Color.BLACK);
1376                 
1377                         //addEmptyRows(table,1);
1378                         table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1379                         //table.getDefaultCell().setBackgroundColor(Color.decode(Globals.getDataTableHeaderBackgroundFontColor()));
1380                     title = Utils.replaceInString(title, "<BR/>", " ");
1381                     title = Utils.replaceInString(title, "<br/>", " ");
1382                     title = Utils.replaceInString(title, "<br>", " ");
1383                         title  = strip.stripHtml(nvl(title).trim());
1384                         //subtitle = Utils.replaceInString(subtitle, "<BR/>", " ");
1385                         //subtitle = Utils.replaceInString(subtitle, "<br/>", " ");
1386                         //subtitle = Utils.replaceInString(subtitle, "<br>", " ");
1387                         //subtitle  = strip.stripHtml(nvl(subtitle).trim());
1388                         StyleSheet styles = new StyleSheet();
1389                         
1390                         HTMLWorker htmlWorker = new HTMLWorker(document); 
1391                         ArrayList cc = new ArrayList(); 
1392                         cc = htmlWorker.parseToList(new StringReader(subtitle), styles); 
1393                                                 
1394                         Phrase p1 = new Phrase(); 
1395                         for (int i = 0; i < cc.size(); i++){ 
1396                                 Element elem = (Element)cc.get(i); 
1397                                 ArrayList al  = elem.getChunks();
1398                                 for (int j = 0; j < al.size(); j++) {
1399                                         Chunk chunk = (Chunk) al.get(j);
1400                                         chunk.font().setSize(6.0f);
1401                                 }
1402                                 p1.add(elem); 
1403                         } 
1404                         //cell = new PdfPCell(p1);
1405                 StyleSheet style = new StyleSheet();
1406                 style.loadTagStyle("font", "font-size", "3");
1407                 style.loadTagStyle("font", "size", "3");
1408             styles.loadStyle("pdfFont1", "size", "11px");                                 
1409             styles.loadStyle("pdfFont1", "font-size", "11px"); 
1410                 /*ArrayList p = HTMLWorker.parseToList(new StringReader(nvl(title)), style);
1411                 for (int k = 0; k < p.size(); ++k){
1412                         document.add((com.lowagie.text.Element)p.get(k));
1413                 }*/
1414             //p1.font().setSize(3.0f);
1415                         PdfPCell titleCell = new PdfPCell(new Phrase(title, font));
1416                         titleCell.setColspan(rr.getVisibleColumnCount());
1417                         PdfPCell subtitleCell = new PdfPCell(p1);
1418                         subtitleCell.setColspan(rr.getVisibleColumnCount());
1419                         titleCell.setHorizontalAlignment(1);
1420                         subtitleCell.setHorizontalAlignment(1);
1421                         table.addCell(titleCell);
1422                         table.addCell(subtitleCell);
1423                         //document.add(table);
1424                 }
1425                 return table;
1426         }
1427
1428
1429         private void paintPdfReportFooter(HttpServletRequest request, Document document, ReportRuntime rr, float[] f) 
1430                         throws DocumentException, IOException {
1431                 
1432                 HttpSession session = request.getSession();
1433                 String drilldown_index = (String) session.getAttribute("drilldown_index");
1434                 int index = 0;
1435                 try {
1436                  index = Integer.parseInt(drilldown_index);
1437                 } catch (NumberFormatException ex) {
1438                         index = 0;
1439                 }
1440
1441                 String title = (String) session.getAttribute("FOOTER_"+index);
1442                 if(nvl(title).length()>0) {
1443                         PdfPTable table = new PdfPTable(1);
1444                         table.setWidthPercentage(100f);
1445                         table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1446                         table.getDefaultCell().setVerticalAlignment(Rectangle.ALIGN_BOTTOM);
1447                 
1448                         Font font = FontFactory.getFont(FONT_FAMILY, 
1449                                         FONT_SIZE-3f,
1450                                         Font.BOLD, 
1451                                         Color.BLACK);
1452                 
1453                         
1454                         //addEmptyRows(table,1);
1455                         table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1456                         //table.getDefaultCell().setBackgroundColor(Color.decode(Globals.getDataTableHeaderBackgroundFontColor()));
1457                     /*title = Utils.replaceInString(title, "<BR/>", " ");
1458                     title = Utils.replaceInString(title, "<br/>", " ");
1459                     title = Utils.replaceInString(title, "<br>", " ");
1460                         title  = strip.stripHtml(nvl(title).trim());*/
1461                 StyleSheet style = new StyleSheet();
1462                 
1463                         HTMLWorker htmlWorker = new HTMLWorker(document); 
1464                         ArrayList cc = new ArrayList(); 
1465                         cc = htmlWorker.parseToList(new StringReader(title), style); 
1466                                                 
1467                         Phrase p1 = new Phrase(); 
1468                         for (int i = 0; i < cc.size(); i++){ 
1469                                 Element elem = (Element)cc.get(i); 
1470                                 ArrayList al  = elem.getChunks();
1471                                 for (int j = 0; j < al.size(); j++) {
1472                                         Chunk chunk = (Chunk) al.get(j);
1473                                         chunk.font().setSize(6.0f);
1474                                 }
1475                                 p1.add(elem); 
1476                         } 
1477                 
1478 /*                      
1479                         HTMLWorker.parseToList(new StringReader(nvl(title)), style);*/
1480                         PdfPCell titleCell = new PdfPCell(p1);
1481                         titleCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1482                         table.addCell(titleCell);
1483                         //table.
1484                         document.add(table);
1485                 }
1486                 //return table;
1487         }
1488         
1489         
1490         private void paintPdfTableHeader(Document document, ReportData rd, PdfPTable table) 
1491                                                                                                                                 throws DocumentException {
1492                         
1493                 Font font = FontFactory.getFont(FONT_FAMILY, 
1494                                                                                 FONT_SIZE+1f,
1495                                                                                 Font.BOLD, 
1496                                                                                 Color.decode(Globals.getDataTableHeaderFontColor()));
1497                 //table.setHeaderRows(1);
1498                 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1499                 table.getDefaultCell().setBackgroundColor(Color.decode(Globals.getDataTableHeaderBackgroundFontColor()));
1500                 String title = "";
1501                 
1502                 boolean firstPass = true;
1503                 
1504                 /*if(rd.reportTotalRowHeaderCols!=null) {
1505                         if(firstPass) {
1506                                 table.addCell(new Paragraph("No.", font));
1507                                 firstPass = false;
1508                         }
1509                 }*/             
1510                 for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) 
1511                 {
1512                         if(firstPass) {
1513                                 for(rd.reportRowHeaderCols.resetNext();rd.reportRowHeaderCols.hasNext();) {
1514                                         /*if(firstPass) {
1515                                                 table.addCell(new Paragraph("No.", font));
1516                                                 firstPass = false;
1517                                         } else {*/
1518                                                 RowHeaderCol rhc = rd.reportRowHeaderCols.getNext();
1519                                                 title = rhc.getColumnTitle();
1520                                         title = Utils.replaceInString(title,"_nl_", " \n");
1521                                                 table.addCell(new Paragraph(title,font));
1522                                         //}
1523                                 }
1524                         }
1525                         
1526                         ColumnHeaderRow chr = rd.reportColumnHeaderRows.getNext();
1527                         for (chr.resetNext(); chr.hasNext();) {
1528                                 ColumnHeader ch = chr.getNext();
1529                                 //System.out.println(ch);
1530                                 if(ch.isVisible()) {
1531                                         title = ch.getColumnTitle();
1532                                 title = Utils.replaceInString(title,"_nl_", " \n");
1533                                         table.addCell(new Paragraph(title,font));
1534                                 }
1535                         }
1536                 }
1537         }
1538         
1539         public static String currentTime(String pattern) {
1540                 try {
1541                 SimpleDateFormat oracleDateFormat = new SimpleDateFormat("MM/dd/yyyy kk:mm:ss");
1542                 Date sysdate = oracleDateFormat.parse(ReportLoader.getSystemDateTime());
1543                 SimpleDateFormat dtimestamp = new SimpleDateFormat(Globals.getScheduleDatePattern());
1544                 return dtimestamp.format(sysdate)+" "+Globals.getTimeZone();
1545                 //paramList.add(new IdNameValue("DATE", dtimestamp.format(sysdate)+" "+Globals.getTimeZone()));
1546         } catch(Exception ex) {}         
1547                 
1548                 SimpleDateFormat s = new SimpleDateFormat(pattern);
1549                 s.setTimeZone(TimeZone.getTimeZone(Globals.getTimeZone()));
1550                 //System.out.println("^^^^^^^^^^^^^^^^^^^^ " + Calendar.getInstance().getTime());
1551                 //System.out.println("^^^^^^^^^^^^^^^^^^^^ " + s.format(Calendar.getInstance().getTime()));
1552                 return s.format(Calendar.getInstance().getTime());
1553         }
1554
1555         private PdfBean preparePdfBean(HttpServletRequest request,ReportRuntime rr) {
1556                 PdfBean pb = new PdfBean();
1557
1558                 pb.setUserId(AppUtils.getUserID(request));
1559
1560                 pb.setWhereToShowPageNumber(Globals.getPageNumberPosition());
1561                 pb.setAlternateColor(Globals.isDataAlternateColor());
1562                 pb.setTimestampPattern(Globals.getDatePattern());
1563
1564                 int temp = -1;
1565                 try {
1566                         temp = Integer.parseInt(request.getParameter(AppConstants.RI_NEXT_PAGE));
1567                 } catch (NumberFormatException e) {}            
1568                 pb.setCurrentPage(temp);
1569         
1570                 //pb.setPortrait( trueORfalse(request.getParameter("isPortrait"),true));
1571                 pb.setPortrait(trueORfalse(rr.getPDFOrientation() == "portait"?"true":"false", true));
1572                 //pb.setCoverPageIncluded( trueORfalse(request.getParameter("isCoverPageIncluded"), true));
1573                 //if(Globals.isCoverPageNeeded()) {
1574                         pb.setCoverPageIncluded(Globals.isCoverPageNeeded()?rr.isPDFCoverPage():false);
1575                 //}
1576                 pb.setTitle(nvl(request.getParameter("title")));
1577                 pb.setPagesize(nvls(request.getParameter("pagesize"),"LETTER"));
1578                 
1579                 pb.setLogo1Url(rr.getPDFLogo1());
1580                 pb.setLogo2Url(rr.getPDFLogo2());
1581                 pb.setLogo1Size(rr.getPDFLogo1Size());
1582                 pb.setLogo2Size(rr.getPDFLogo2Size());
1583                 pb.setFullWebContextPath(request.getSession().getServletContext().getRealPath(File.separator));
1584                 
1585
1586                 pb.setDisplayChart(nvl(rr.getChartType()).trim().length()>0 && rr.getDisplayChart());
1587                         
1588                 String id = nvl(request.getParameter("pdfAttachmentKey")).trim();
1589                 String log_id = nvl(request.getParameter("log_id")).trim();
1590                 if(id.length()>0 && log_id.length()>0)
1591                         pb.setAttachmentOfEmail(true);
1592                 
1593                 return pb;
1594         }
1595         
1596         private boolean trueORfalse(String str) {
1597                 return (str != null) && (str.equalsIgnoreCase("true"));
1598         }
1599         
1600         private boolean trueORfalse(String str,boolean b_default) {
1601                 return str==null ? b_default : (str.equalsIgnoreCase("true"));
1602         }
1603         
1604    
1605 }