2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
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
26 * https://creativecommons.org/licenses/by/4.0/
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.
34 * ============LICENSE_END============================================
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 * ===========================================================================================
44 * -------------------------------------------------------------------------------------------
45 * PdfReportHandler.java - This class is used to generate reports in PDF using iText
46 * -------------------------------------------------------------------------------------------
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>
56 package org.onap.portalsdk.analytics.model.pdf;
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;
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;
96 import java.util.Map.Entry;
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;
130 * @author mwliu and sundar
133 public class PdfReportHandler extends org.onap.portalsdk.analytics.RaptorObject{
135 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PdfReportHandler.class);
138 private HtmlStripper strip = new HtmlStripper();
139 private static final int RetryCreateNewImage = 3;
140 private int retryCreateNewImageCount=0;
142 private String FONT_FAMILY = "Arial";
143 private int FONT_SIZE = 9;
145 public PdfReportHandler() { }
147 public void createPdfFileContent(HttpServletRequest request, HttpServletResponse response, int type) throws IOException, RaptorException {
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);
155 response.setContentType("application/pdf");
156 OutputStream outStream = response.getOutputStream();
158 String formattedReportName = "";
159 PdfWriter writer = null;
160 ReportRuntime firstReportRuntimeObj = null;
163 ReportRuntime rr = null;
165 rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
167 boolean isDashboard = false;
168 if ((request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID)!=null) && ( ((String) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID)).equals(rr.getReportID())) ) {
173 String reportID = (String) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID);
174 ReportRuntime rrDash = rh.loadReportRuntime(request, reportID, true, 1);
175 pb = preparePdfBean(request,rrDash);
178 document.setPageSize(PageSize.getRectangle(pb.getPagesize()));
179 if(!pb.isPortrait()) // get this from properties file
180 document.setPageSize(document.getPageSize().rotate());
183 writer = PdfWriter.getInstance(document, response.getOutputStream());
184 writer.setPageEvent(new PageEvent(pb));//header,footer,bookmark
187 formattedReportName = new HtmlStripper().stripSpecialCharacters(rrDash.getReportName());
188 if(pb.isAttachmentOfEmail())
189 response.setHeader("Content-disposition", "inline");
191 response.setHeader("Content-disposition", "attachment;filename="+ formattedReportName+formattedDate+user_id+".pdf");
193 pdfFName = "dashboard"+formattedReportName+formattedDate+user_id+".pdf";
194 Map reportRuntimeMap = null;
195 Map reportDataMap = null;
196 Map reportDisplayTypeMap = null;
198 reportRuntimeMap = (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP);
199 reportDataMap = (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP);
200 reportDisplayTypeMap = (TreeMap) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP);
202 if(reportRuntimeMap!=null) {
203 Set setReportRuntime = reportRuntimeMap.entrySet();
204 Set setReportDataMap = reportDataMap.entrySet();
205 Set setReportDisplayTypeMap = reportDisplayTypeMap.entrySet();
207 Iterator iter2 = setReportDataMap.iterator();
208 Iterator iter3 = setReportDisplayTypeMap.iterator();
210 for(Iterator iter = setReportRuntime.iterator(); iter.hasNext(); ) {
212 Map.Entry entryData = (Entry) iter2.next();
213 Map.Entry entry = (Entry) iter.next();
214 Map.Entry entryCheckChart = (Entry) iter3.next();
215 ReportRuntime rrDashRep = (ReportRuntime) entry.getValue();
218 firstReportRuntimeObj = (ReportRuntime) entry.getValue();
219 if(pb.isCoverPageIncluded()) {
220 document = paintDashboardCoverPage(document, rrDash, firstReportRuntimeObj, request);
223 ReportData rdDashRep = (ReportData) entryData.getValue();
225 if( ((rrDashRep.getChartType()).trim().length()>0 && rrDashRep.getDisplayChart()) && entryCheckChart.getValue().toString().equals("c")) {
227 pb.setTitle(nvl(rrDashRep.getReportTitle()).length()>0?rrDashRep.getReportTitle():rrDashRep.getReportName());
228 paintPdfImage(request, document,AppUtils.getTempFolderPath()+"cr_"+ pb.getUserId()+"_"+request.getSession().getId()+"_"+rrDashRep.getReportID()+".png", rrDashRep);
231 pb.setTitle(nvl(rrDashRep.getReportTitle()).length()>0?rrDashRep.getReportTitle():rrDashRep.getReportName());
232 paintPdfData(request, document,rdDashRep,rrDashRep, "");
237 } catch (DocumentException dex) {
238 logger.error(EELFLoggerDelegate.errorLogger, "DocumentException in createPdfFileContent", dex);
240 catch (RaptorException rex) {
241 logger.error(EELFLoggerDelegate.errorLogger, "RaptorException in createPdfFileContent", rex);
245 ReportData rd = null;
248 if(!nvl(request.getParameter("parent"), "").equals("N"))
249 parent = nvl(request.getParameter("parent"), "");
250 if(parent.startsWith("parent_"))
252 if(parentFlag == 1) {
253 rr = (ReportRuntime) request.getSession().getAttribute(parent+"_rr");
254 rd = (ReportData) request.getSession().getAttribute(parent+"_rd");
257 rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
259 rd = (ReportData) request.getSession().getAttribute(AppConstants.RI_REPORT_DATA);
261 pb = preparePdfBean(request,rr);
262 FONT_FAMILY = rr.getPDFFont();
263 FONT_SIZE = rr.getPDFFontSize();
265 formattedReportName = new HtmlStripper().stripSpecialCharacters(rr.getReportName());
269 response.setContentType("application/pdf");
270 if(pb.isAttachmentOfEmail())
271 response.setHeader("Content-disposition", "inline");
273 response.setHeader("Content-disposition", "attachment;filename="+ formattedReportName+formattedDate+user_id+".pdf");
275 document.setPageSize(PageSize.getRectangle(pb.getPagesize()));
277 if(!pb.isPortrait()) // get this from properties file
278 document.setPageSize(document.getPageSize().rotate());
282 writer = PdfWriter.getInstance(document, outStream);
283 writer.setPageEvent(new PageEvent(pb));//header,footer,bookmark
286 if(pb.isCoverPageIncluded()) {
287 document = paintCoverPage(document, rr, request);
291 if(pb.isDisplayChart()) {
292 paintPdfImage(request, document,AppUtils.getTempFolderPath()+"cr_"+ pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+".png", rr);
296 if(type == 3 && rr.getSemaphoreList()==null && !(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) ) { //type = 3 is whole
297 String sql_whole = (String) request.getAttribute(AppConstants.RI_REPORT_SQL_WHOLE);
298 returnValue = paintPdfData(request, document, rd, rr, sql_whole);
299 } else if(type == 2) {
300 returnValue = paintPdfData(request, document, rd, rr, "");
302 int downloadLimit = (rr.getMaxRowsInExcelDownload()>0)?rr.getMaxRowsInExcelDownload():Globals.getDownloadLimit();
303 String action = request.getParameter(AppConstants.RI_ACTION);
305 if(!(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) && !action.endsWith("session"))
306 rd = rr.loadReportData(-1, AppUtils.getUserID(request), downloadLimit,request, false /*download*/);
307 if(rr.getSemaphoreList()!=null) {
308 rd = rr.loadReportData(-1, AppUtils.getUserID(request), downloadLimit,request, true);
309 returnValue = paintPdfData(request, document, rd, rr, "");
311 returnValue = paintPdfData(request, document, rd, rr, rr.getWholeSQL());
318 } catch (DocumentException de) {
319 logger.error(EELFLoggerDelegate.errorLogger, "DocumentException in createPdfFileContent", de);
325 Runtime runtime = Runtime.getRuntime();
326 logger.debug(EELFLoggerDelegate.debugLogger, ("##### Heap utilization statistics [MB] #####"));
327 logger.debug(EELFLoggerDelegate.debugLogger, ("Used Memory:"
328 + (runtime.maxMemory() - runtime.freeMemory()) / mb));
329 logger.debug(EELFLoggerDelegate.debugLogger, ("Free Memory:"
330 + runtime.freeMemory() / mb));
331 logger.debug(EELFLoggerDelegate.debugLogger, ("Total Memory:" + runtime.totalMemory() / mb));
332 logger.debug(EELFLoggerDelegate.debugLogger, ("Max Memory:" + runtime.maxMemory() / mb));
336 private Document paintCoverPage(Document doc, ReportRuntime rr, HttpServletRequest request) throws IOException, DocumentException {
338 if(nvl(rr.getPdfImg()).length()>0) {
339 Image image1 = Image.getInstance(AppUtils.getExcelTemplatePath()+"../../"+AppUtils.getImgFolderURL()+rr.getPdfImg());
340 image1.scalePercent(20f, 20f);
343 float firstColumnSize = Globals.getCoverPageFirstColumnSize();
344 float[] relativeWidths = {firstColumnSize,1f-firstColumnSize};
345 PdfPTable table = new PdfPTable(relativeWidths);
346 table.getDefaultCell().setBorderWidth(0);
347 addEmptyRows(table,6);
348 HTMLWorker worker = new HTMLWorker(doc);
349 StyleSheet style = new StyleSheet();
350 style.loadTagStyle("body", "leading", "16,0");
351 StringBuffer reportDescrBuf = new StringBuffer("");
352 ArrayList descr = HTMLWorker.parseToList(new StringReader(nvl(rr.getReportDescr())), style);
353 ArrayList paraList = null;
354 if(nvl(rr.getReportTitle()).length()>0) {
355 add2Cells(table,"Report Title : ",nvl(rr.getReportTitle()));
356 if(nvl(rr.getReportSubTitle()).length()>0) {
357 add2Cells(table,"Report Sub-Title : ",nvl(rr.getReportSubTitle()));
358 System.out.println("Adding the report sub-title ");
362 add2Cells(table,"Report Name : ",nvl(rr.getReportName()));
364 if((descr!=null && descr.size()>0)) {
365 paraList = (com.lowagie.text.Paragraph)descr.get(0);
366 for (int i=0 ; i<paraList.size(); i++) {
367 reportDescrBuf.append(paraList.get(i));
371 add2Cells(table,"Description : ",reportDescrBuf.toString());
372 if(Globals.getSessionInfoForTheCoverPage().length()>0) {
373 String nameValue[] = Globals.getSessionInfoForTheCoverPage().split(",");
374 String name=nameValue[0];
375 String value=nameValue[1];
376 add2Cells(table,name+" : ",(AppUtils.getRequestNvlValue(request, value).length()>0?AppUtils.getRequestNvlValue(request, value):nvl((String)request.getSession().getAttribute(value))));
379 if(Globals.isCreatedOwnerInfoNeeded()) {
380 add2Cells(table,"Created By : ",nvl(AppUtils.getUserName(rr.getCreateID())));
381 add2Cells(table,"Owner : ",nvl(AppUtils.getUserName(rr.getOwnerID())));
383 if(Globals.displayLoginIdForDownloadedBy())
384 add2Cells(table,"Downloaded by : ",nvl(AppUtils.getUserBackdoorLoginId(request)));
386 add2Cells(table,"Downloaded by : ",nvl(AppUtils.getUserName(AppUtils.getUserID(request))));
388 addEmptyRows(table,1);
390 boolean isFirstRow = true;
391 ArrayList al = rr.getParamNameValuePairsforPDFExcel(request, 1);
393 al = (ArrayList) request.getSession().getAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO);
396 Iterator it = al.iterator();
397 addEmptyRows(table,1);
398 if(rr.getFormFieldComments(request).length()<=0) {
399 while(it.hasNext()) {
402 add2Cells(table, "Run-time Criteria : ", " ");
406 IdNameValue value = (IdNameValue)it.next();
407 if(!value.getId().trim().equals("BLANK"))
408 add2Cells(table, value.getId()+" : ",value.getName().replaceAll("~",","));
410 addEmptyRows(table,1);
416 addEmptyRows(table,1);
418 ArrayList p = HTMLWorker.parseToList(new StringReader(rr.getFormFieldComments(request).replaceAll("~",",")), style);
420 for (int k = 0; k < p.size(); ++k){
421 doc.add((com.lowagie.text.Element)p.get(k));
430 private Document paintDashboardCoverPage(Document doc, ReportRuntime rrDashRep, ReportRuntime firstReportRuntimeObj, HttpServletRequest request) throws IOException, DocumentException {
432 float firstColumnSize = Globals.getCoverPageFirstColumnSize();
433 float[] relativeWidths = {firstColumnSize,1f-firstColumnSize};
434 PdfPTable table = new PdfPTable(relativeWidths);
435 table.getDefaultCell().setBorderWidth(0);
436 addEmptyRows(table,6);
438 add2Cells(table,"Report Name : ",rrDashRep.getReportName());
439 add2Cells(table,"Description : ",rrDashRep.getReportDescr());
440 if(Globals.getSessionInfoForTheCoverPage().length()>0) {
441 String nameValue[] = Globals.getSessionInfoForTheCoverPage().split(",");
442 String name=nameValue[0];
443 String value=nameValue[1];
444 add2Cells(table,name+" : ",(AppUtils.getRequestNvlValue(request, value).length()>0?AppUtils.getRequestNvlValue(request, value):nvl((String)request.getSession().getAttribute(value))));
447 if(Globals.isCreatedOwnerInfoNeeded()) {
448 add2Cells(table,"Created By : ",AppUtils.getUserName(rrDashRep.getCreateID()));
449 add2Cells(table,"Owner : ",AppUtils.getUserName(rrDashRep.getOwnerID()));
451 if(Globals.displayLoginIdForDownloadedBy())
452 add2Cells(table,"Downloaded by : ",AppUtils.getUserBackdoorLoginId(request));
454 add2Cells(table,"Downloaded by : ",AppUtils.getUserName(request));
456 addEmptyRows(table,1);
458 boolean isFirstRow = true;
459 ArrayList al = firstReportRuntimeObj.getParamNameValuePairsforPDFExcel(request, 2);
460 Iterator it = al.iterator();
461 addEmptyRows(table,1);
462 if(firstReportRuntimeObj.getFormFieldComments(request).length()<=0) {
463 while(it.hasNext()) {
466 add2Cells(table, "Run-time Criteria : ", " ");
470 IdNameValue value = (IdNameValue)it.next();
471 if(!value.getId().trim().equals("BLANK"))
472 add2Cells(table, value.getId()+" : ",value.getName());
474 addEmptyRows(table,1);
480 addEmptyRows(table,1);
482 HTMLWorker worker = new HTMLWorker(doc);
483 StyleSheet style = new StyleSheet();
484 style.loadTagStyle("body", "leading", "16,0");
485 ArrayList p = HTMLWorker.parseToList(new StringReader(firstReportRuntimeObj.getFormFieldComments(request)), style);
487 for (int k = 0; k < p.size(); ++k){
488 doc.add((com.lowagie.text.Element)p.get(k));
497 public static void addEmptyRows(PdfPTable table, int rows) throws DocumentException {
498 for (int i=0; i<rows; i++)
499 for(int j=0;j<table.getAbsoluteWidths().length;j++)
500 table.addCell(new Paragraph(" "));
504 private void add2Cells(PdfPTable table, String key, String value) {
507 cell = new PdfPCell(new Paragraph(key));
508 cell.setHorizontalAlignment(Rectangle.ALIGN_RIGHT);
509 cell.setBorderWidth(0f);
512 cell = new PdfPCell(new Paragraph(value));
513 cell.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
514 cell.setBorderWidth(0f);
518 private void paintPdfImage(HttpServletRequest request, Document document, String fileName, ReportRuntime rr)
519 throws DocumentException
522 ArrayList images = getImage(request, fileName,pb.isAttachmentOfEmail()?true:false, rr);
523 PdfPTable table = null;
524 PdfPCell cellValue = null;
527 for (int i = 0; i < images.size(); i++) {
528 table = new PdfPTable(1);
529 cellValue = new PdfPCell();
530 cellValue.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
531 Image image = (Image) images.get(i);
532 image.setAlignment(Image.ALIGN_CENTER);
535 cellValue.setImage(image);
536 table.addCell(cellValue);
542 private ArrayList getImage(HttpServletRequest request, String fileName, boolean isGenerateNewImage, ReportRuntime rr) {
543 ArrayList images = new ArrayList();
544 if(!isGenerateNewImage) {
546 Image image = Image.getInstance(fileName);
550 catch (MalformedURLException e) {
551 isGenerateNewImage = true;
552 logger.error(EELFLoggerDelegate.errorLogger, "MalformedURLException in getImage", e);
554 catch (BadElementException e) {
555 isGenerateNewImage = true;
556 logger.error(EELFLoggerDelegate.errorLogger, "BadElementException in getImage", e);
557 } catch (FileNotFoundException e) {
558 isGenerateNewImage = true;
559 logger.error(EELFLoggerDelegate.errorLogger, "FileNotFoundException in getImage", e);
560 } catch (IOException e) {
561 isGenerateNewImage = true;
562 logger.error(EELFLoggerDelegate.errorLogger, "IOException in getImage", e);
566 if(isGenerateNewImage && retryCreateNewImageCount<RetryCreateNewImage){
567 retryCreateNewImageCount++;
568 return generateNewImage(request, rr);
575 private ArrayList generateNewImage(HttpServletRequest request, ReportRuntime rr) {
576 ArrayList images = new ArrayList();
577 final String MALFORMEDURLEXCEPTION_MSG = "MalformedURLException in generateNewImage";
578 final String BADELEMENTEXCEPTION_MSG = "BadElementException in generateNewImage";
579 final String FILENOTFOUNDEXCEPTION_MSG = "FileNotFoundException in generateNewImage";
580 final String IOEXCEPTION_MSG = "IOException in generateNewImage";
583 if(request.getSession().getAttribute(AppConstants.RI_CHART_DATA)!=null) {
584 ds = (DataSet) request.getSession().getAttribute(AppConstants.RI_CHART_DATA);
586 ds = rr.loadChartData(pb.getUserId(),request);
588 String downloadFileName = "";
589 HashMap additionalChartOptionsMap = new HashMap();
590 String chartType = nvl(rr.getChartType());
591 if(chartType.equals(AppConstants.GT_PIE_MULTIPLE)) {
592 additionalChartOptionsMap.put("multiplePieOrderRow", new Boolean((AppUtils.getRequestNvlValue(request, "multiplePieOrder").length()>0?AppUtils.getRequestNvlValue(request, "multiplePieOrder").equals("row"):rr.isMultiplePieOrderByRow())) );
593 additionalChartOptionsMap.put("multiplePieLabelDisplay", AppUtils.getRequestNvlValue(request, "multiplePieLabelDisplay").length()>0? AppUtils.getRequestNvlValue(request, "multiplePieLabelDisplay"):rr.getMultiplePieLabelDisplay());
594 additionalChartOptionsMap.put("chartDisplay", new Boolean(AppUtils.getRequestNvlValue(request, "chartDisplay").length()>0? AppUtils.getRequestNvlValue(request, "chartDisplay").equals("3D"):rr.isChartDisplayIn3D()));
595 } else if (chartType.equals(AppConstants.GT_BAR_3D)) {
596 additionalChartOptionsMap.put("chartOrientation", new Boolean((AppUtils.getRequestNvlValue(request, "chartOrientation").length()>0?AppUtils.getRequestNvlValue(request, "chartOrientation").equals("vertical"):rr.isVerticalOrientation())) );
597 additionalChartOptionsMap.put("secondaryChartRenderer", AppUtils.getRequestNvlValue(request, "secondaryChartRenderer").length()>0? AppUtils.getRequestNvlValue(request, "secondaryChartRenderer"):rr.getSecondaryChartRenderer());
598 additionalChartOptionsMap.put("chartDisplay", new Boolean(AppUtils.getRequestNvlValue(request, "chartDisplay").length()>0? AppUtils.getRequestNvlValue(request, "chartDisplay").equals("3D"):rr.isChartDisplayIn3D()));
599 additionalChartOptionsMap.put("lastSeriesALineChart", new Boolean(rr.isLastSeriesALineChart()));
600 } else if (chartType.equals(AppConstants.GT_LINE)) {
601 additionalChartOptionsMap.put("chartOrientation", new Boolean((AppUtils.getRequestNvlValue(request, "chartOrientation").length()>0?AppUtils.getRequestNvlValue(request, "chartOrientation").equals("vertical"):rr.isVerticalOrientation())) );
602 additionalChartOptionsMap.put("chartDisplay", new Boolean(AppUtils.getRequestNvlValue(request, "chartDisplay").length()>0? AppUtils.getRequestNvlValue(request, "chartDisplay").equals("3D"):rr.isChartDisplayIn3D()));
603 additionalChartOptionsMap.put("lastSeriesABarChart", new Boolean(rr.isLastSeriesABarChart()));
604 } else if (chartType.equals(AppConstants.GT_TIME_DIFFERENCE_CHART)) {
605 additionalChartOptionsMap.put("intervalFromDate",AppUtils.getRequestNvlValue(request, "intervalFromDate").length()>0?AppUtils.getRequestNvlValue(request, "intervalFromDate"):rr.getIntervalFromdate());
606 additionalChartOptionsMap.put("intervalToDate", AppUtils.getRequestNvlValue(request, "intervalToDate").length()>0? AppUtils.getRequestNvlValue(request, "intervalToDate"):rr.getIntervalTodate());
607 additionalChartOptionsMap.put("intervalLabel", AppUtils.getRequestNvlValue(request, "intervalLabel").length()>0? AppUtils.getRequestNvlValue(request, "intervalLabel"):rr.getIntervalLabel());
608 } else if (chartType.equals(AppConstants.GT_REGRESSION)) {
609 additionalChartOptionsMap.put("regressionType",AppUtils.getRequestNvlValue(request, "regressionType").length()>0?AppUtils.getRequestNvlValue(request, "regressionType"):rr.getLinearRegression());
610 additionalChartOptionsMap.put("linearRegressionColor",nvl(rr.getLinearRegressionColor()));
611 additionalChartOptionsMap.put("expRegressionColor",nvl(rr.getExponentialRegressionColor()));
612 additionalChartOptionsMap.put("maxRegression",nvl(rr.getCustomizedRegressionPoint()));
613 } else if (chartType.equals(AppConstants.GT_STACK_BAR) ||chartType.equals(AppConstants.GT_STACKED_HORIZ_BAR) || chartType.equals(AppConstants.GT_STACKED_HORIZ_BAR_LINES)
614 || chartType.equals(AppConstants.GT_STACKED_VERT_BAR) || chartType.equals(AppConstants.GT_STACKED_VERT_BAR_LINES)
616 additionalChartOptionsMap.put("overlayItemValue",new Boolean(nvl(rr.getOverlayItemValueOnStackBar()).equals("Y")));
618 additionalChartOptionsMap.put("legendPosition", nvl(rr.getLegendPosition()));
619 additionalChartOptionsMap.put("hideToolTips", new Boolean(rr.hideChartToolTips()));
620 additionalChartOptionsMap.put("hideLegend", new Boolean(AppUtils.getRequestNvlValue(request, "hideLegend").length()>0? AppUtils.getRequestNvlValue(request, "hideLegend").equals("Y"):rr.hideChartLegend()));
621 additionalChartOptionsMap.put("labelAngle", nvl(rr.getLegendLabelAngle()));
622 additionalChartOptionsMap.put("maxLabelsInDomainAxis", nvl(rr.getMaxLabelsInDomainAxis()));
623 additionalChartOptionsMap.put("rangeAxisLowerLimit", nvl(rr.getRangeAxisLowerLimit()));
624 additionalChartOptionsMap.put("rangeAxisUpperLimit", nvl(rr.getRangeAxisUpperLimit()));
627 boolean totalOnChart = false;
628 totalOnChart = AppUtils.getRequestNvlValue(request, "totalOnChart").equals("Y");
629 String filename = null;
630 ArrayList graphURL = new ArrayList();
631 ArrayList chartNames = new ArrayList();
632 ArrayList fileNames = new ArrayList();
633 List l = rr.getAllColumns();
634 List lGroups = rr.getAllChartGroups();
635 HashMap mapYAxis = rr.getAllChartYAxis(rr.getReportParamValues());
636 String chartLeftAxisLabel = rr.getFormFieldFilled(nvl(rr.getChartLeftAxisLabel()));
637 String chartRightAxisLabel = rr.getFormFieldFilled(nvl(rr.getChartRightAxisLabel()));
638 int displayTotalOnChart = 0;
639 HashMap formValues = Globals.getRequestParamtersMap(request, false);
641 for (Iterator iterC = l.iterator(); iterC.hasNext();) {
642 DataColumnType dc = (DataColumnType) iterC.next();
643 if(nvl(dc.getColName()).equals(AppConstants.RI_CHART_TOTAL_COL)) {
644 displayTotalOnChart = 1;
648 String legendColumnName = (rr.getChartLegendColumn()!=null)?rr.getChartLegendColumn().getDisplayName():"Legend Column";
654 if(rr.hasSeriesColumn() && chartType.equals(AppConstants.GT_TIME_SERIES) && (lGroups==null || lGroups.size() <= 0)) { /** Check whether Report has only category columns if so then all the columns will open in seperate chart - sundar**/
655 for (int i=0; i<rr.getChartValueColumnAxisList(AppConstants.CHART_ALL_COLUMNS, formValues).size();i++) {
656 String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():"";
657 chartTitle = rr.getFormFieldFilled(chartTitle);
658 downloadFileName = AppUtils.getTempFolderPath()+"cr_"+pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png";
661 Image image = Image.getInstance(downloadFileName);
663 } catch (MalformedURLException e) {
664 logger.error(EELFLoggerDelegate.errorLogger, MALFORMEDURLEXCEPTION_MSG,
666 } catch (BadElementException e) {
667 logger.error(EELFLoggerDelegate.errorLogger, BADELEMENTEXCEPTION_MSG,
669 } catch (FileNotFoundException e) {
670 logger.error(EELFLoggerDelegate.errorLogger, FILENOTFOUNDEXCEPTION_MSG,
672 } catch (IOException e) {
673 logger.error(EELFLoggerDelegate.errorLogger, IOEXCEPTION_MSG, e);
677 } else { /** first check the columns to be opened in new charts and loop around in ChartGen generate chart function - sundar**/
678 String tempChartGroupPrev = "";
679 String tempChartGroupCurrent = "";
680 for (int i=0; i<lGroups.size();i++) {
681 String chartGroupOrg = (String) lGroups.get(i);
682 String chartYAxis = (String) mapYAxis.get(chartGroupOrg);
683 if(nvl(chartGroupOrg).length()>0)
684 tempChartGroupCurrent = chartGroupOrg.substring(0,chartGroupOrg.lastIndexOf("|"));
686 tempChartGroupPrev = ((String) lGroups.get(i-1)).substring(0,((String) lGroups.get(i-1)).lastIndexOf("|"));
687 if(tempChartGroupCurrent.equals(tempChartGroupPrev))
689 String chartGroup = chartGroupOrg;
691 downloadFileName = AppUtils.getTempFolderPath()+"cr_"+pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png";
692 String chartTitle = (Globals.getDisplayChartTitle()? (chartGroup!=null && chartGroup.indexOf("|") > 0 ?chartGroup.substring(0,chartGroup.lastIndexOf("|")):rr.getReportName()):"");
693 chartTitle = rr.getFormFieldFilled(chartTitle);
694 String leftAxisLabel = "";
695 if(!rr.isMultiSeries()) {
696 leftAxisLabel = ((chartYAxis!=null && chartYAxis.indexOf("|") > 0) ? chartYAxis.substring(0,chartYAxis.lastIndexOf("|")): chartLeftAxisLabel );
698 leftAxisLabel = chartLeftAxisLabel;
703 Image image = Image.getInstance(downloadFileName);
705 } catch (MalformedURLException e) {
706 logger.error(EELFLoggerDelegate.errorLogger, MALFORMEDURLEXCEPTION_MSG,
708 } catch (BadElementException e) {
709 logger.error(EELFLoggerDelegate.errorLogger, BADELEMENTEXCEPTION_MSG,
711 } catch (FileNotFoundException e) {
712 logger.error(EELFLoggerDelegate.errorLogger, FILENOTFOUNDEXCEPTION_MSG,
714 } catch (IOException e) {
715 logger.error(EELFLoggerDelegate.errorLogger, IOEXCEPTION_MSG, e);
719 if(!chartType.equals(AppConstants.GT_PIE_MULTIPLE)) {
720 for (int i=0; i<rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).size();i++) {
722 downloadFileName = AppUtils.getTempFolderPath()+"cr_"+ pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png";
723 String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():"";
724 chartTitle = rr.getFormFieldFilled(chartTitle);
729 Image image = Image.getInstance(downloadFileName);
731 } catch (MalformedURLException e) {
732 logger.error(EELFLoggerDelegate.errorLogger,
733 MALFORMEDURLEXCEPTION_MSG, e);
734 } catch (BadElementException e) {
735 logger.error(EELFLoggerDelegate.errorLogger,
736 BADELEMENTEXCEPTION_MSG, e);
737 } catch (FileNotFoundException e) {
738 logger.error(EELFLoggerDelegate.errorLogger,
739 FILENOTFOUNDEXCEPTION_MSG, e);
740 } catch (IOException e) {
741 logger.error(EELFLoggerDelegate.errorLogger, IOEXCEPTION_MSG, e);
745 /** second rest of the columns are merged to one single chart - sundar**/
747 if((!(lGroups!=null && lGroups.size() > 0))) {
749 if(/*chartType.equals(AppConstants.GT_TIME_SERIES) && */rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues)!=null && rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues).size()>0) {
750 downloadFileName = AppUtils.getTempFolderPath()+"cr_"+ pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_All.png";
751 String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():"";
752 chartTitle = rr.getFormFieldFilled(chartTitle);
757 Image image = Image.getInstance(downloadFileName);
759 } catch (MalformedURLException e) {
760 logger.error(EELFLoggerDelegate.errorLogger,
761 MALFORMEDURLEXCEPTION_MSG, e);
762 } catch (BadElementException e) {
763 logger.error(EELFLoggerDelegate.errorLogger,
764 BADELEMENTEXCEPTION_MSG, e);
765 } catch (FileNotFoundException e) {
766 logger.error(EELFLoggerDelegate.errorLogger,
767 FILENOTFOUNDEXCEPTION_MSG, e);
768 } catch (IOException e) {
769 logger.error(EELFLoggerDelegate.errorLogger, IOEXCEPTION_MSG, e);
772 } // Stacked Chart Check
773 } // else no Series Column
777 } catch (Exception e) {
778 logger.error(EELFLoggerDelegate.errorLogger, "Exception in generateNewImage", e);
780 return images.size()>0?images:null;
785 private final int DEFAULT_PDF_DISPLAY_WIDTH = 10;
787 private int paintPdfData(final HttpServletRequest request, final Document document, final ReportData rd,
788 final ReportRuntime rr, final String sql_whole) throws DocumentException, RaptorException, IOException {
790 final int mb = 1024 * 1024;
791 final Runtime runtime = Runtime.getRuntime();
794 final float f[] = getRelativeWidths(rd, AppConstants.RT_CROSSTAB.equals(rr.getReportType()));
795 PdfPTable table = new PdfPTable(f);
796 table.setWidthPercentage(100f);
797 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
798 table.getDefaultCell().setVerticalAlignment(Rectangle.ALIGN_BOTTOM);
800 final ReportDefinition rdef = (new ReportHandler()).loadReportDefinition(request, rr.getReportID());
802 final List allColumns = rdef.getAllColumns();
804 final float[] repotWidths = new float[rdef.getVisibleColumnCount()];
806 float pdfDisplayWidth = 0;
807 for (final Iterator iter = allColumns.iterator(); iter.hasNext(); ) {
808 final DataColumnType dct = (DataColumnType) iter.next();
809 if (dct.isVisible()) {
811 if (dct.getPdfDisplayWidthInPxls() == null || dct.getPdfDisplayWidthInPxls().isEmpty() || dct
812 .getPdfDisplayWidthInPxls().startsWith("null")) {
813 pdfDisplayWidth = DEFAULT_PDF_DISPLAY_WIDTH;
815 pdfDisplayWidth = Float.parseFloat(dct.getPdfDisplayWidthInPxls());
818 repotWidths[columnIdx++] = pdfDisplayWidth;
822 table.setWidths(repotWidths);
824 //TODO: check title and subtitle
825 final HttpSession session = request.getSession();
826 final String drilldown_index = (String) session.getAttribute("drilldown_index");
829 index = Integer.parseInt(drilldown_index);
830 } catch (NumberFormatException ex) {
833 final String titleRep = (String) session.getAttribute("TITLE_" + index);
834 final String subtitle = (String) session.getAttribute("SUBTITLE_" + index);
836 if (nvl(titleRep).length() > 0 && nvl(subtitle).length() > 0) {
837 table.setHeaderRows(3);
838 } else if (nvl(titleRep).length() > 0) {
839 table.setHeaderRows(2);
841 table.setHeaderRows(1);
843 table = paintPdfReportHeader(request, document, table, rr, f);
844 paintPdfTableHeader(document, rd, table);
847 final int fragmentsize = 30; //for memory management
849 rd.reportDataRows.resetNext();
850 DataRow dr = rd.reportDataRows.getNext();
852 if (nvl(sql_whole).length() > 0 && AppConstants.RT_LINEAR.equals(rr.getReportType())) {
853 try (final Connection conn = ConnectionUtils.getConnection(rr.getDbInfo());
854 final Statement st = conn.createStatement();
855 final ResultSet rs = st.executeQuery(sql_whole);) {
857 logger.debug(EELFLoggerDelegate.debugLogger, ("************* Map Whole SQL *************"));
858 logger.debug(EELFLoggerDelegate.debugLogger, (sql_whole));
859 logger.debug(EELFLoggerDelegate.debugLogger, ("*****************************************"));
861 final ResultSetMetaData rsmd = rs.getMetaData();
862 final int numberOfColumns = rsmd.getColumnCount();
868 final Map colHash = new HashMap();
869 for (int i = 1; i <= numberOfColumns; i++) {
870 colHash.put(rsmd.getColumnLabel(i).toUpperCase(), rs.getString(i));
872 rd.reportDataRows.resetNext();
874 dr = rd.reportDataRows.getNext();
876 for (dr.resetNext(); dr.hasNext(); ) {
877 final DataValue dv = dr.getNext();
879 final String value = nvl((String) colHash.get(dv.getColId().toUpperCase()));
880 if (dv.isVisible()) {
882 final HtmlFormatter cfmt = dv.getCellFormatter();
883 final HtmlFormatter rfmt = dv.getRowFormatter();
885 final Font cellFont = FontFactory.getFont(FONT_FAMILY,
887 Font.NORMAL, Color.BLACK);
889 cellFormatterFont(cfmt, cellFont);
890 } else if (rfmt != null) {
891 cellFormatterFont(rfmt, cellFont);
894 cellFont.setStyle(Font.BOLD);
898 final String cellValue = strip.stripHtml(value.trim());
899 final PdfPCell cell = new PdfPCell(new Paragraph(cellValue, cellFont));
901 //row background color can be overwritten by cell background color
902 cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
904 if (nvl(dv.getAlignment()).trim().length() > 0) {
905 cell.setHorizontalAlignment(ElementTags.alignmentValue(dv.getAlignment()));
907 cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
911 formatterCell(cfmt, cell);
912 } else if (rfmt != null) {
913 formatterCell(rfmt, cell);
923 if (rd.reportDataTotalRow != null) {
924 for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext(); idx++) {
925 dr = rd.reportDataTotalRow.getNext();
926 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
927 final Font rowHeaderFont = FontFactory.getFont(FONT_FAMILY,
929 Font.NORMAL, Color.BLACK);
930 rowHeaderFont.setStyle(Font.BOLD);
931 rowHeaderFont.setSize(FONT_SIZE + 1f);
932 table.getDefaultCell().setBackgroundColor(getRowBackgroundColor(dr, idx));
933 table.addCell(new Paragraph("Total", rowHeaderFont));
935 addTotalRowColumns(table, dr, idx);
936 if (idx % fragmentsize == fragmentsize - 1) {
938 table.deleteBodyRows();
939 table.setSkipFirstHeader(true);
944 } catch (final SQLException | ReportSQLException ex) {
945 throw new RaptorException(ex);
946 } catch (final Exception ex) {
947 if (!(ex.getCause() instanceof java.net.SocketException)) {
948 throw new RaptorException(ex);
951 //document.add(table);
953 if (rr.getReportType().equals(AppConstants.RT_LINEAR)) {
954 for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext(); idx++) {
956 if (runtime.freeMemory() / mb <= ((runtime.maxMemory() / mb) * Globals.getMemoryThreshold()
961 dr = rd.reportDataRows.getNext();
963 addRowHeader(table, dr, idx, rd);
965 addRowColumns(table, dr, idx);
967 if (idx % fragmentsize == fragmentsize - 1) {
969 table.deleteBodyRows();
970 table.setSkipFirstHeader(true);
974 if (rd.reportDataTotalRow != null) {
975 for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext(); idx++) {
976 dr = rd.reportDataTotalRow.getNext();
977 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
978 Font rowHeaderFont = FontFactory.getFont(FONT_FAMILY,
980 Font.NORMAL, Color.BLACK);
981 rowHeaderFont.setStyle(Font.BOLD);
982 rowHeaderFont.setSize(FONT_SIZE + 1f);
983 table.getDefaultCell().setBackgroundColor(getRowBackgroundColor(dr, idx));
984 table.addCell(new Paragraph("Total", rowHeaderFont));
986 addTotalRowColumns(table, dr, idx);
987 if (idx % fragmentsize == fragmentsize - 1) {
989 table.deleteBodyRows();
990 table.setSkipFirstHeader(true);
996 } else if (AppConstants.RT_CROSSTAB.equals(rr.getReportType())) {
998 final List l = rd.getReportDataList();
999 boolean first = true;
1000 for (int dataRow = 0; dataRow < l.size(); dataRow++) {
1003 dr = (DataRow) l.get(dataRow);
1004 final Vector<DataValue> rowNames = dr.getRowValues();
1005 for (dr.resetNext(); dr.hasNext(); ) {
1008 HtmlFormatter rfmt = dr.getRowFormatter();
1010 Font cellFont = FontFactory.getFont(FONT_FAMILY,
1012 Font.NORMAL, Color.BLACK);
1014 cellFormatterFont(rfmt, cellFont);
1017 if (rowNames != null) {
1018 for (int i = 0; i < rowNames.size(); i++) {
1019 final DataValue dv = rowNames.get(i);
1020 rfmt = dr.getRowFormatter();
1022 cellFont = FontFactory.getFont(FONT_FAMILY,
1024 Font.NORMAL, Color.BLACK);
1026 cellFormatterFont(rfmt, cellFont);
1028 String cellValue = dv.getDisplayValue();
1029 if (cellValue.indexOf("|#") != -1) {
1030 cellValue = cellValue.substring(0, cellValue.indexOf("|"));
1033 final PdfPCell cell = new PdfPCell(new Paragraph(cellValue, cellFont));
1034 //row background color can be overwritten by cell background color
1035 cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
1037 cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1040 formatterCell(rfmt, cell);
1042 table.addCell(cell);
1048 if (runtime.freeMemory() / mb <= ((runtime.maxMemory() / mb) * Globals.getMemoryThreshold()
1053 //addRowHeader(table,dr,idx,rd);
1055 addRowColumns(table, dr, idx);
1057 if (idx % fragmentsize == fragmentsize - 1) {
1058 document.add(table);
1059 table.deleteBodyRows();
1060 table.setSkipFirstHeader(true);
1067 //document.add(table);
1071 document.add(table);
1072 paintPdfReportFooter(request, document, rr, f);
1077 private void addRowHeader(PdfPTable table, DataRow dr, int idx, ReportData rd) {
1079 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1081 for(rd.reportRowHeaderCols.resetNext();rd.reportRowHeaderCols.hasNext();) {
1082 RowHeaderCol rhc = rd.reportRowHeaderCols.getNext();
1085 RowHeader rh = rhc.getNext();
1086 //System.out.println(" =============== RowHeader\n "+rh);
1088 Font rowHeaderFont = FontFactory.getFont(FONT_FAMILY,
1090 Font.NORMAL, Color.BLACK);
1092 rowHeaderFont.setStyle(Font.BOLD);
1093 rowHeaderFont.setSize(FONT_SIZE+1f);
1096 if(rh.getColSpan()>0) {
1097 table.getDefaultCell().setColspan(rh.getColSpan());
1098 table.getDefaultCell().setBackgroundColor(getRowBackgroundColor(dr, idx));
1099 table.addCell(new Paragraph(strip.stripHtml(rh.getRowTitle()),rowHeaderFont));
1104 private void addRowColumns(PdfPTable table, DataRow dr, int idx) {
1106 table.getDefaultCell().setColspan(1);
1108 for(dr.resetNext();dr.hasNext();)
1110 DataValue dv = dr.getNext();
1111 //System.out.println(columnCount +" --> "+dv);
1112 if(dv.isVisible()) {
1113 HtmlFormatter cfmt = dv.getCellFormatter();
1114 HtmlFormatter rfmt = dv.getRowFormatter();
1116 Font cellFont = FontFactory.getFont(FONT_FAMILY,
1118 Font.NORMAL, Color.BLACK);
1120 cellFormatterFont(cfmt,cellFont);
1122 else if(rfmt != null) {
1123 cellFormatterFont(rfmt,cellFont);
1127 cellFont.setStyle(Font.BOLD);
1131 String cellValue = strip.stripHtml(dv.getDisplayValue().trim());
1132 PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont));
1134 //row background color can be overwritten by cell background color
1135 cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
1137 if(nvl(dv.getAlignment()).trim().length()>0)
1138 cell.setHorizontalAlignment(ElementTags.alignmentValue(dv.getAlignment()));
1140 cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1143 formatterCell(cfmt,cell);
1145 else if(rfmt != null) {
1146 formatterCell(rfmt,cell);
1149 table.addCell(cell);
1156 private void addTotalRowColumns(PdfPTable table, DataRow dr, int idx) {
1158 table.getDefaultCell().setColspan(1);
1163 DataValue dv = dr.getNext();
1164 //System.out.println(columnCount +" --> "+dv);
1165 if(dv.isVisible()) {
1166 HtmlFormatter cfmt = dv.getCellFormatter();
1167 HtmlFormatter rfmt = dv.getRowFormatter();
1169 Font cellFont = FontFactory.getFont(FONT_FAMILY,
1171 Font.NORMAL, Color.BLACK);
1173 cellFormatterFont(cfmt,cellFont);
1175 else if(rfmt != null) {
1176 cellFormatterFont(rfmt,cellFont);
1180 cellFont.setStyle(Font.BOLD);
1184 String cellValue = strip.stripHtml(dv.getDisplayValue().trim());
1185 PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont));
1187 //row background color can be overwritten by cell background color
1188 cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
1190 if(nvl(dv.getAlignment()).trim().length()>0)
1191 cell.setHorizontalAlignment(ElementTags.alignmentValue(dv.getAlignment()));
1193 cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1196 formatterCell(cfmt,cell);
1198 else if(rfmt != null) {
1199 formatterCell(rfmt,cell);
1202 table.addCell(cell);
1209 private void formatterCell(HtmlFormatter fmt, PdfPCell cell) {
1211 if(nvl(fmt.getBgColor()).trim().length()>0)
1212 cell.setBackgroundColor(Color.decode(fmt.getBgColor()));
1213 if(nvl(fmt.getAlignment()).trim().length()>0)
1214 cell.setHorizontalAlignment(ElementTags.alignmentValue(fmt.getAlignment()));
1217 private void cellFormatterFont(HtmlFormatter fmt, Font font) {
1220 font.setStyle(Font.BOLD);
1222 font.setStyle(Font.ITALIC);
1223 if(fmt.isUnderline())
1224 font.setStyle(Font.UNDERLINE);
1225 if(fmt.getFontColor().trim().length()>0)
1226 font.setColor(Color.decode(fmt.getFontColor()));
1227 if(fmt.getFontSize().trim().length()>0)
1228 font.setSize(Float.parseFloat(fmt.getFontSize())-Globals.getDataFontSizeOffset());
1229 // if(fmt.getFontFace().trim().length()>0)
1230 // cellFont.setFamily()
1234 private Color getRowBackgroundColor(DataRow dr, int idx) {
1236 Color color = Color.decode(Globals.getDataDefaultBackgroundHexCode());
1238 HtmlFormatter rhf = dr.getRowFormatter();
1239 if(rhf!=null && nvl(rhf.getBgColor()).trim().length()>0)
1241 color = Color.decode(rhf.getBgColor());
1243 else if(pb.isAlternateColor() && idx%2==0)
1245 color = Color.decode(Globals.getDataBackgroundAlternateHexCode());
1251 private int getTotalVisbleColumns(ReportData rd) {
1253 int totalVisbleColumn = rd.getTotalColumnCount();
1254 for(rd.reportDataRows.resetNext();rd.reportDataRows.hasNext();)
1256 DataRow dr = rd.reportDataRows.getNext();
1257 for(dr.resetNext();dr.hasNext();) {
1258 DataValue dv = dr.getNext();
1260 totalVisbleColumn--;
1266 return totalVisbleColumn;
1270 private int getFirstRowIndex(ReportRuntime rr) {
1271 return (pb.getCurrentPage()>0)?pb.getCurrentPage()*rr.getPageSize()+1 : 1;
1274 private float[] getRelativeWidths(ReportData rd, boolean crosstab){
1276 int totalColumns = getTotalVisbleColumns(rd);
1277 /*if(rd.reportTotalRowHeaderCols!=null) {
1284 if(totalColumns == 0 )
1287 float[] relativeWidths = new float[totalColumns];
1288 //initial widths are even
1289 for(int i=0; i<relativeWidths.length; i++)
1290 relativeWidths[i] = 10f;
1293 boolean firstPass = true;
1295 for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();)
1298 /*if(rd.reportTotalRowHeaderCols!=null) {
1299 String columnWidth = "5";
1301 if(columnWidth != null && columnWidth.trim().endsWith("%"))
1302 relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
1307 for(rd.reportRowHeaderCols.resetNext();rd.reportRowHeaderCols.hasNext();) {
1308 String columnWidth = rd.reportRowHeaderCols.getNext().getColumnWidth();
1310 if(columnWidth != null && columnWidth.trim().endsWith("%"))
1311 relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
1318 ColumnHeaderRow chr = rd.reportColumnHeaderRows.getNext();
1319 for (chr.resetNext(); chr.hasNext();) {
1321 ColumnHeader ch = chr.getNext();
1323 if(ch.isVisible()) {
1325 String columnWidth = ch.getColumnWidth();
1327 if(ch.getColSpan() <= 1){
1328 if(columnWidth != null && columnWidth.trim().endsWith("%"))
1329 relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
1332 for(int i=0; i<ch.getColSpan(); i++) {
1334 if(columnWidth != null && columnWidth.trim().endsWith("%"))
1335 relativeWidths[index] =
1336 (Float.parseFloat(removeLastCharacter(columnWidth)))/ch.getColSpan();
1345 return relativeWidths;
1348 public static String removeLastCharacter(String str) {
1349 return str.substring(0, str.length()-1);
1352 private PdfPTable paintPdfReportHeader(HttpServletRequest request, Document document, PdfPTable table, ReportRuntime rr, float[] f)
1353 throws DocumentException, IOException {
1355 HttpSession session = request.getSession();
1356 String drilldown_index = (String) session.getAttribute("drilldown_index");
1359 index = Integer.parseInt(drilldown_index);
1360 } catch (NumberFormatException ex) {
1363 String title = (String) session.getAttribute("TITLE_"+index);
1364 String subtitle = (String) session.getAttribute("SUBTITLE_"+index);
1365 if(nvl(title).length()>0) {
1366 //PdfPTable table = new PdfPTable(1);
1367 table.setWidthPercentage(100f);
1368 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1369 table.getDefaultCell().setVerticalAlignment(Rectangle.ALIGN_BOTTOM);
1372 Font font = FontFactory.getFont(FONT_FAMILY,
1377 //addEmptyRows(table,1);
1378 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1379 //table.getDefaultCell().setBackgroundColor(Color.decode(Globals.getDataTableHeaderBackgroundFontColor()));
1380 title = Utils.replaceInString(title, "<BR/>", " ");
1381 title = Utils.replaceInString(title, "<br/>", " ");
1382 title = Utils.replaceInString(title, "<br>", " ");
1383 title = strip.stripHtml(nvl(title).trim());
1384 //subtitle = Utils.replaceInString(subtitle, "<BR/>", " ");
1385 //subtitle = Utils.replaceInString(subtitle, "<br/>", " ");
1386 //subtitle = Utils.replaceInString(subtitle, "<br>", " ");
1387 //subtitle = strip.stripHtml(nvl(subtitle).trim());
1388 StyleSheet styles = new StyleSheet();
1390 HTMLWorker htmlWorker = new HTMLWorker(document);
1391 ArrayList cc = new ArrayList();
1392 cc = htmlWorker.parseToList(new StringReader(subtitle), styles);
1394 Phrase p1 = new Phrase();
1395 for (int i = 0; i < cc.size(); i++){
1396 Element elem = (Element)cc.get(i);
1397 ArrayList al = elem.getChunks();
1398 for (int j = 0; j < al.size(); j++) {
1399 Chunk chunk = (Chunk) al.get(j);
1400 chunk.font().setSize(6.0f);
1404 //cell = new PdfPCell(p1);
1405 StyleSheet style = new StyleSheet();
1406 style.loadTagStyle("font", "font-size", "3");
1407 style.loadTagStyle("font", "size", "3");
1408 styles.loadStyle("pdfFont1", "size", "11px");
1409 styles.loadStyle("pdfFont1", "font-size", "11px");
1410 /*ArrayList p = HTMLWorker.parseToList(new StringReader(nvl(title)), style);
1411 for (int k = 0; k < p.size(); ++k){
1412 document.add((com.lowagie.text.Element)p.get(k));
1414 //p1.font().setSize(3.0f);
1415 PdfPCell titleCell = new PdfPCell(new Phrase(title, font));
1416 titleCell.setColspan(rr.getVisibleColumnCount());
1417 PdfPCell subtitleCell = new PdfPCell(p1);
1418 subtitleCell.setColspan(rr.getVisibleColumnCount());
1419 titleCell.setHorizontalAlignment(1);
1420 subtitleCell.setHorizontalAlignment(1);
1421 table.addCell(titleCell);
1422 table.addCell(subtitleCell);
1423 //document.add(table);
1429 private void paintPdfReportFooter(HttpServletRequest request, Document document, ReportRuntime rr, float[] f)
1430 throws DocumentException, IOException {
1432 HttpSession session = request.getSession();
1433 String drilldown_index = (String) session.getAttribute("drilldown_index");
1436 index = Integer.parseInt(drilldown_index);
1437 } catch (NumberFormatException ex) {
1441 String title = (String) session.getAttribute("FOOTER_"+index);
1442 if(nvl(title).length()>0) {
1443 PdfPTable table = new PdfPTable(1);
1444 table.setWidthPercentage(100f);
1445 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1446 table.getDefaultCell().setVerticalAlignment(Rectangle.ALIGN_BOTTOM);
1448 Font font = FontFactory.getFont(FONT_FAMILY,
1454 //addEmptyRows(table,1);
1455 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1456 //table.getDefaultCell().setBackgroundColor(Color.decode(Globals.getDataTableHeaderBackgroundFontColor()));
1457 /*title = Utils.replaceInString(title, "<BR/>", " ");
1458 title = Utils.replaceInString(title, "<br/>", " ");
1459 title = Utils.replaceInString(title, "<br>", " ");
1460 title = strip.stripHtml(nvl(title).trim());*/
1461 StyleSheet style = new StyleSheet();
1463 HTMLWorker htmlWorker = new HTMLWorker(document);
1464 ArrayList cc = new ArrayList();
1465 cc = htmlWorker.parseToList(new StringReader(title), style);
1467 Phrase p1 = new Phrase();
1468 for (int i = 0; i < cc.size(); i++){
1469 Element elem = (Element)cc.get(i);
1470 ArrayList al = elem.getChunks();
1471 for (int j = 0; j < al.size(); j++) {
1472 Chunk chunk = (Chunk) al.get(j);
1473 chunk.font().setSize(6.0f);
1479 HTMLWorker.parseToList(new StringReader(nvl(title)), style);*/
1480 PdfPCell titleCell = new PdfPCell(p1);
1481 titleCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1482 table.addCell(titleCell);
1484 document.add(table);
1490 private void paintPdfTableHeader(Document document, ReportData rd, PdfPTable table)
1491 throws DocumentException {
1493 Font font = FontFactory.getFont(FONT_FAMILY,
1496 Color.decode(Globals.getDataTableHeaderFontColor()));
1497 //table.setHeaderRows(1);
1498 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1499 table.getDefaultCell().setBackgroundColor(Color.decode(Globals.getDataTableHeaderBackgroundFontColor()));
1502 boolean firstPass = true;
1504 /*if(rd.reportTotalRowHeaderCols!=null) {
1506 table.addCell(new Paragraph("No.", font));
1510 for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();)
1513 for(rd.reportRowHeaderCols.resetNext();rd.reportRowHeaderCols.hasNext();) {
1515 table.addCell(new Paragraph("No.", font));
1518 RowHeaderCol rhc = rd.reportRowHeaderCols.getNext();
1519 title = rhc.getColumnTitle();
1520 title = Utils.replaceInString(title,"_nl_", " \n");
1521 table.addCell(new Paragraph(title,font));
1526 ColumnHeaderRow chr = rd.reportColumnHeaderRows.getNext();
1527 for (chr.resetNext(); chr.hasNext();) {
1528 ColumnHeader ch = chr.getNext();
1529 //System.out.println(ch);
1530 if(ch.isVisible()) {
1531 title = ch.getColumnTitle();
1532 title = Utils.replaceInString(title,"_nl_", " \n");
1533 table.addCell(new Paragraph(title,font));
1539 public static String currentTime(String pattern) {
1541 SimpleDateFormat oracleDateFormat = new SimpleDateFormat("MM/dd/yyyy kk:mm:ss");
1542 Date sysdate = oracleDateFormat.parse(ReportLoader.getSystemDateTime());
1543 SimpleDateFormat dtimestamp = new SimpleDateFormat(Globals.getScheduleDatePattern());
1544 return dtimestamp.format(sysdate)+" "+Globals.getTimeZone();
1545 //paramList.add(new IdNameValue("DATE", dtimestamp.format(sysdate)+" "+Globals.getTimeZone()));
1546 } catch(Exception ex) {}
1548 SimpleDateFormat s = new SimpleDateFormat(pattern);
1549 s.setTimeZone(TimeZone.getTimeZone(Globals.getTimeZone()));
1550 //System.out.println("^^^^^^^^^^^^^^^^^^^^ " + Calendar.getInstance().getTime());
1551 //System.out.println("^^^^^^^^^^^^^^^^^^^^ " + s.format(Calendar.getInstance().getTime()));
1552 return s.format(Calendar.getInstance().getTime());
1555 private PdfBean preparePdfBean(HttpServletRequest request,ReportRuntime rr) {
1556 PdfBean pb = new PdfBean();
1558 pb.setUserId(AppUtils.getUserID(request));
1560 pb.setWhereToShowPageNumber(Globals.getPageNumberPosition());
1561 pb.setAlternateColor(Globals.isDataAlternateColor());
1562 pb.setTimestampPattern(Globals.getDatePattern());
1566 temp = Integer.parseInt(request.getParameter(AppConstants.RI_NEXT_PAGE));
1567 } catch (NumberFormatException e) {}
1568 pb.setCurrentPage(temp);
1570 //pb.setPortrait( trueORfalse(request.getParameter("isPortrait"),true));
1571 pb.setPortrait(trueORfalse(rr.getPDFOrientation() == "portait"?"true":"false", true));
1572 //pb.setCoverPageIncluded( trueORfalse(request.getParameter("isCoverPageIncluded"), true));
1573 //if(Globals.isCoverPageNeeded()) {
1574 pb.setCoverPageIncluded(Globals.isCoverPageNeeded()?rr.isPDFCoverPage():false);
1576 pb.setTitle(nvl(request.getParameter("title")));
1577 pb.setPagesize(nvls(request.getParameter("pagesize"),"LETTER"));
1579 pb.setLogo1Url(rr.getPDFLogo1());
1580 pb.setLogo2Url(rr.getPDFLogo2());
1581 pb.setLogo1Size(rr.getPDFLogo1Size());
1582 pb.setLogo2Size(rr.getPDFLogo2Size());
1583 pb.setFullWebContextPath(request.getSession().getServletContext().getRealPath(File.separator));
1586 pb.setDisplayChart(nvl(rr.getChartType()).trim().length()>0 && rr.getDisplayChart());
1588 String id = nvl(request.getParameter("pdfAttachmentKey")).trim();
1589 String log_id = nvl(request.getParameter("log_id")).trim();
1590 if(id.length()>0 && log_id.length()>0)
1591 pb.setAttachmentOfEmail(true);
1596 private boolean trueORfalse(String str) {
1597 return (str != null) && (str.equalsIgnoreCase("true"));
1600 private boolean trueORfalse(String str,boolean b_default) {
1601 return str==null ? b_default : (str.equalsIgnoreCase("true"));