1ff21200ee70e79194a8208f787074e51cb01698
[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.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
537                         table.addCell(cellValue);
538                         document.add(table);
539                         }
540                 }
541         }
542         
543         private ArrayList getImage(HttpServletRequest request, String fileName, boolean isGenerateNewImage, ReportRuntime rr) {
544                 ArrayList images = new ArrayList();
545                 if(!isGenerateNewImage) {
546                         try {
547                                 Image image = Image.getInstance(fileName);
548                                 images.add(image);
549                                 return images;
550                         } 
551                         catch (MalformedURLException e) {
552                                 isGenerateNewImage = true;
553                     logger.error(EELFLoggerDelegate.errorLogger, "MalformedURLException in getImage", e);
554                         } 
555                         catch (BadElementException e) {
556                                 isGenerateNewImage = true;
557                     logger.error(EELFLoggerDelegate.errorLogger, "BadElementException in getImage", e);
558                         } catch (FileNotFoundException e) {
559                                 isGenerateNewImage = true;
560                 logger.error(EELFLoggerDelegate.errorLogger, "FileNotFoundException in getImage", e);
561                         } catch (IOException e) {
562                                 isGenerateNewImage = true;
563                 logger.error(EELFLoggerDelegate.errorLogger, "IOException in getImage", e);
564                     }                   
565                 }
566                 
567                 if(isGenerateNewImage && retryCreateNewImageCount<RetryCreateNewImage){
568                         retryCreateNewImageCount++;
569                         return generateNewImage(request, rr);
570                 }
571                 
572                 return null;
573                         
574         }
575
576         private ArrayList generateNewImage(HttpServletRequest request, ReportRuntime rr) {
577                 ArrayList images = new ArrayList();
578                 final String MALFORMEDURLEXCEPTION_MSG = "MalformedURLException in generateNewImage";
579                 final String BADELEMENTEXCEPTION_MSG = "BadElementException in generateNewImage";
580                 final String FILENOTFOUNDEXCEPTION_MSG = "FileNotFoundException in generateNewImage";
581                 final String IOEXCEPTION_MSG = "IOException in generateNewImage";
582                 try {
583                         //ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
584                         DataSet ds = null;
585                         if(request.getSession().getAttribute(AppConstants.RI_CHART_DATA)!=null) {
586                                 ds = (DataSet) request.getSession().getAttribute(AppConstants.RI_CHART_DATA);
587                         } else {
588                                 ds = rr.loadChartData(pb.getUserId(),request);
589                         }
590                     String downloadFileName = "";
591                         HashMap additionalChartOptionsMap = new HashMap();
592                         String chartType = nvl(rr.getChartType());
593                         if(chartType.equals(AppConstants.GT_PIE_MULTIPLE)) {
594                                 additionalChartOptionsMap.put("multiplePieOrderRow", new Boolean((AppUtils.getRequestNvlValue(request, "multiplePieOrder").length()>0?AppUtils.getRequestNvlValue(request, "multiplePieOrder").equals("row"):rr.isMultiplePieOrderByRow())) );
595                                 additionalChartOptionsMap.put("multiplePieLabelDisplay", AppUtils.getRequestNvlValue(request, "multiplePieLabelDisplay").length()>0? AppUtils.getRequestNvlValue(request, "multiplePieLabelDisplay"):rr.getMultiplePieLabelDisplay());
596                                 additionalChartOptionsMap.put("chartDisplay", new Boolean(AppUtils.getRequestNvlValue(request, "chartDisplay").length()>0? AppUtils.getRequestNvlValue(request, "chartDisplay").equals("3D"):rr.isChartDisplayIn3D()));
597                         } else if (chartType.equals(AppConstants.GT_BAR_3D)) {
598                                 additionalChartOptionsMap.put("chartOrientation", new Boolean((AppUtils.getRequestNvlValue(request, "chartOrientation").length()>0?AppUtils.getRequestNvlValue(request, "chartOrientation").equals("vertical"):rr.isVerticalOrientation())) );
599                                 additionalChartOptionsMap.put("secondaryChartRenderer", AppUtils.getRequestNvlValue(request, "secondaryChartRenderer").length()>0? AppUtils.getRequestNvlValue(request, "secondaryChartRenderer"):rr.getSecondaryChartRenderer());
600                                 additionalChartOptionsMap.put("chartDisplay", new Boolean(AppUtils.getRequestNvlValue(request, "chartDisplay").length()>0? AppUtils.getRequestNvlValue(request, "chartDisplay").equals("3D"):rr.isChartDisplayIn3D()));
601                                 additionalChartOptionsMap.put("lastSeriesALineChart", new Boolean(rr.isLastSeriesALineChart()));                
602                         } else if (chartType.equals(AppConstants.GT_LINE)) {
603                                 additionalChartOptionsMap.put("chartOrientation", new Boolean((AppUtils.getRequestNvlValue(request, "chartOrientation").length()>0?AppUtils.getRequestNvlValue(request, "chartOrientation").equals("vertical"):rr.isVerticalOrientation())) );
604                                 //additionalChartOptionsMap.put("secondaryChartRenderer", AppUtils.getRequestNvlValue(request, "secondaryChartRenderer").length()>0? AppUtils.getRequestNvlValue(request, "secondaryChartRenderer"):rr.getSecondaryChartRenderer());
605                                 additionalChartOptionsMap.put("chartDisplay", new Boolean(AppUtils.getRequestNvlValue(request, "chartDisplay").length()>0? AppUtils.getRequestNvlValue(request, "chartDisplay").equals("3D"):rr.isChartDisplayIn3D()));
606                                 additionalChartOptionsMap.put("lastSeriesABarChart", new Boolean(rr.isLastSeriesABarChart()));
607                         } else if (chartType.equals(AppConstants.GT_TIME_DIFFERENCE_CHART)) {
608                                 additionalChartOptionsMap.put("intervalFromDate",AppUtils.getRequestNvlValue(request, "intervalFromDate").length()>0?AppUtils.getRequestNvlValue(request, "intervalFromDate"):rr.getIntervalFromdate());
609                                 additionalChartOptionsMap.put("intervalToDate", AppUtils.getRequestNvlValue(request, "intervalToDate").length()>0? AppUtils.getRequestNvlValue(request, "intervalToDate"):rr.getIntervalTodate());
610                                 additionalChartOptionsMap.put("intervalLabel", AppUtils.getRequestNvlValue(request, "intervalLabel").length()>0? AppUtils.getRequestNvlValue(request, "intervalLabel"):rr.getIntervalLabel());
611                         } else if (chartType.equals(AppConstants.GT_REGRESSION)) {
612                                 additionalChartOptionsMap.put("regressionType",AppUtils.getRequestNvlValue(request, "regressionType").length()>0?AppUtils.getRequestNvlValue(request, "regressionType"):rr.getLinearRegression());
613                                 additionalChartOptionsMap.put("linearRegressionColor",nvl(rr.getLinearRegressionColor()));
614                                 additionalChartOptionsMap.put("expRegressionColor",nvl(rr.getExponentialRegressionColor()));
615                                 additionalChartOptionsMap.put("maxRegression",nvl(rr.getCustomizedRegressionPoint()));
616                         } else if (chartType.equals(AppConstants.GT_STACK_BAR) ||chartType.equals(AppConstants.GT_STACKED_HORIZ_BAR) || chartType.equals(AppConstants.GT_STACKED_HORIZ_BAR_LINES)
617                            || chartType.equals(AppConstants.GT_STACKED_VERT_BAR) || chartType.equals(AppConstants.GT_STACKED_VERT_BAR_LINES)    
618                         ) {
619                                 additionalChartOptionsMap.put("overlayItemValue",new Boolean(nvl(rr.getOverlayItemValueOnStackBar()).equals("Y")));
620                         }
621                         additionalChartOptionsMap.put("legendPosition", nvl(rr.getLegendPosition()));
622                         additionalChartOptionsMap.put("hideToolTips", new Boolean(rr.hideChartToolTips()));
623                         additionalChartOptionsMap.put("hideLegend", new Boolean(AppUtils.getRequestNvlValue(request, "hideLegend").length()>0? AppUtils.getRequestNvlValue(request, "hideLegend").equals("Y"):rr.hideChartLegend()));
624                         additionalChartOptionsMap.put("labelAngle", nvl(rr.getLegendLabelAngle()));
625                         additionalChartOptionsMap.put("maxLabelsInDomainAxis", nvl(rr.getMaxLabelsInDomainAxis()));
626                         additionalChartOptionsMap.put("rangeAxisLowerLimit", nvl(rr.getRangeAxisLowerLimit()));
627                         additionalChartOptionsMap.put("rangeAxisUpperLimit", nvl(rr.getRangeAxisUpperLimit()));
628                         
629                     
630                         boolean totalOnChart = false;
631                         totalOnChart = AppUtils.getRequestNvlValue(request, "totalOnChart").equals("Y");
632                         String filename  = null;
633                         ArrayList graphURL  = new ArrayList();
634                         ArrayList chartNames = new ArrayList();
635                         ArrayList fileNames = new ArrayList(); 
636                     List l = rr.getAllColumns();
637                     List lGroups = rr.getAllChartGroups();
638                     HashMap mapYAxis = rr.getAllChartYAxis(rr.getReportParamValues());
639                     String chartLeftAxisLabel = rr.getFormFieldFilled(nvl(rr.getChartLeftAxisLabel()));
640                 String chartRightAxisLabel = rr.getFormFieldFilled(nvl(rr.getChartRightAxisLabel()));
641                     int displayTotalOnChart = 0;
642                     HashMap formValues = Globals.getRequestParamtersMap(request, false);
643
644                     for (Iterator iterC = l.iterator(); iterC.hasNext();) {
645                                 DataColumnType dc = (DataColumnType) iterC.next();
646                                 if(nvl(dc.getColName()).equals(AppConstants.RI_CHART_TOTAL_COL)) {
647                                         displayTotalOnChart = 1;
648                                 }
649                         }
650                     
651                     String legendColumnName = (rr.getChartLegendColumn()!=null)?rr.getChartLegendColumn().getDisplayName():"Legend Column";
652                     
653                     
654                     
655                         if(ds!=null)
656                         {
657                                    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**/
658                                 for (int i=0; i<rr.getChartValueColumnAxisList(AppConstants.CHART_ALL_COLUMNS, formValues).size();i++) {
659                                 String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():"";
660                                 chartTitle = rr.getFormFieldFilled(chartTitle);
661                                                 downloadFileName = AppUtils.getTempFolderPath()+"cr_"+pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png";
662                                                 filename = null;
663                         try {
664                             Image image = Image.getInstance(downloadFileName);
665                             images.add(image);
666                         } catch (MalformedURLException e) {
667                             logger.error(EELFLoggerDelegate.errorLogger, MALFORMEDURLEXCEPTION_MSG,
668                                     e);
669                         } catch (BadElementException e) {
670                             logger.error(EELFLoggerDelegate.errorLogger, BADELEMENTEXCEPTION_MSG,
671                                     e);
672                         } catch (FileNotFoundException e) {
673                             logger.error(EELFLoggerDelegate.errorLogger, FILENOTFOUNDEXCEPTION_MSG,
674                                     e);
675                         } catch (IOException e) {
676                             logger.error(EELFLoggerDelegate.errorLogger, IOEXCEPTION_MSG, e);
677                         }
678                                 }
679                                            
680                                    } else { /** first check the columns to be opened in new charts and loop around in ChartGen generate chart function  - sundar**/
681                             String tempChartGroupPrev = "";
682                                         String tempChartGroupCurrent = "";
683                                 for (int i=0; i<lGroups.size();i++) {
684                                         String chartGroupOrg = (String) lGroups.get(i);
685                                         String chartYAxis = (String) mapYAxis.get(chartGroupOrg);
686                                         if(nvl(chartGroupOrg).length()>0)
687                                                 tempChartGroupCurrent = chartGroupOrg.substring(0,chartGroupOrg.lastIndexOf("|"));
688                                         if(i>0)
689                                                                 tempChartGroupPrev = ((String) lGroups.get(i-1)).substring(0,((String) lGroups.get(i-1)).lastIndexOf("|"));
690                                         if(tempChartGroupCurrent.equals(tempChartGroupPrev))
691                                                                 continue;
692                                         String chartGroup = chartGroupOrg;
693                                         
694                                                         downloadFileName = AppUtils.getTempFolderPath()+"cr_"+pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png";
695                                                         String chartTitle = (Globals.getDisplayChartTitle()? (chartGroup!=null && chartGroup.indexOf("|") > 0 ?chartGroup.substring(0,chartGroup.lastIndexOf("|")):rr.getReportName()):"");
696                                                         chartTitle = rr.getFormFieldFilled(chartTitle);
697                                                         String leftAxisLabel = "";
698                                                           if(!rr.isMultiSeries()) {
699                                                                 leftAxisLabel = ((chartYAxis!=null && chartYAxis.indexOf("|") > 0) ? chartYAxis.substring(0,chartYAxis.lastIndexOf("|")): chartLeftAxisLabel );
700                                                         } else {
701                                                                 leftAxisLabel = chartLeftAxisLabel;
702                                                         }
703
704                                                 filename = null;
705                         try {
706                             Image image = Image.getInstance(downloadFileName);
707                             images.add(image);
708                         } catch (MalformedURLException e) {
709                             logger.error(EELFLoggerDelegate.errorLogger, MALFORMEDURLEXCEPTION_MSG,
710                                     e);
711                         } catch (BadElementException e) {
712                             logger.error(EELFLoggerDelegate.errorLogger, BADELEMENTEXCEPTION_MSG,
713                                     e);
714                         } catch (FileNotFoundException e) {
715                             logger.error(EELFLoggerDelegate.errorLogger, FILENOTFOUNDEXCEPTION_MSG,
716                                     e);
717                         } catch (IOException e) {
718                             logger.error(EELFLoggerDelegate.errorLogger, IOEXCEPTION_MSG, e);
719                         }
720                                                 }
721                                            
722                             if(!chartType.equals(AppConstants.GT_PIE_MULTIPLE)) {    
723                         for (int i=0; i<rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).size();i++) { 
724
725                                                 downloadFileName = AppUtils.getTempFolderPath()+"cr_"+ pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png";
726                                 String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():"";
727                                 chartTitle = rr.getFormFieldFilled(chartTitle);
728
729                         filename = null; /*(String) ChartGen.generateChart(  chartType,
730                                                                                                         request.getSession(),
731                                                                                                         ds,
732                                                                                                         legendColumnName, 
733                                                                                                         chartLeftAxisLabel,
734                                                                                                         chartRightAxisLabel,
735                                                                                                         (chartType.equals(AppConstants.GT_PIE_MULTIPLE))?rr.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartDisplayNamesList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).subList(i, i+1), 
736                                                                                                         (chartType.equals(AppConstants.GT_PIE_MULTIPLE))?rr.getChartColumnColorsList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartColumnColorsList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).subList(i, i+1), 
737                                                                                                         (chartType.equals(AppConstants.GT_PIE_MULTIPLE))?rr.getChartValueColumnAxisList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).subList(i, i+1), 
738                                                                                                         "",
739                                                                                                         chartTitle,
740                                                                                                         null,
741                                                                                                         rr.getChartWidthAsInt(),
742                                                                                                         rr.getChartHeightAsInt(),
743                                                                         rr.getChartValueColumnsList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).subList(i,i+1),
744                                                                                     rr.hasSeriesColumn(),
745                                                                                     //rr.isChartMultiSeries(),
746                                                                                     rr.isMultiSeries(),
747                                                                                     rr.getAllColumns(),
748                                                                         downloadFileName,
749                                                                         totalOnChart, 
750                                                                         AppConstants.WEB_VERSION, 
751                                                                         additionalChartOptionsMap,
752                                                                         true
753                                           );*/
754                             try {
755                                 Image image = Image.getInstance(downloadFileName);
756                                 images.add(image);
757                             } catch (MalformedURLException e) {
758                                 logger.error(EELFLoggerDelegate.errorLogger,
759                                         MALFORMEDURLEXCEPTION_MSG, e);
760                             } catch (BadElementException e) {
761                                 logger.error(EELFLoggerDelegate.errorLogger,
762                                         BADELEMENTEXCEPTION_MSG, e);
763                             } catch (FileNotFoundException e) {
764                                 logger.error(EELFLoggerDelegate.errorLogger,
765                                         FILENOTFOUNDEXCEPTION_MSG, e);
766                             } catch (IOException e) {
767                                 logger.error(EELFLoggerDelegate.errorLogger, IOEXCEPTION_MSG, e);
768                             }
769                         }
770                             }
771                         /** second rest of the columns are merged to one single chart  - sundar**/
772                                           // System.out.println(" rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS) " + rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS));
773                                           // System.out.println(" rr.getChartValueColumnAxisList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS) " + rr.getChartValueColumnAxisList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS));
774                                           // System.out.println(" rr.getChartValueColumnsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS) " + rr.getChartValueColumnsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS));
775
776                                           if((!(lGroups!=null && lGroups.size() > 0))) {
777                                                   
778                                            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) {
779                         downloadFileName = AppUtils.getTempFolderPath()+"cr_"+  pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_All.png";
780                         String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():"";
781                         chartTitle = rr.getFormFieldFilled(chartTitle);
782
783                         filename = null; /*(String) ChartGen.generateChart(  chartType,
784                                                                                                         request.getSession(),
785                                                                                                         ds,
786                                                                                                         legendColumnName, 
787                                                                                                         chartLeftAxisLabel,
788                                                                                                         chartRightAxisLabel,
789                                                                                                         rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues), 
790                                                                                                         rr.getChartColumnColorsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues), 
791                                                                                                         rr.getChartValueColumnAxisList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues), 
792                                                                                                         "",
793                                                                                                         chartTitle,
794                                                                                                         null,
795                                                                                                         rr.getChartWidthAsInt(),
796                                                                                                         rr.getChartHeightAsInt(),
797                                                                         rr.getChartValueColumnsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues),
798                                                                                     rr.hasSeriesColumn(),
799                                                                                   //rr.isChartMultiSeries(),
800                                                                                     rr.isMultiSeries(),
801                                                                                     rr.getAllColumns(),
802                                                                         downloadFileName,
803                                                                         totalOnChart, 
804                                                                         AppConstants.WEB_VERSION, 
805                                                                         additionalChartOptionsMap,
806                                                                         true
807                                           );*/
808                             try {
809                                 Image image = Image.getInstance(downloadFileName);
810                                 images.add(image);
811                             } catch (MalformedURLException e) {
812                                 logger.error(EELFLoggerDelegate.errorLogger,
813                                         MALFORMEDURLEXCEPTION_MSG, e);
814                             } catch (BadElementException e) {
815                                 logger.error(EELFLoggerDelegate.errorLogger,
816                                         BADELEMENTEXCEPTION_MSG, e);
817                             } catch (FileNotFoundException e) {
818                                 logger.error(EELFLoggerDelegate.errorLogger,
819                                         FILENOTFOUNDEXCEPTION_MSG, e);
820                             } catch (IOException e) {
821                                 logger.error(EELFLoggerDelegate.errorLogger, IOEXCEPTION_MSG, e);
822                             }
823                         }
824                     } // Stacked Chart Check
825                 } // else no Series Column
826
827             } // if(ds!=null)
828
829         } catch (Exception e) {
830             logger.error(EELFLoggerDelegate.errorLogger, "Exception in generateNewImage", e);
831         }
832                 return images.size()>0?images:null;
833                 
834         }
835
836
837         private final int DEFAULT_PDF_DISPLAY_WIDTH = 10;
838
839     private int paintPdfData(final HttpServletRequest request, final Document document, final ReportData rd,
840         final ReportRuntime rr, final String sql_whole) throws DocumentException, RaptorException, IOException {
841
842         final int mb = 1024 * 1024;
843         final Runtime runtime = Runtime.getRuntime();
844         int returnValue = 0;
845
846         final float f[] = getRelativeWidths(rd, AppConstants.RT_CROSSTAB.equals(rr.getReportType()));
847         PdfPTable table = new PdfPTable(f);
848         table.setWidthPercentage(100f);
849         table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
850         table.getDefaultCell().setVerticalAlignment(Rectangle.ALIGN_BOTTOM);
851
852         final ReportDefinition rdef = (new ReportHandler()).loadReportDefinition(request, rr.getReportID());
853
854         final List allColumns = rdef.getAllColumns();
855
856         final float[] repotWidths = new float[rdef.getVisibleColumnCount()];
857         int columnIdx = 0;
858         float pdfDisplayWidth = 0;
859         for (final Iterator iter = allColumns.iterator(); iter.hasNext(); ) {
860             final DataColumnType dct = (DataColumnType) iter.next();
861             if (dct.isVisible()) {
862
863                 if (dct.getPdfDisplayWidthInPxls() == null || dct.getPdfDisplayWidthInPxls().isEmpty() || dct
864                     .getPdfDisplayWidthInPxls().startsWith("null")) {
865                     pdfDisplayWidth = DEFAULT_PDF_DISPLAY_WIDTH;
866                 } else {
867                     pdfDisplayWidth = Float.parseFloat(dct.getPdfDisplayWidthInPxls());
868                 }
869
870                 repotWidths[columnIdx++] = pdfDisplayWidth;
871             }
872         }
873
874         table.setWidths(repotWidths);
875
876         //TODO: check title and subtitle
877         final HttpSession session = request.getSession();
878         final String drilldown_index = (String) session.getAttribute("drilldown_index");
879         int index = 0;
880         try {
881             index = Integer.parseInt(drilldown_index);
882         } catch (NumberFormatException ex) {
883             index = 0;
884         }
885         final String titleRep = (String) session.getAttribute("TITLE_" + index);
886         final String subtitle = (String) session.getAttribute("SUBTITLE_" + index);
887
888         if (nvl(titleRep).length() > 0 && nvl(subtitle).length() > 0) {
889             table.setHeaderRows(3);
890         } else if (nvl(titleRep).length() > 0) {
891             table.setHeaderRows(2);
892         } else {
893             table.setHeaderRows(1);
894         }
895         table = paintPdfReportHeader(request, document, table, rr, f);
896         paintPdfTableHeader(document, rd, table);
897
898         int idx = 0;
899         final int fragmentsize = 30; //for memory management
900
901         rd.reportDataRows.resetNext();
902         DataRow dr = rd.reportDataRows.getNext();
903
904         if (nvl(sql_whole).length() > 0 && AppConstants.RT_LINEAR.equals(rr.getReportType())) {
905             try (final Connection conn = ConnectionUtils.getConnection(rr.getDbInfo());
906                 final Statement st = conn.createStatement();
907                 final ResultSet rs = st.executeQuery(sql_whole);) {
908
909                 logger.debug(EELFLoggerDelegate.debugLogger, ("************* Map Whole SQL *************"));
910                 logger.debug(EELFLoggerDelegate.debugLogger, (sql_whole));
911                 logger.debug(EELFLoggerDelegate.debugLogger, ("*****************************************"));
912
913                 final ResultSetMetaData rsmd = rs.getMetaData();
914                 final int numberOfColumns = rsmd.getColumnCount();
915                 dr = null;
916                 int rowCount = 0;
917                 while (rs.next()) {
918
919                     rowCount++;
920                     final Map colHash = new HashMap();
921                     for (int i = 1; i <= numberOfColumns; i++) {
922                         colHash.put(rsmd.getColumnLabel(i).toUpperCase(), rs.getString(i));
923                     }
924                     rd.reportDataRows.resetNext();
925
926                     dr = rd.reportDataRows.getNext();
927
928                     for (dr.resetNext(); dr.hasNext(); ) {
929                         final DataValue dv = dr.getNext();
930
931                         final String value = nvl((String) colHash.get(dv.getColId().toUpperCase()));
932                         if (dv.isVisible()) {
933
934                             final HtmlFormatter cfmt = dv.getCellFormatter();
935                             final HtmlFormatter rfmt = dv.getRowFormatter();
936
937                             final Font cellFont = FontFactory.getFont(FONT_FAMILY,
938                                 FONT_SIZE,
939                                 Font.NORMAL, Color.BLACK);
940                             if (cfmt != null) {
941                                 cellFormatterFont(cfmt, cellFont);
942                             } else if (rfmt != null) {
943                                 cellFormatterFont(rfmt, cellFont);
944                             } else {
945                                 if (dv.isBold()) {
946                                     cellFont.setStyle(Font.BOLD);
947                                 }
948                             }
949
950                             final String cellValue = strip.stripHtml(value.trim());
951                             final PdfPCell cell = new PdfPCell(new Paragraph(cellValue, cellFont));
952
953                             //row background color can be overwritten by cell background color
954                             cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
955
956                             if (nvl(dv.getAlignment()).trim().length() > 0) {
957                                 cell.setHorizontalAlignment(ElementTags.alignmentValue(dv.getAlignment()));
958                             } else {
959                                 cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
960                             }
961
962                             if (cfmt != null) {
963                                 formatterCell(cfmt, cell);
964                             } else if (rfmt != null) {
965                                 formatterCell(rfmt, cell);
966                             }
967
968                             table.addCell(cell);
969
970                         }//if isVisible()
971
972                     }
973
974                 }
975                 if (rd.reportDataTotalRow != null) {
976                     for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext(); idx++) {
977                         dr = rd.reportDataTotalRow.getNext();
978                         table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
979                         final Font rowHeaderFont = FontFactory.getFont(FONT_FAMILY,
980                             FONT_SIZE,
981                             Font.NORMAL, Color.BLACK);
982                         rowHeaderFont.setStyle(Font.BOLD);
983                         rowHeaderFont.setSize(FONT_SIZE + 1f);
984                         table.getDefaultCell().setBackgroundColor(getRowBackgroundColor(dr, idx));
985                         table.addCell(new Paragraph("Total", rowHeaderFont));
986
987                         addTotalRowColumns(table, dr, idx);
988                         if (idx % fragmentsize == fragmentsize - 1) {
989                             document.add(table);
990                             table.deleteBodyRows();
991                             table.setSkipFirstHeader(true);
992                         }
993
994                     }
995                 }
996             } catch (final SQLException | ReportSQLException ex) {
997                 throw new RaptorException(ex);
998             } catch (final Exception ex) {
999                 if (!(ex.getCause() instanceof java.net.SocketException)) {
1000                     throw new RaptorException(ex);
1001                 }
1002             }
1003             //document.add(table);
1004         } else {
1005             if (rr.getReportType().equals(AppConstants.RT_LINEAR)) {
1006                 for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext(); idx++) {
1007
1008                     if (runtime.freeMemory() / mb <= ((runtime.maxMemory() / mb) * Globals.getMemoryThreshold()
1009                         / 100)) {
1010                         returnValue = 1;
1011                     }
1012
1013                     dr = rd.reportDataRows.getNext();
1014
1015                     addRowHeader(table, dr, idx, rd);
1016
1017                     addRowColumns(table, dr, idx);
1018
1019                     if (idx % fragmentsize == fragmentsize - 1) {
1020                         document.add(table);
1021                         table.deleteBodyRows();
1022                         table.setSkipFirstHeader(true);
1023                     }
1024                 }
1025
1026                 if (rd.reportDataTotalRow != null) {
1027                     for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext(); idx++) {
1028                         dr = rd.reportDataTotalRow.getNext();
1029                         table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1030                         Font rowHeaderFont = FontFactory.getFont(FONT_FAMILY,
1031                             FONT_SIZE,
1032                             Font.NORMAL, Color.BLACK);
1033                         rowHeaderFont.setStyle(Font.BOLD);
1034                         rowHeaderFont.setSize(FONT_SIZE + 1f);
1035                         table.getDefaultCell().setBackgroundColor(getRowBackgroundColor(dr, idx));
1036                         table.addCell(new Paragraph("Total", rowHeaderFont));
1037
1038                         addTotalRowColumns(table, dr, idx);
1039                         if (idx % fragmentsize == fragmentsize - 1) {
1040                             document.add(table);
1041                             table.deleteBodyRows();
1042                             table.setSkipFirstHeader(true);
1043                         }
1044
1045                     }
1046                 }
1047
1048             } else if (AppConstants.RT_CROSSTAB.equals(rr.getReportType())) {
1049                 int rowCount = 0;
1050                 final List l = rd.getReportDataList();
1051                 boolean first = true;
1052                 for (int dataRow = 0; dataRow < l.size(); dataRow++) {
1053                     first = true;
1054                     rowCount++;
1055                     dr = (DataRow) l.get(dataRow);
1056                     final Vector<DataValue> rowNames = dr.getRowValues();
1057                     for (dr.resetNext(); dr.hasNext(); ) {
1058
1059                         if (first) {
1060                             HtmlFormatter rfmt = dr.getRowFormatter();
1061
1062                             Font cellFont = FontFactory.getFont(FONT_FAMILY,
1063                                 FONT_SIZE,
1064                                 Font.NORMAL, Color.BLACK);
1065                             if (rfmt != null) {
1066                                 cellFormatterFont(rfmt, cellFont);
1067                             }
1068
1069                             if (rowNames != null) {
1070                                 for (int i = 0; i < rowNames.size(); i++) {
1071                                     final DataValue dv = rowNames.get(i);
1072                                     rfmt = dr.getRowFormatter();
1073
1074                                     cellFont = FontFactory.getFont(FONT_FAMILY,
1075                                         FONT_SIZE,
1076                                         Font.NORMAL, Color.BLACK);
1077                                     if (rfmt != null) {
1078                                         cellFormatterFont(rfmt, cellFont);
1079                                     }
1080                                     String cellValue = dv.getDisplayValue();
1081                                     if (cellValue.indexOf("|#") != -1) {
1082                                         cellValue = cellValue.substring(0, cellValue.indexOf("|"));
1083                                     }
1084
1085                                     final PdfPCell cell = new PdfPCell(new Paragraph(cellValue, cellFont));
1086                                     //row background color can be overwritten by cell background color
1087                                     cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
1088
1089                                     cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1090
1091                                     if (rfmt != null) {
1092                                         formatterCell(rfmt, cell);
1093                                     }
1094                                     table.addCell(cell);
1095                                 }
1096                             }
1097                         }
1098                         first = false;
1099
1100                         if (runtime.freeMemory() / mb <= ((runtime.maxMemory() / mb) * Globals.getMemoryThreshold()
1101                             / 100)) {
1102                             returnValue = 1;
1103                         }
1104
1105                         //addRowHeader(table,dr,idx,rd);
1106
1107                         addRowColumns(table, dr, idx);
1108
1109                         if (idx % fragmentsize == fragmentsize - 1) {
1110                             document.add(table);
1111                             table.deleteBodyRows();
1112                             table.setSkipFirstHeader(true);
1113                         }
1114                     }
1115
1116                 }
1117             }
1118
1119             //document.add(table);
1120
1121         }
1122
1123         document.add(table);
1124         paintPdfReportFooter(request, document, rr, f);
1125
1126         return returnValue;
1127     }
1128
1129         private void addRowHeader(PdfPTable table, DataRow dr, int idx, ReportData rd) {
1130                 
1131                 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);  
1132
1133                 for(rd.reportRowHeaderCols.resetNext();rd.reportRowHeaderCols.hasNext();) {
1134                         RowHeaderCol rhc = rd.reportRowHeaderCols.getNext();
1135                         if(idx==0) 
1136                                 rhc.resetNext();
1137                         RowHeader rh = rhc.getNext();
1138                         //System.out.println(" =============== RowHeader\n "+rh);
1139                         
1140                         Font rowHeaderFont = FontFactory.getFont(FONT_FAMILY, 
1141                                                                                                         FONT_SIZE,
1142                                                                                                         Font.NORMAL, Color.BLACK);
1143                         if(rh.isBold()) {
1144                                 rowHeaderFont.setStyle(Font.BOLD);
1145                                 rowHeaderFont.setSize(FONT_SIZE+1f);
1146                         }
1147                         
1148                         if(rh.getColSpan()>0) {
1149                                 table.getDefaultCell().setColspan(rh.getColSpan());
1150                                 table.getDefaultCell().setBackgroundColor(getRowBackgroundColor(dr, idx));
1151                                 table.addCell(new Paragraph(strip.stripHtml(rh.getRowTitle()),rowHeaderFont));
1152                         }
1153                 }               
1154         }
1155
1156         private void addRowColumns(PdfPTable table, DataRow dr, int idx) {
1157                         
1158                 table.getDefaultCell().setColspan(1);
1159                         
1160                 for(dr.resetNext();dr.hasNext();)
1161                 {
1162                         DataValue dv = dr.getNext();
1163                         //System.out.println(columnCount +" --> "+dv);
1164                         if(dv.isVisible()) {
1165                                 HtmlFormatter cfmt = dv.getCellFormatter();
1166                                 HtmlFormatter rfmt = dv.getRowFormatter();
1167
1168                                 Font cellFont = FontFactory.getFont(FONT_FAMILY, 
1169                                                                                                         FONT_SIZE,
1170                                                                                                         Font.NORMAL, Color.BLACK);
1171                                 if(cfmt!= null) {
1172                                         cellFormatterFont(cfmt,cellFont);
1173                                 }
1174                                 else if(rfmt != null) {
1175                                         cellFormatterFont(rfmt,cellFont);
1176                                 }
1177                                 else {
1178                                         if(dv.isBold()) {
1179                                                 cellFont.setStyle(Font.BOLD);
1180                                         }
1181                                 }
1182                                 
1183                                 String cellValue = strip.stripHtml(dv.getDisplayValue().trim());
1184                                 PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont));
1185                                 
1186                                 //row background color can be overwritten by cell background color
1187                                 cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
1188                                 
1189                                 if(nvl(dv.getAlignment()).trim().length()>0)
1190                                         cell.setHorizontalAlignment(ElementTags.alignmentValue(dv.getAlignment()));
1191                                 else
1192                                         cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1193                                 
1194                                 if(cfmt!= null) {
1195                                         formatterCell(cfmt,cell);
1196                                 }
1197                                 else if(rfmt != null) {
1198                                         formatterCell(rfmt,cell);
1199                                 }
1200                                 
1201                                 table.addCell(cell);
1202                         
1203                         }//if isVisible()
1204                 }                                       
1205         }
1206
1207
1208         private void addTotalRowColumns(PdfPTable table, DataRow dr, int idx) {
1209                 
1210                 table.getDefaultCell().setColspan(1);
1211                 dr.resetNext();
1212                 dr.getNext();
1213                 for(;dr.hasNext();)
1214                 {
1215                         DataValue dv = dr.getNext();
1216                         //System.out.println(columnCount +" --> "+dv);
1217                         if(dv.isVisible()) {
1218                                 HtmlFormatter cfmt = dv.getCellFormatter();
1219                                 HtmlFormatter rfmt = dv.getRowFormatter();
1220
1221                                 Font cellFont = FontFactory.getFont(FONT_FAMILY, 
1222                                                                                                         FONT_SIZE,
1223                                                                                                         Font.NORMAL, Color.BLACK);
1224                                 if(cfmt!= null) {
1225                                         cellFormatterFont(cfmt,cellFont);
1226                                 }
1227                                 else if(rfmt != null) {
1228                                         cellFormatterFont(rfmt,cellFont);
1229                                 }
1230                                 else {
1231                                         if(dv.isBold()) {
1232                                                 cellFont.setStyle(Font.BOLD);
1233                                         }
1234                                 }
1235                                 
1236                                 String cellValue = strip.stripHtml(dv.getDisplayValue().trim());
1237                                 PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont));
1238                                 
1239                                 //row background color can be overwritten by cell background color
1240                                 cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
1241                                 
1242                                 if(nvl(dv.getAlignment()).trim().length()>0)
1243                                         cell.setHorizontalAlignment(ElementTags.alignmentValue(dv.getAlignment()));
1244                                 else
1245                                         cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1246                                 
1247                                 if(cfmt!= null) {
1248                                         formatterCell(cfmt,cell);
1249                                 }
1250                                 else if(rfmt != null) {
1251                                         formatterCell(rfmt,cell);
1252                                 }
1253                                 
1254                                 table.addCell(cell);
1255                         
1256                         }//if isVisible()
1257                 }                                       
1258         }
1259         
1260         
1261         private void formatterCell(HtmlFormatter fmt, PdfPCell cell) {
1262                 
1263                 if(nvl(fmt.getBgColor()).trim().length()>0)
1264                         cell.setBackgroundColor(Color.decode(fmt.getBgColor()));
1265                 if(nvl(fmt.getAlignment()).trim().length()>0)
1266                         cell.setHorizontalAlignment(ElementTags.alignmentValue(fmt.getAlignment()));
1267         }
1268
1269         private void cellFormatterFont(HtmlFormatter fmt, Font font) {
1270                 
1271                 if(fmt.isBold()) 
1272                         font.setStyle(Font.BOLD);
1273                 if(fmt.isItalic()) 
1274                         font.setStyle(Font.ITALIC);
1275                 if(fmt.isUnderline()) 
1276                         font.setStyle(Font.UNDERLINE);
1277                 if(fmt.getFontColor().trim().length()>0)
1278                         font.setColor(Color.decode(fmt.getFontColor()));
1279                 if(fmt.getFontSize().trim().length()>0)
1280                         font.setSize(Float.parseFloat(fmt.getFontSize())-Globals.getDataFontSizeOffset());
1281 //              if(fmt.getFontFace().trim().length()>0)
1282 //                      cellFont.setFamily()
1283                 
1284         }
1285
1286         private Color getRowBackgroundColor(DataRow dr, int idx) {
1287                 
1288                 Color color =  Color.decode(Globals.getDataDefaultBackgroundHexCode());
1289                 
1290                 HtmlFormatter rhf = dr.getRowFormatter();
1291                 if(rhf!=null && nvl(rhf.getBgColor()).trim().length()>0)
1292                         
1293                         color = Color.decode(rhf.getBgColor());
1294                 
1295                 else if(pb.isAlternateColor() && idx%2==0)
1296                         
1297                         color = Color.decode(Globals.getDataBackgroundAlternateHexCode());
1298                 
1299                 return color;           
1300
1301         }
1302
1303         private int getTotalVisbleColumns(ReportData rd) {
1304                 
1305                 int totalVisbleColumn = rd.getTotalColumnCount();
1306                 for(rd.reportDataRows.resetNext();rd.reportDataRows.hasNext();)
1307                 {       
1308                         DataRow dr = rd.reportDataRows.getNext();
1309                         for(dr.resetNext();dr.hasNext();) {
1310                                 DataValue dv = dr.getNext();
1311                                 if(!dv.isVisible())
1312                                     totalVisbleColumn--;
1313                         }
1314                         
1315                         break;
1316                 }
1317                 
1318                 return totalVisbleColumn;
1319         }
1320
1321         /*
1322         private int getFirstRowIndex(ReportRuntime rr) {
1323                 return (pb.getCurrentPage()>0)?pb.getCurrentPage()*rr.getPageSize()+1 : 1;
1324         }
1325         */
1326         private float[] getRelativeWidths(ReportData rd, boolean crosstab){
1327                 
1328                 int totalColumns = getTotalVisbleColumns(rd);
1329                 /*if(rd.reportTotalRowHeaderCols!=null) {
1330                         totalColumns += 1;
1331                 }*/
1332                 if(crosstab) {
1333                         totalColumns += 1;
1334                 }
1335
1336                 if(totalColumns == 0 )
1337                         totalColumns=1;
1338                 
1339                 float[] relativeWidths = new float[totalColumns];
1340                 //initial widths are even
1341                 for(int i=0; i<relativeWidths.length; i++)
1342                         relativeWidths[i] = 10f;
1343                 
1344                 int index=0;
1345                 boolean firstPass = true;
1346                 
1347                 for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) 
1348                 {
1349                         if(firstPass) {
1350                                 /*if(rd.reportTotalRowHeaderCols!=null) { 
1351                                         String columnWidth = "5";
1352                                         
1353                                         if(columnWidth != null && columnWidth.trim().endsWith("%"))
1354                                                 relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
1355                                         
1356                                         index++;
1357                                 }*/
1358                                 
1359                                 for(rd.reportRowHeaderCols.resetNext();rd.reportRowHeaderCols.hasNext();) {
1360                                         String columnWidth = rd.reportRowHeaderCols.getNext().getColumnWidth();
1361                                         
1362                                         if(columnWidth != null && columnWidth.trim().endsWith("%"))
1363                                                 relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
1364                                         
1365                                         index++;
1366                                 }
1367                                 firstPass = false;
1368                         }
1369                 
1370                         ColumnHeaderRow chr = rd.reportColumnHeaderRows.getNext();
1371                         for (chr.resetNext(); chr.hasNext();) {
1372                                 
1373                                 ColumnHeader ch = chr.getNext();
1374
1375                                 if(ch.isVisible()) {
1376                                         
1377                                         String columnWidth = ch.getColumnWidth();
1378                                         
1379                                         if(ch.getColSpan() <= 1){
1380                                                 if(columnWidth != null && columnWidth.trim().endsWith("%")) 
1381                                                         relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
1382                                         } 
1383                                         else {
1384                                                 for(int i=0; i<ch.getColSpan(); i++) {
1385                                                         index += i;
1386                                                         if(columnWidth != null && columnWidth.trim().endsWith("%"))
1387                                                                 relativeWidths[index] = 
1388                                                                         (Float.parseFloat(removeLastCharacter(columnWidth)))/ch.getColSpan();                                                   
1389                                                 }
1390                                         }
1391                                         
1392                                         index++;
1393                                 }
1394                         }
1395                 }
1396                 
1397                 return relativeWidths;
1398         }
1399         
1400         public static String removeLastCharacter(String str) {
1401                 return str.substring(0, str.length()-1);
1402         }
1403         
1404         private PdfPTable paintPdfReportHeader(HttpServletRequest request, Document document, PdfPTable table, ReportRuntime rr, float[] f) 
1405                         throws DocumentException, IOException {
1406                 
1407                 HttpSession session = request.getSession();
1408                 String drilldown_index = (String) session.getAttribute("drilldown_index");
1409                 int index = 0;
1410                 try {
1411                  index = Integer.parseInt(drilldown_index);
1412                 } catch (NumberFormatException ex) {
1413                         index = 0;
1414                 }
1415                 String title = (String) session.getAttribute("TITLE_"+index);
1416                 String subtitle = (String) session.getAttribute("SUBTITLE_"+index);
1417                 if(nvl(title).length()>0) {
1418                         //PdfPTable table = new PdfPTable(1);
1419                         table.setWidthPercentage(100f);
1420                         table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1421                         table.getDefaultCell().setVerticalAlignment(Rectangle.ALIGN_BOTTOM);
1422                 
1423         
1424                         Font font = FontFactory.getFont(FONT_FAMILY, 
1425                                         FONT_SIZE-2f,
1426                                         Font.BOLD, 
1427                                         Color.BLACK);
1428                 
1429                         //addEmptyRows(table,1);
1430                         table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1431                         //table.getDefaultCell().setBackgroundColor(Color.decode(Globals.getDataTableHeaderBackgroundFontColor()));
1432                     title = Utils.replaceInString(title, "<BR/>", " ");
1433                     title = Utils.replaceInString(title, "<br/>", " ");
1434                     title = Utils.replaceInString(title, "<br>", " ");
1435                         title  = strip.stripHtml(nvl(title).trim());
1436                         //subtitle = Utils.replaceInString(subtitle, "<BR/>", " ");
1437                         //subtitle = Utils.replaceInString(subtitle, "<br/>", " ");
1438                         //subtitle = Utils.replaceInString(subtitle, "<br>", " ");
1439                         //subtitle  = strip.stripHtml(nvl(subtitle).trim());
1440                         StyleSheet styles = new StyleSheet();
1441                         
1442                         HTMLWorker htmlWorker = new HTMLWorker(document); 
1443                         ArrayList cc = new ArrayList(); 
1444                         cc = htmlWorker.parseToList(new StringReader(subtitle), styles); 
1445                                                 
1446                         Phrase p1 = new Phrase(); 
1447                         for (int i = 0; i < cc.size(); i++){ 
1448                                 Element elem = (Element)cc.get(i); 
1449                                 ArrayList al  = elem.getChunks();
1450                                 for (int j = 0; j < al.size(); j++) {
1451                                         Chunk chunk = (Chunk) al.get(j);
1452                                         chunk.font().setSize(6.0f);
1453                                 }
1454                                 p1.add(elem); 
1455                         } 
1456                         //cell = new PdfPCell(p1);
1457                 StyleSheet style = new StyleSheet();
1458                 style.loadTagStyle("font", "font-size", "3");
1459                 style.loadTagStyle("font", "size", "3");
1460             styles.loadStyle("pdfFont1", "size", "11px");                                 
1461             styles.loadStyle("pdfFont1", "font-size", "11px"); 
1462                 /*ArrayList p = HTMLWorker.parseToList(new StringReader(nvl(title)), style);
1463                 for (int k = 0; k < p.size(); ++k){
1464                         document.add((com.lowagie.text.Element)p.get(k));
1465                 }*/
1466             //p1.font().setSize(3.0f);
1467                         PdfPCell titleCell = new PdfPCell(new Phrase(title, font));
1468                         titleCell.setColspan(rr.getVisibleColumnCount());
1469                         PdfPCell subtitleCell = new PdfPCell(p1);
1470                         subtitleCell.setColspan(rr.getVisibleColumnCount());
1471                         titleCell.setHorizontalAlignment(1);
1472                         subtitleCell.setHorizontalAlignment(1);
1473                         table.addCell(titleCell);
1474                         table.addCell(subtitleCell);
1475                         //document.add(table);
1476                 }
1477                 return table;
1478         }
1479
1480
1481         private void paintPdfReportFooter(HttpServletRequest request, Document document, ReportRuntime rr, float[] f) 
1482                         throws DocumentException, IOException {
1483                 
1484                 HttpSession session = request.getSession();
1485                 String drilldown_index = (String) session.getAttribute("drilldown_index");
1486                 int index = 0;
1487                 try {
1488                  index = Integer.parseInt(drilldown_index);
1489                 } catch (NumberFormatException ex) {
1490                         index = 0;
1491                 }
1492
1493                 String title = (String) session.getAttribute("FOOTER_"+index);
1494                 if(nvl(title).length()>0) {
1495                         PdfPTable table = new PdfPTable(1);
1496                         table.setWidthPercentage(100f);
1497                         table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1498                         table.getDefaultCell().setVerticalAlignment(Rectangle.ALIGN_BOTTOM);
1499                 
1500                         Font font = FontFactory.getFont(FONT_FAMILY, 
1501                                         FONT_SIZE-3f,
1502                                         Font.BOLD, 
1503                                         Color.BLACK);
1504                 
1505                         
1506                         //addEmptyRows(table,1);
1507                         table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1508                         //table.getDefaultCell().setBackgroundColor(Color.decode(Globals.getDataTableHeaderBackgroundFontColor()));
1509                     /*title = Utils.replaceInString(title, "<BR/>", " ");
1510                     title = Utils.replaceInString(title, "<br/>", " ");
1511                     title = Utils.replaceInString(title, "<br>", " ");
1512                         title  = strip.stripHtml(nvl(title).trim());*/
1513                 StyleSheet style = new StyleSheet();
1514                 
1515                         HTMLWorker htmlWorker = new HTMLWorker(document); 
1516                         ArrayList cc = new ArrayList(); 
1517                         cc = htmlWorker.parseToList(new StringReader(title), style); 
1518                                                 
1519                         Phrase p1 = new Phrase(); 
1520                         for (int i = 0; i < cc.size(); i++){ 
1521                                 Element elem = (Element)cc.get(i); 
1522                                 ArrayList al  = elem.getChunks();
1523                                 for (int j = 0; j < al.size(); j++) {
1524                                         Chunk chunk = (Chunk) al.get(j);
1525                                         chunk.font().setSize(6.0f);
1526                                 }
1527                                 p1.add(elem); 
1528                         } 
1529                 
1530 /*                      
1531                         HTMLWorker.parseToList(new StringReader(nvl(title)), style);*/
1532                         PdfPCell titleCell = new PdfPCell(p1);
1533                         titleCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1534                         table.addCell(titleCell);
1535                         //table.
1536                         document.add(table);
1537                 }
1538                 //return table;
1539         }
1540         
1541         
1542         private void paintPdfTableHeader(Document document, ReportData rd, PdfPTable table) 
1543                                                                                                                                 throws DocumentException {
1544                         
1545                 Font font = FontFactory.getFont(FONT_FAMILY, 
1546                                                                                 FONT_SIZE+1f,
1547                                                                                 Font.BOLD, 
1548                                                                                 Color.decode(Globals.getDataTableHeaderFontColor()));
1549                 //table.setHeaderRows(1);
1550                 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1551                 table.getDefaultCell().setBackgroundColor(Color.decode(Globals.getDataTableHeaderBackgroundFontColor()));
1552                 String title = "";
1553                 
1554                 boolean firstPass = true;
1555                 
1556                 /*if(rd.reportTotalRowHeaderCols!=null) {
1557                         if(firstPass) {
1558                                 table.addCell(new Paragraph("No.", font));
1559                                 firstPass = false;
1560                         }
1561                 }*/             
1562                 for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();) 
1563                 {
1564                         if(firstPass) {
1565                                 for(rd.reportRowHeaderCols.resetNext();rd.reportRowHeaderCols.hasNext();) {
1566                                         /*if(firstPass) {
1567                                                 table.addCell(new Paragraph("No.", font));
1568                                                 firstPass = false;
1569                                         } else {*/
1570                                                 RowHeaderCol rhc = rd.reportRowHeaderCols.getNext();
1571                                                 title = rhc.getColumnTitle();
1572                                         title = Utils.replaceInString(title,"_nl_", " \n");
1573                                                 table.addCell(new Paragraph(title,font));
1574                                         //}
1575                                 }
1576                         }
1577                         
1578                         ColumnHeaderRow chr = rd.reportColumnHeaderRows.getNext();
1579                         for (chr.resetNext(); chr.hasNext();) {
1580                                 ColumnHeader ch = chr.getNext();
1581                                 //System.out.println(ch);
1582                                 if(ch.isVisible()) {
1583                                         title = ch.getColumnTitle();
1584                                 title = Utils.replaceInString(title,"_nl_", " \n");
1585                                         table.addCell(new Paragraph(title,font));
1586                                 }
1587                         }
1588                 }
1589         }
1590         
1591         public static String currentTime(String pattern) {
1592                 try {
1593                 SimpleDateFormat oracleDateFormat = new SimpleDateFormat("MM/dd/yyyy kk:mm:ss");
1594                 Date sysdate = oracleDateFormat.parse(ReportLoader.getSystemDateTime());
1595                 SimpleDateFormat dtimestamp = new SimpleDateFormat(Globals.getScheduleDatePattern());
1596                 return dtimestamp.format(sysdate)+" "+Globals.getTimeZone();
1597                 //paramList.add(new IdNameValue("DATE", dtimestamp.format(sysdate)+" "+Globals.getTimeZone()));
1598         } catch(Exception ex) {}         
1599                 
1600                 SimpleDateFormat s = new SimpleDateFormat(pattern);
1601                 s.setTimeZone(TimeZone.getTimeZone(Globals.getTimeZone()));
1602                 //System.out.println("^^^^^^^^^^^^^^^^^^^^ " + Calendar.getInstance().getTime());
1603                 //System.out.println("^^^^^^^^^^^^^^^^^^^^ " + s.format(Calendar.getInstance().getTime()));
1604                 return s.format(Calendar.getInstance().getTime());
1605         }
1606
1607         private PdfBean preparePdfBean(HttpServletRequest request,ReportRuntime rr) {
1608                 PdfBean pb = new PdfBean();
1609
1610                 pb.setUserId(AppUtils.getUserID(request));
1611
1612                 pb.setWhereToShowPageNumber(Globals.getPageNumberPosition());
1613                 pb.setAlternateColor(Globals.isDataAlternateColor());
1614                 pb.setTimestampPattern(Globals.getDatePattern());
1615
1616                 int temp = -1;
1617                 try {
1618                         temp = Integer.parseInt(request.getParameter(AppConstants.RI_NEXT_PAGE));
1619                 } catch (NumberFormatException e) {}            
1620                 pb.setCurrentPage(temp);
1621         
1622                 //pb.setPortrait( trueORfalse(request.getParameter("isPortrait"),true));
1623                 pb.setPortrait(trueORfalse(rr.getPDFOrientation() == "portait"?"true":"false", true));
1624                 //pb.setCoverPageIncluded( trueORfalse(request.getParameter("isCoverPageIncluded"), true));
1625                 //if(Globals.isCoverPageNeeded()) {
1626                         pb.setCoverPageIncluded(Globals.isCoverPageNeeded()?rr.isPDFCoverPage():false);
1627                 //}
1628                 pb.setTitle(nvl(request.getParameter("title")));
1629                 pb.setPagesize(nvls(request.getParameter("pagesize"),"LETTER"));
1630                 
1631                 pb.setLogo1Url(rr.getPDFLogo1());
1632                 pb.setLogo2Url(rr.getPDFLogo2());
1633                 pb.setLogo1Size(rr.getPDFLogo1Size());
1634                 pb.setLogo2Size(rr.getPDFLogo2Size());
1635                 pb.setFullWebContextPath(request.getSession().getServletContext().getRealPath(File.separator));
1636                 
1637
1638                 pb.setDisplayChart(nvl(rr.getChartType()).trim().length()>0 && rr.getDisplayChart());
1639                         
1640                 String id = nvl(request.getParameter("pdfAttachmentKey")).trim();
1641                 String log_id = nvl(request.getParameter("log_id")).trim();
1642                 if(id.length()>0 && log_id.length()>0)
1643                         pb.setAttachmentOfEmail(true);
1644                 
1645                 return pb;
1646         }
1647         
1648         private boolean trueORfalse(String str) {
1649                 return (str != null) && (str.equalsIgnoreCase("true"));
1650         }
1651         
1652         private boolean trueORfalse(String str,boolean b_default) {
1653                 return str==null ? b_default : (str.equalsIgnoreCase("true"));
1654         }
1655         
1656    
1657 }