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