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.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
537 table.addCell(cellValue);
543 private ArrayList getImage(HttpServletRequest request, String fileName, boolean isGenerateNewImage, ReportRuntime rr) {
544 ArrayList images = new ArrayList();
545 if(!isGenerateNewImage) {
547 Image image = Image.getInstance(fileName);
551 catch (MalformedURLException e) {
552 isGenerateNewImage = true;
553 logger.error(EELFLoggerDelegate.errorLogger, "MalformedURLException in getImage", e);
555 catch (BadElementException e) {
556 isGenerateNewImage = true;
557 logger.error(EELFLoggerDelegate.errorLogger, "BadElementException in getImage", e);
558 } catch (FileNotFoundException e) {
559 isGenerateNewImage = true;
560 logger.error(EELFLoggerDelegate.errorLogger, "FileNotFoundException in getImage", e);
561 } catch (IOException e) {
562 isGenerateNewImage = true;
563 logger.error(EELFLoggerDelegate.errorLogger, "IOException in getImage", e);
567 if(isGenerateNewImage && retryCreateNewImageCount<RetryCreateNewImage){
568 retryCreateNewImageCount++;
569 return generateNewImage(request, rr);
576 private ArrayList generateNewImage(HttpServletRequest request, ReportRuntime rr) {
577 ArrayList images = new ArrayList();
578 final String MALFORMEDURLEXCEPTION_MSG = "MalformedURLException in generateNewImage";
579 final String BADELEMENTEXCEPTION_MSG = "BadElementException in generateNewImage";
580 final String FILENOTFOUNDEXCEPTION_MSG = "FileNotFoundException in generateNewImage";
581 final String IOEXCEPTION_MSG = "IOException in generateNewImage";
583 //ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
585 if(request.getSession().getAttribute(AppConstants.RI_CHART_DATA)!=null) {
586 ds = (DataSet) request.getSession().getAttribute(AppConstants.RI_CHART_DATA);
588 ds = rr.loadChartData(pb.getUserId(),request);
590 String downloadFileName = "";
591 HashMap additionalChartOptionsMap = new HashMap();
592 String chartType = nvl(rr.getChartType());
593 if(chartType.equals(AppConstants.GT_PIE_MULTIPLE)) {
594 additionalChartOptionsMap.put("multiplePieOrderRow", new Boolean((AppUtils.getRequestNvlValue(request, "multiplePieOrder").length()>0?AppUtils.getRequestNvlValue(request, "multiplePieOrder").equals("row"):rr.isMultiplePieOrderByRow())) );
595 additionalChartOptionsMap.put("multiplePieLabelDisplay", AppUtils.getRequestNvlValue(request, "multiplePieLabelDisplay").length()>0? AppUtils.getRequestNvlValue(request, "multiplePieLabelDisplay"):rr.getMultiplePieLabelDisplay());
596 additionalChartOptionsMap.put("chartDisplay", new Boolean(AppUtils.getRequestNvlValue(request, "chartDisplay").length()>0? AppUtils.getRequestNvlValue(request, "chartDisplay").equals("3D"):rr.isChartDisplayIn3D()));
597 } else if (chartType.equals(AppConstants.GT_BAR_3D)) {
598 additionalChartOptionsMap.put("chartOrientation", new Boolean((AppUtils.getRequestNvlValue(request, "chartOrientation").length()>0?AppUtils.getRequestNvlValue(request, "chartOrientation").equals("vertical"):rr.isVerticalOrientation())) );
599 additionalChartOptionsMap.put("secondaryChartRenderer", AppUtils.getRequestNvlValue(request, "secondaryChartRenderer").length()>0? AppUtils.getRequestNvlValue(request, "secondaryChartRenderer"):rr.getSecondaryChartRenderer());
600 additionalChartOptionsMap.put("chartDisplay", new Boolean(AppUtils.getRequestNvlValue(request, "chartDisplay").length()>0? AppUtils.getRequestNvlValue(request, "chartDisplay").equals("3D"):rr.isChartDisplayIn3D()));
601 additionalChartOptionsMap.put("lastSeriesALineChart", new Boolean(rr.isLastSeriesALineChart()));
602 } else if (chartType.equals(AppConstants.GT_LINE)) {
603 additionalChartOptionsMap.put("chartOrientation", new Boolean((AppUtils.getRequestNvlValue(request, "chartOrientation").length()>0?AppUtils.getRequestNvlValue(request, "chartOrientation").equals("vertical"):rr.isVerticalOrientation())) );
604 //additionalChartOptionsMap.put("secondaryChartRenderer", AppUtils.getRequestNvlValue(request, "secondaryChartRenderer").length()>0? AppUtils.getRequestNvlValue(request, "secondaryChartRenderer"):rr.getSecondaryChartRenderer());
605 additionalChartOptionsMap.put("chartDisplay", new Boolean(AppUtils.getRequestNvlValue(request, "chartDisplay").length()>0? AppUtils.getRequestNvlValue(request, "chartDisplay").equals("3D"):rr.isChartDisplayIn3D()));
606 additionalChartOptionsMap.put("lastSeriesABarChart", new Boolean(rr.isLastSeriesABarChart()));
607 } else if (chartType.equals(AppConstants.GT_TIME_DIFFERENCE_CHART)) {
608 additionalChartOptionsMap.put("intervalFromDate",AppUtils.getRequestNvlValue(request, "intervalFromDate").length()>0?AppUtils.getRequestNvlValue(request, "intervalFromDate"):rr.getIntervalFromdate());
609 additionalChartOptionsMap.put("intervalToDate", AppUtils.getRequestNvlValue(request, "intervalToDate").length()>0? AppUtils.getRequestNvlValue(request, "intervalToDate"):rr.getIntervalTodate());
610 additionalChartOptionsMap.put("intervalLabel", AppUtils.getRequestNvlValue(request, "intervalLabel").length()>0? AppUtils.getRequestNvlValue(request, "intervalLabel"):rr.getIntervalLabel());
611 } else if (chartType.equals(AppConstants.GT_REGRESSION)) {
612 additionalChartOptionsMap.put("regressionType",AppUtils.getRequestNvlValue(request, "regressionType").length()>0?AppUtils.getRequestNvlValue(request, "regressionType"):rr.getLinearRegression());
613 additionalChartOptionsMap.put("linearRegressionColor",nvl(rr.getLinearRegressionColor()));
614 additionalChartOptionsMap.put("expRegressionColor",nvl(rr.getExponentialRegressionColor()));
615 additionalChartOptionsMap.put("maxRegression",nvl(rr.getCustomizedRegressionPoint()));
616 } else if (chartType.equals(AppConstants.GT_STACK_BAR) ||chartType.equals(AppConstants.GT_STACKED_HORIZ_BAR) || chartType.equals(AppConstants.GT_STACKED_HORIZ_BAR_LINES)
617 || chartType.equals(AppConstants.GT_STACKED_VERT_BAR) || chartType.equals(AppConstants.GT_STACKED_VERT_BAR_LINES)
619 additionalChartOptionsMap.put("overlayItemValue",new Boolean(nvl(rr.getOverlayItemValueOnStackBar()).equals("Y")));
621 additionalChartOptionsMap.put("legendPosition", nvl(rr.getLegendPosition()));
622 additionalChartOptionsMap.put("hideToolTips", new Boolean(rr.hideChartToolTips()));
623 additionalChartOptionsMap.put("hideLegend", new Boolean(AppUtils.getRequestNvlValue(request, "hideLegend").length()>0? AppUtils.getRequestNvlValue(request, "hideLegend").equals("Y"):rr.hideChartLegend()));
624 additionalChartOptionsMap.put("labelAngle", nvl(rr.getLegendLabelAngle()));
625 additionalChartOptionsMap.put("maxLabelsInDomainAxis", nvl(rr.getMaxLabelsInDomainAxis()));
626 additionalChartOptionsMap.put("rangeAxisLowerLimit", nvl(rr.getRangeAxisLowerLimit()));
627 additionalChartOptionsMap.put("rangeAxisUpperLimit", nvl(rr.getRangeAxisUpperLimit()));
630 boolean totalOnChart = false;
631 totalOnChart = AppUtils.getRequestNvlValue(request, "totalOnChart").equals("Y");
632 String filename = null;
633 ArrayList graphURL = new ArrayList();
634 ArrayList chartNames = new ArrayList();
635 ArrayList fileNames = new ArrayList();
636 List l = rr.getAllColumns();
637 List lGroups = rr.getAllChartGroups();
638 HashMap mapYAxis = rr.getAllChartYAxis(rr.getReportParamValues());
639 String chartLeftAxisLabel = rr.getFormFieldFilled(nvl(rr.getChartLeftAxisLabel()));
640 String chartRightAxisLabel = rr.getFormFieldFilled(nvl(rr.getChartRightAxisLabel()));
641 int displayTotalOnChart = 0;
642 HashMap formValues = Globals.getRequestParamtersMap(request, false);
644 for (Iterator iterC = l.iterator(); iterC.hasNext();) {
645 DataColumnType dc = (DataColumnType) iterC.next();
646 if(nvl(dc.getColName()).equals(AppConstants.RI_CHART_TOTAL_COL)) {
647 displayTotalOnChart = 1;
651 String legendColumnName = (rr.getChartLegendColumn()!=null)?rr.getChartLegendColumn().getDisplayName():"Legend Column";
657 if(rr.hasSeriesColumn() && chartType.equals(AppConstants.GT_TIME_SERIES) && (lGroups==null || lGroups.size() <= 0)) { /** Check whether Report has only category columns if so then all the columns will open in seperate chart - sundar**/
658 for (int i=0; i<rr.getChartValueColumnAxisList(AppConstants.CHART_ALL_COLUMNS, formValues).size();i++) {
659 String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():"";
660 chartTitle = rr.getFormFieldFilled(chartTitle);
661 downloadFileName = AppUtils.getTempFolderPath()+"cr_"+pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png";
664 Image image = Image.getInstance(downloadFileName);
666 } catch (MalformedURLException e) {
667 logger.error(EELFLoggerDelegate.errorLogger, MALFORMEDURLEXCEPTION_MSG,
669 } catch (BadElementException e) {
670 logger.error(EELFLoggerDelegate.errorLogger, BADELEMENTEXCEPTION_MSG,
672 } catch (FileNotFoundException e) {
673 logger.error(EELFLoggerDelegate.errorLogger, FILENOTFOUNDEXCEPTION_MSG,
675 } catch (IOException e) {
676 logger.error(EELFLoggerDelegate.errorLogger, IOEXCEPTION_MSG, e);
680 } else { /** first check the columns to be opened in new charts and loop around in ChartGen generate chart function - sundar**/
681 String tempChartGroupPrev = "";
682 String tempChartGroupCurrent = "";
683 for (int i=0; i<lGroups.size();i++) {
684 String chartGroupOrg = (String) lGroups.get(i);
685 String chartYAxis = (String) mapYAxis.get(chartGroupOrg);
686 if(nvl(chartGroupOrg).length()>0)
687 tempChartGroupCurrent = chartGroupOrg.substring(0,chartGroupOrg.lastIndexOf("|"));
689 tempChartGroupPrev = ((String) lGroups.get(i-1)).substring(0,((String) lGroups.get(i-1)).lastIndexOf("|"));
690 if(tempChartGroupCurrent.equals(tempChartGroupPrev))
692 String chartGroup = chartGroupOrg;
694 downloadFileName = AppUtils.getTempFolderPath()+"cr_"+pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png";
695 String chartTitle = (Globals.getDisplayChartTitle()? (chartGroup!=null && chartGroup.indexOf("|") > 0 ?chartGroup.substring(0,chartGroup.lastIndexOf("|")):rr.getReportName()):"");
696 chartTitle = rr.getFormFieldFilled(chartTitle);
697 String leftAxisLabel = "";
698 if(!rr.isMultiSeries()) {
699 leftAxisLabel = ((chartYAxis!=null && chartYAxis.indexOf("|") > 0) ? chartYAxis.substring(0,chartYAxis.lastIndexOf("|")): chartLeftAxisLabel );
701 leftAxisLabel = chartLeftAxisLabel;
706 Image image = Image.getInstance(downloadFileName);
708 } catch (MalformedURLException e) {
709 logger.error(EELFLoggerDelegate.errorLogger, MALFORMEDURLEXCEPTION_MSG,
711 } catch (BadElementException e) {
712 logger.error(EELFLoggerDelegate.errorLogger, BADELEMENTEXCEPTION_MSG,
714 } catch (FileNotFoundException e) {
715 logger.error(EELFLoggerDelegate.errorLogger, FILENOTFOUNDEXCEPTION_MSG,
717 } catch (IOException e) {
718 logger.error(EELFLoggerDelegate.errorLogger, IOEXCEPTION_MSG, e);
722 if(!chartType.equals(AppConstants.GT_PIE_MULTIPLE)) {
723 for (int i=0; i<rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).size();i++) {
725 downloadFileName = AppUtils.getTempFolderPath()+"cr_"+ pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_"+i+".png";
726 String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():"";
727 chartTitle = rr.getFormFieldFilled(chartTitle);
729 filename = null; /*(String) ChartGen.generateChart( chartType,
730 request.getSession(),
735 (chartType.equals(AppConstants.GT_PIE_MULTIPLE))?rr.getChartDisplayNamesList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartDisplayNamesList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).subList(i, i+1),
736 (chartType.equals(AppConstants.GT_PIE_MULTIPLE))?rr.getChartColumnColorsList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartColumnColorsList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).subList(i, i+1),
737 (chartType.equals(AppConstants.GT_PIE_MULTIPLE))?rr.getChartValueColumnAxisList(AppConstants.CHART_ALL_COLUMNS, formValues):rr.getChartValueColumnAxisList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).subList(i, i+1),
741 rr.getChartWidthAsInt(),
742 rr.getChartHeightAsInt(),
743 rr.getChartValueColumnsList(AppConstants.CHART_NEWCHART_COLUMNS, formValues).subList(i,i+1),
744 rr.hasSeriesColumn(),
745 //rr.isChartMultiSeries(),
750 AppConstants.WEB_VERSION,
751 additionalChartOptionsMap,
755 Image image = Image.getInstance(downloadFileName);
757 } catch (MalformedURLException e) {
758 logger.error(EELFLoggerDelegate.errorLogger,
759 MALFORMEDURLEXCEPTION_MSG, e);
760 } catch (BadElementException e) {
761 logger.error(EELFLoggerDelegate.errorLogger,
762 BADELEMENTEXCEPTION_MSG, e);
763 } catch (FileNotFoundException e) {
764 logger.error(EELFLoggerDelegate.errorLogger,
765 FILENOTFOUNDEXCEPTION_MSG, e);
766 } catch (IOException e) {
767 logger.error(EELFLoggerDelegate.errorLogger, IOEXCEPTION_MSG, e);
771 /** second rest of the columns are merged to one single chart - sundar**/
772 // System.out.println(" rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS) " + rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS));
773 // System.out.println(" rr.getChartValueColumnAxisList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS) " + rr.getChartValueColumnAxisList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS));
774 // System.out.println(" rr.getChartValueColumnsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS) " + rr.getChartValueColumnsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS));
776 if((!(lGroups!=null && lGroups.size() > 0))) {
778 if(/*chartType.equals(AppConstants.GT_TIME_SERIES) && */rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues)!=null && rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues).size()>0) {
779 downloadFileName = AppUtils.getTempFolderPath()+"cr_"+ pb.getUserId()+"_"+request.getSession().getId()+"_"+rr.getReportID()+"_All.png";
780 String chartTitle = Globals.getDisplayChartTitle()? rr.getReportName():"";
781 chartTitle = rr.getFormFieldFilled(chartTitle);
783 filename = null; /*(String) ChartGen.generateChart( chartType,
784 request.getSession(),
789 rr.getChartDisplayNamesList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues),
790 rr.getChartColumnColorsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues),
791 rr.getChartValueColumnAxisList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues),
795 rr.getChartWidthAsInt(),
796 rr.getChartHeightAsInt(),
797 rr.getChartValueColumnsList(AppConstants.CHART_WITHOUT_NEWCHART_COLUMNS, formValues),
798 rr.hasSeriesColumn(),
799 //rr.isChartMultiSeries(),
804 AppConstants.WEB_VERSION,
805 additionalChartOptionsMap,
809 Image image = Image.getInstance(downloadFileName);
811 } catch (MalformedURLException e) {
812 logger.error(EELFLoggerDelegate.errorLogger,
813 MALFORMEDURLEXCEPTION_MSG, e);
814 } catch (BadElementException e) {
815 logger.error(EELFLoggerDelegate.errorLogger,
816 BADELEMENTEXCEPTION_MSG, e);
817 } catch (FileNotFoundException e) {
818 logger.error(EELFLoggerDelegate.errorLogger,
819 FILENOTFOUNDEXCEPTION_MSG, e);
820 } catch (IOException e) {
821 logger.error(EELFLoggerDelegate.errorLogger, IOEXCEPTION_MSG, e);
824 } // Stacked Chart Check
825 } // else no Series Column
829 } catch (Exception e) {
830 logger.error(EELFLoggerDelegate.errorLogger, "Exception in generateNewImage", e);
832 return images.size()>0?images:null;
837 private final int DEFAULT_PDF_DISPLAY_WIDTH = 10;
839 private int paintPdfData(final HttpServletRequest request, final Document document, final ReportData rd,
840 final ReportRuntime rr, final String sql_whole) throws DocumentException, RaptorException, IOException {
842 final int mb = 1024 * 1024;
843 final Runtime runtime = Runtime.getRuntime();
846 final float f[] = getRelativeWidths(rd, AppConstants.RT_CROSSTAB.equals(rr.getReportType()));
847 PdfPTable table = new PdfPTable(f);
848 table.setWidthPercentage(100f);
849 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
850 table.getDefaultCell().setVerticalAlignment(Rectangle.ALIGN_BOTTOM);
852 final ReportDefinition rdef = (new ReportHandler()).loadReportDefinition(request, rr.getReportID());
854 final List allColumns = rdef.getAllColumns();
856 final float[] repotWidths = new float[rdef.getVisibleColumnCount()];
858 float pdfDisplayWidth = 0;
859 for (final Iterator iter = allColumns.iterator(); iter.hasNext(); ) {
860 final DataColumnType dct = (DataColumnType) iter.next();
861 if (dct.isVisible()) {
863 if (dct.getPdfDisplayWidthInPxls() == null || dct.getPdfDisplayWidthInPxls().isEmpty() || dct
864 .getPdfDisplayWidthInPxls().startsWith("null")) {
865 pdfDisplayWidth = DEFAULT_PDF_DISPLAY_WIDTH;
867 pdfDisplayWidth = Float.parseFloat(dct.getPdfDisplayWidthInPxls());
870 repotWidths[columnIdx++] = pdfDisplayWidth;
874 table.setWidths(repotWidths);
876 //TODO: check title and subtitle
877 final HttpSession session = request.getSession();
878 final String drilldown_index = (String) session.getAttribute("drilldown_index");
881 index = Integer.parseInt(drilldown_index);
882 } catch (NumberFormatException ex) {
885 final String titleRep = (String) session.getAttribute("TITLE_" + index);
886 final String subtitle = (String) session.getAttribute("SUBTITLE_" + index);
888 if (nvl(titleRep).length() > 0 && nvl(subtitle).length() > 0) {
889 table.setHeaderRows(3);
890 } else if (nvl(titleRep).length() > 0) {
891 table.setHeaderRows(2);
893 table.setHeaderRows(1);
895 table = paintPdfReportHeader(request, document, table, rr, f);
896 paintPdfTableHeader(document, rd, table);
899 final int fragmentsize = 30; //for memory management
901 rd.reportDataRows.resetNext();
902 DataRow dr = rd.reportDataRows.getNext();
904 if (nvl(sql_whole).length() > 0 && AppConstants.RT_LINEAR.equals(rr.getReportType())) {
905 try (final Connection conn = ConnectionUtils.getConnection(rr.getDbInfo());
906 final Statement st = conn.createStatement();
907 final ResultSet rs = st.executeQuery(sql_whole);) {
909 logger.debug(EELFLoggerDelegate.debugLogger, ("************* Map Whole SQL *************"));
910 logger.debug(EELFLoggerDelegate.debugLogger, (sql_whole));
911 logger.debug(EELFLoggerDelegate.debugLogger, ("*****************************************"));
913 final ResultSetMetaData rsmd = rs.getMetaData();
914 final int numberOfColumns = rsmd.getColumnCount();
920 final Map colHash = new HashMap();
921 for (int i = 1; i <= numberOfColumns; i++) {
922 colHash.put(rsmd.getColumnLabel(i).toUpperCase(), rs.getString(i));
924 rd.reportDataRows.resetNext();
926 dr = rd.reportDataRows.getNext();
928 for (dr.resetNext(); dr.hasNext(); ) {
929 final DataValue dv = dr.getNext();
931 final String value = nvl((String) colHash.get(dv.getColId().toUpperCase()));
932 if (dv.isVisible()) {
934 final HtmlFormatter cfmt = dv.getCellFormatter();
935 final HtmlFormatter rfmt = dv.getRowFormatter();
937 final Font cellFont = FontFactory.getFont(FONT_FAMILY,
939 Font.NORMAL, Color.BLACK);
941 cellFormatterFont(cfmt, cellFont);
942 } else if (rfmt != null) {
943 cellFormatterFont(rfmt, cellFont);
946 cellFont.setStyle(Font.BOLD);
950 final String cellValue = strip.stripHtml(value.trim());
951 final PdfPCell cell = new PdfPCell(new Paragraph(cellValue, cellFont));
953 //row background color can be overwritten by cell background color
954 cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
956 if (nvl(dv.getAlignment()).trim().length() > 0) {
957 cell.setHorizontalAlignment(ElementTags.alignmentValue(dv.getAlignment()));
959 cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
963 formatterCell(cfmt, cell);
964 } else if (rfmt != null) {
965 formatterCell(rfmt, cell);
975 if (rd.reportDataTotalRow != null) {
976 for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext(); idx++) {
977 dr = rd.reportDataTotalRow.getNext();
978 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
979 final Font rowHeaderFont = FontFactory.getFont(FONT_FAMILY,
981 Font.NORMAL, Color.BLACK);
982 rowHeaderFont.setStyle(Font.BOLD);
983 rowHeaderFont.setSize(FONT_SIZE + 1f);
984 table.getDefaultCell().setBackgroundColor(getRowBackgroundColor(dr, idx));
985 table.addCell(new Paragraph("Total", rowHeaderFont));
987 addTotalRowColumns(table, dr, idx);
988 if (idx % fragmentsize == fragmentsize - 1) {
990 table.deleteBodyRows();
991 table.setSkipFirstHeader(true);
996 } catch (final SQLException | ReportSQLException ex) {
997 throw new RaptorException(ex);
998 } catch (final Exception ex) {
999 if (!(ex.getCause() instanceof java.net.SocketException)) {
1000 throw new RaptorException(ex);
1003 //document.add(table);
1005 if (rr.getReportType().equals(AppConstants.RT_LINEAR)) {
1006 for (rd.reportDataRows.resetNext(); rd.reportDataRows.hasNext(); idx++) {
1008 if (runtime.freeMemory() / mb <= ((runtime.maxMemory() / mb) * Globals.getMemoryThreshold()
1013 dr = rd.reportDataRows.getNext();
1015 addRowHeader(table, dr, idx, rd);
1017 addRowColumns(table, dr, idx);
1019 if (idx % fragmentsize == fragmentsize - 1) {
1020 document.add(table);
1021 table.deleteBodyRows();
1022 table.setSkipFirstHeader(true);
1026 if (rd.reportDataTotalRow != null) {
1027 for (rd.reportDataTotalRow.resetNext(); rd.reportDataTotalRow.hasNext(); idx++) {
1028 dr = rd.reportDataTotalRow.getNext();
1029 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1030 Font rowHeaderFont = FontFactory.getFont(FONT_FAMILY,
1032 Font.NORMAL, Color.BLACK);
1033 rowHeaderFont.setStyle(Font.BOLD);
1034 rowHeaderFont.setSize(FONT_SIZE + 1f);
1035 table.getDefaultCell().setBackgroundColor(getRowBackgroundColor(dr, idx));
1036 table.addCell(new Paragraph("Total", rowHeaderFont));
1038 addTotalRowColumns(table, dr, idx);
1039 if (idx % fragmentsize == fragmentsize - 1) {
1040 document.add(table);
1041 table.deleteBodyRows();
1042 table.setSkipFirstHeader(true);
1048 } else if (AppConstants.RT_CROSSTAB.equals(rr.getReportType())) {
1050 final List l = rd.getReportDataList();
1051 boolean first = true;
1052 for (int dataRow = 0; dataRow < l.size(); dataRow++) {
1055 dr = (DataRow) l.get(dataRow);
1056 final Vector<DataValue> rowNames = dr.getRowValues();
1057 for (dr.resetNext(); dr.hasNext(); ) {
1060 HtmlFormatter rfmt = dr.getRowFormatter();
1062 Font cellFont = FontFactory.getFont(FONT_FAMILY,
1064 Font.NORMAL, Color.BLACK);
1066 cellFormatterFont(rfmt, cellFont);
1069 if (rowNames != null) {
1070 for (int i = 0; i < rowNames.size(); i++) {
1071 final DataValue dv = rowNames.get(i);
1072 rfmt = dr.getRowFormatter();
1074 cellFont = FontFactory.getFont(FONT_FAMILY,
1076 Font.NORMAL, Color.BLACK);
1078 cellFormatterFont(rfmt, cellFont);
1080 String cellValue = dv.getDisplayValue();
1081 if (cellValue.indexOf("|#") != -1) {
1082 cellValue = cellValue.substring(0, cellValue.indexOf("|"));
1085 final PdfPCell cell = new PdfPCell(new Paragraph(cellValue, cellFont));
1086 //row background color can be overwritten by cell background color
1087 cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
1089 cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1092 formatterCell(rfmt, cell);
1094 table.addCell(cell);
1100 if (runtime.freeMemory() / mb <= ((runtime.maxMemory() / mb) * Globals.getMemoryThreshold()
1105 //addRowHeader(table,dr,idx,rd);
1107 addRowColumns(table, dr, idx);
1109 if (idx % fragmentsize == fragmentsize - 1) {
1110 document.add(table);
1111 table.deleteBodyRows();
1112 table.setSkipFirstHeader(true);
1119 //document.add(table);
1123 document.add(table);
1124 paintPdfReportFooter(request, document, rr, f);
1129 private void addRowHeader(PdfPTable table, DataRow dr, int idx, ReportData rd) {
1131 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1133 for(rd.reportRowHeaderCols.resetNext();rd.reportRowHeaderCols.hasNext();) {
1134 RowHeaderCol rhc = rd.reportRowHeaderCols.getNext();
1137 RowHeader rh = rhc.getNext();
1138 //System.out.println(" =============== RowHeader\n "+rh);
1140 Font rowHeaderFont = FontFactory.getFont(FONT_FAMILY,
1142 Font.NORMAL, Color.BLACK);
1144 rowHeaderFont.setStyle(Font.BOLD);
1145 rowHeaderFont.setSize(FONT_SIZE+1f);
1148 if(rh.getColSpan()>0) {
1149 table.getDefaultCell().setColspan(rh.getColSpan());
1150 table.getDefaultCell().setBackgroundColor(getRowBackgroundColor(dr, idx));
1151 table.addCell(new Paragraph(strip.stripHtml(rh.getRowTitle()),rowHeaderFont));
1156 private void addRowColumns(PdfPTable table, DataRow dr, int idx) {
1158 table.getDefaultCell().setColspan(1);
1160 for(dr.resetNext();dr.hasNext();)
1162 DataValue dv = dr.getNext();
1163 //System.out.println(columnCount +" --> "+dv);
1164 if(dv.isVisible()) {
1165 HtmlFormatter cfmt = dv.getCellFormatter();
1166 HtmlFormatter rfmt = dv.getRowFormatter();
1168 Font cellFont = FontFactory.getFont(FONT_FAMILY,
1170 Font.NORMAL, Color.BLACK);
1172 cellFormatterFont(cfmt,cellFont);
1174 else if(rfmt != null) {
1175 cellFormatterFont(rfmt,cellFont);
1179 cellFont.setStyle(Font.BOLD);
1183 String cellValue = strip.stripHtml(dv.getDisplayValue().trim());
1184 PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont));
1186 //row background color can be overwritten by cell background color
1187 cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
1189 if(nvl(dv.getAlignment()).trim().length()>0)
1190 cell.setHorizontalAlignment(ElementTags.alignmentValue(dv.getAlignment()));
1192 cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1195 formatterCell(cfmt,cell);
1197 else if(rfmt != null) {
1198 formatterCell(rfmt,cell);
1201 table.addCell(cell);
1208 private void addTotalRowColumns(PdfPTable table, DataRow dr, int idx) {
1210 table.getDefaultCell().setColspan(1);
1215 DataValue dv = dr.getNext();
1216 //System.out.println(columnCount +" --> "+dv);
1217 if(dv.isVisible()) {
1218 HtmlFormatter cfmt = dv.getCellFormatter();
1219 HtmlFormatter rfmt = dv.getRowFormatter();
1221 Font cellFont = FontFactory.getFont(FONT_FAMILY,
1223 Font.NORMAL, Color.BLACK);
1225 cellFormatterFont(cfmt,cellFont);
1227 else if(rfmt != null) {
1228 cellFormatterFont(rfmt,cellFont);
1232 cellFont.setStyle(Font.BOLD);
1236 String cellValue = strip.stripHtml(dv.getDisplayValue().trim());
1237 PdfPCell cell = new PdfPCell(new Paragraph(cellValue,cellFont));
1239 //row background color can be overwritten by cell background color
1240 cell.setBackgroundColor(getRowBackgroundColor(dr, idx));
1242 if(nvl(dv.getAlignment()).trim().length()>0)
1243 cell.setHorizontalAlignment(ElementTags.alignmentValue(dv.getAlignment()));
1245 cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1248 formatterCell(cfmt,cell);
1250 else if(rfmt != null) {
1251 formatterCell(rfmt,cell);
1254 table.addCell(cell);
1261 private void formatterCell(HtmlFormatter fmt, PdfPCell cell) {
1263 if(nvl(fmt.getBgColor()).trim().length()>0)
1264 cell.setBackgroundColor(Color.decode(fmt.getBgColor()));
1265 if(nvl(fmt.getAlignment()).trim().length()>0)
1266 cell.setHorizontalAlignment(ElementTags.alignmentValue(fmt.getAlignment()));
1269 private void cellFormatterFont(HtmlFormatter fmt, Font font) {
1272 font.setStyle(Font.BOLD);
1274 font.setStyle(Font.ITALIC);
1275 if(fmt.isUnderline())
1276 font.setStyle(Font.UNDERLINE);
1277 if(fmt.getFontColor().trim().length()>0)
1278 font.setColor(Color.decode(fmt.getFontColor()));
1279 if(fmt.getFontSize().trim().length()>0)
1280 font.setSize(Float.parseFloat(fmt.getFontSize())-Globals.getDataFontSizeOffset());
1281 // if(fmt.getFontFace().trim().length()>0)
1282 // cellFont.setFamily()
1286 private Color getRowBackgroundColor(DataRow dr, int idx) {
1288 Color color = Color.decode(Globals.getDataDefaultBackgroundHexCode());
1290 HtmlFormatter rhf = dr.getRowFormatter();
1291 if(rhf!=null && nvl(rhf.getBgColor()).trim().length()>0)
1293 color = Color.decode(rhf.getBgColor());
1295 else if(pb.isAlternateColor() && idx%2==0)
1297 color = Color.decode(Globals.getDataBackgroundAlternateHexCode());
1303 private int getTotalVisbleColumns(ReportData rd) {
1305 int totalVisbleColumn = rd.getTotalColumnCount();
1306 for(rd.reportDataRows.resetNext();rd.reportDataRows.hasNext();)
1308 DataRow dr = rd.reportDataRows.getNext();
1309 for(dr.resetNext();dr.hasNext();) {
1310 DataValue dv = dr.getNext();
1312 totalVisbleColumn--;
1318 return totalVisbleColumn;
1322 private int getFirstRowIndex(ReportRuntime rr) {
1323 return (pb.getCurrentPage()>0)?pb.getCurrentPage()*rr.getPageSize()+1 : 1;
1326 private float[] getRelativeWidths(ReportData rd, boolean crosstab){
1328 int totalColumns = getTotalVisbleColumns(rd);
1329 /*if(rd.reportTotalRowHeaderCols!=null) {
1336 if(totalColumns == 0 )
1339 float[] relativeWidths = new float[totalColumns];
1340 //initial widths are even
1341 for(int i=0; i<relativeWidths.length; i++)
1342 relativeWidths[i] = 10f;
1345 boolean firstPass = true;
1347 for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();)
1350 /*if(rd.reportTotalRowHeaderCols!=null) {
1351 String columnWidth = "5";
1353 if(columnWidth != null && columnWidth.trim().endsWith("%"))
1354 relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
1359 for(rd.reportRowHeaderCols.resetNext();rd.reportRowHeaderCols.hasNext();) {
1360 String columnWidth = rd.reportRowHeaderCols.getNext().getColumnWidth();
1362 if(columnWidth != null && columnWidth.trim().endsWith("%"))
1363 relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
1370 ColumnHeaderRow chr = rd.reportColumnHeaderRows.getNext();
1371 for (chr.resetNext(); chr.hasNext();) {
1373 ColumnHeader ch = chr.getNext();
1375 if(ch.isVisible()) {
1377 String columnWidth = ch.getColumnWidth();
1379 if(ch.getColSpan() <= 1){
1380 if(columnWidth != null && columnWidth.trim().endsWith("%"))
1381 relativeWidths[index] = Float.parseFloat(removeLastCharacter(columnWidth));
1384 for(int i=0; i<ch.getColSpan(); i++) {
1386 if(columnWidth != null && columnWidth.trim().endsWith("%"))
1387 relativeWidths[index] =
1388 (Float.parseFloat(removeLastCharacter(columnWidth)))/ch.getColSpan();
1397 return relativeWidths;
1400 public static String removeLastCharacter(String str) {
1401 return str.substring(0, str.length()-1);
1404 private PdfPTable paintPdfReportHeader(HttpServletRequest request, Document document, PdfPTable table, ReportRuntime rr, float[] f)
1405 throws DocumentException, IOException {
1407 HttpSession session = request.getSession();
1408 String drilldown_index = (String) session.getAttribute("drilldown_index");
1411 index = Integer.parseInt(drilldown_index);
1412 } catch (NumberFormatException ex) {
1415 String title = (String) session.getAttribute("TITLE_"+index);
1416 String subtitle = (String) session.getAttribute("SUBTITLE_"+index);
1417 if(nvl(title).length()>0) {
1418 //PdfPTable table = new PdfPTable(1);
1419 table.setWidthPercentage(100f);
1420 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1421 table.getDefaultCell().setVerticalAlignment(Rectangle.ALIGN_BOTTOM);
1424 Font font = FontFactory.getFont(FONT_FAMILY,
1429 //addEmptyRows(table,1);
1430 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1431 //table.getDefaultCell().setBackgroundColor(Color.decode(Globals.getDataTableHeaderBackgroundFontColor()));
1432 title = Utils.replaceInString(title, "<BR/>", " ");
1433 title = Utils.replaceInString(title, "<br/>", " ");
1434 title = Utils.replaceInString(title, "<br>", " ");
1435 title = strip.stripHtml(nvl(title).trim());
1436 //subtitle = Utils.replaceInString(subtitle, "<BR/>", " ");
1437 //subtitle = Utils.replaceInString(subtitle, "<br/>", " ");
1438 //subtitle = Utils.replaceInString(subtitle, "<br>", " ");
1439 //subtitle = strip.stripHtml(nvl(subtitle).trim());
1440 StyleSheet styles = new StyleSheet();
1442 HTMLWorker htmlWorker = new HTMLWorker(document);
1443 ArrayList cc = new ArrayList();
1444 cc = htmlWorker.parseToList(new StringReader(subtitle), styles);
1446 Phrase p1 = new Phrase();
1447 for (int i = 0; i < cc.size(); i++){
1448 Element elem = (Element)cc.get(i);
1449 ArrayList al = elem.getChunks();
1450 for (int j = 0; j < al.size(); j++) {
1451 Chunk chunk = (Chunk) al.get(j);
1452 chunk.font().setSize(6.0f);
1456 //cell = new PdfPCell(p1);
1457 StyleSheet style = new StyleSheet();
1458 style.loadTagStyle("font", "font-size", "3");
1459 style.loadTagStyle("font", "size", "3");
1460 styles.loadStyle("pdfFont1", "size", "11px");
1461 styles.loadStyle("pdfFont1", "font-size", "11px");
1462 /*ArrayList p = HTMLWorker.parseToList(new StringReader(nvl(title)), style);
1463 for (int k = 0; k < p.size(); ++k){
1464 document.add((com.lowagie.text.Element)p.get(k));
1466 //p1.font().setSize(3.0f);
1467 PdfPCell titleCell = new PdfPCell(new Phrase(title, font));
1468 titleCell.setColspan(rr.getVisibleColumnCount());
1469 PdfPCell subtitleCell = new PdfPCell(p1);
1470 subtitleCell.setColspan(rr.getVisibleColumnCount());
1471 titleCell.setHorizontalAlignment(1);
1472 subtitleCell.setHorizontalAlignment(1);
1473 table.addCell(titleCell);
1474 table.addCell(subtitleCell);
1475 //document.add(table);
1481 private void paintPdfReportFooter(HttpServletRequest request, Document document, ReportRuntime rr, float[] f)
1482 throws DocumentException, IOException {
1484 HttpSession session = request.getSession();
1485 String drilldown_index = (String) session.getAttribute("drilldown_index");
1488 index = Integer.parseInt(drilldown_index);
1489 } catch (NumberFormatException ex) {
1493 String title = (String) session.getAttribute("FOOTER_"+index);
1494 if(nvl(title).length()>0) {
1495 PdfPTable table = new PdfPTable(1);
1496 table.setWidthPercentage(100f);
1497 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1498 table.getDefaultCell().setVerticalAlignment(Rectangle.ALIGN_BOTTOM);
1500 Font font = FontFactory.getFont(FONT_FAMILY,
1506 //addEmptyRows(table,1);
1507 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1508 //table.getDefaultCell().setBackgroundColor(Color.decode(Globals.getDataTableHeaderBackgroundFontColor()));
1509 /*title = Utils.replaceInString(title, "<BR/>", " ");
1510 title = Utils.replaceInString(title, "<br/>", " ");
1511 title = Utils.replaceInString(title, "<br>", " ");
1512 title = strip.stripHtml(nvl(title).trim());*/
1513 StyleSheet style = new StyleSheet();
1515 HTMLWorker htmlWorker = new HTMLWorker(document);
1516 ArrayList cc = new ArrayList();
1517 cc = htmlWorker.parseToList(new StringReader(title), style);
1519 Phrase p1 = new Phrase();
1520 for (int i = 0; i < cc.size(); i++){
1521 Element elem = (Element)cc.get(i);
1522 ArrayList al = elem.getChunks();
1523 for (int j = 0; j < al.size(); j++) {
1524 Chunk chunk = (Chunk) al.get(j);
1525 chunk.font().setSize(6.0f);
1531 HTMLWorker.parseToList(new StringReader(nvl(title)), style);*/
1532 PdfPCell titleCell = new PdfPCell(p1);
1533 titleCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1534 table.addCell(titleCell);
1536 document.add(table);
1542 private void paintPdfTableHeader(Document document, ReportData rd, PdfPTable table)
1543 throws DocumentException {
1545 Font font = FontFactory.getFont(FONT_FAMILY,
1548 Color.decode(Globals.getDataTableHeaderFontColor()));
1549 //table.setHeaderRows(1);
1550 table.getDefaultCell().setHorizontalAlignment(Rectangle.ALIGN_CENTER);
1551 table.getDefaultCell().setBackgroundColor(Color.decode(Globals.getDataTableHeaderBackgroundFontColor()));
1554 boolean firstPass = true;
1556 /*if(rd.reportTotalRowHeaderCols!=null) {
1558 table.addCell(new Paragraph("No.", font));
1562 for (rd.reportColumnHeaderRows.resetNext(); rd.reportColumnHeaderRows.hasNext();)
1565 for(rd.reportRowHeaderCols.resetNext();rd.reportRowHeaderCols.hasNext();) {
1567 table.addCell(new Paragraph("No.", font));
1570 RowHeaderCol rhc = rd.reportRowHeaderCols.getNext();
1571 title = rhc.getColumnTitle();
1572 title = Utils.replaceInString(title,"_nl_", " \n");
1573 table.addCell(new Paragraph(title,font));
1578 ColumnHeaderRow chr = rd.reportColumnHeaderRows.getNext();
1579 for (chr.resetNext(); chr.hasNext();) {
1580 ColumnHeader ch = chr.getNext();
1581 //System.out.println(ch);
1582 if(ch.isVisible()) {
1583 title = ch.getColumnTitle();
1584 title = Utils.replaceInString(title,"_nl_", " \n");
1585 table.addCell(new Paragraph(title,font));
1591 public static String currentTime(String pattern) {
1593 SimpleDateFormat oracleDateFormat = new SimpleDateFormat("MM/dd/yyyy kk:mm:ss");
1594 Date sysdate = oracleDateFormat.parse(ReportLoader.getSystemDateTime());
1595 SimpleDateFormat dtimestamp = new SimpleDateFormat(Globals.getScheduleDatePattern());
1596 return dtimestamp.format(sysdate)+" "+Globals.getTimeZone();
1597 //paramList.add(new IdNameValue("DATE", dtimestamp.format(sysdate)+" "+Globals.getTimeZone()));
1598 } catch(Exception ex) {}
1600 SimpleDateFormat s = new SimpleDateFormat(pattern);
1601 s.setTimeZone(TimeZone.getTimeZone(Globals.getTimeZone()));
1602 //System.out.println("^^^^^^^^^^^^^^^^^^^^ " + Calendar.getInstance().getTime());
1603 //System.out.println("^^^^^^^^^^^^^^^^^^^^ " + s.format(Calendar.getInstance().getTime()));
1604 return s.format(Calendar.getInstance().getTime());
1607 private PdfBean preparePdfBean(HttpServletRequest request,ReportRuntime rr) {
1608 PdfBean pb = new PdfBean();
1610 pb.setUserId(AppUtils.getUserID(request));
1612 pb.setWhereToShowPageNumber(Globals.getPageNumberPosition());
1613 pb.setAlternateColor(Globals.isDataAlternateColor());
1614 pb.setTimestampPattern(Globals.getDatePattern());
1618 temp = Integer.parseInt(request.getParameter(AppConstants.RI_NEXT_PAGE));
1619 } catch (NumberFormatException e) {}
1620 pb.setCurrentPage(temp);
1622 //pb.setPortrait( trueORfalse(request.getParameter("isPortrait"),true));
1623 pb.setPortrait(trueORfalse(rr.getPDFOrientation() == "portait"?"true":"false", true));
1624 //pb.setCoverPageIncluded( trueORfalse(request.getParameter("isCoverPageIncluded"), true));
1625 //if(Globals.isCoverPageNeeded()) {
1626 pb.setCoverPageIncluded(Globals.isCoverPageNeeded()?rr.isPDFCoverPage():false);
1628 pb.setTitle(nvl(request.getParameter("title")));
1629 pb.setPagesize(nvls(request.getParameter("pagesize"),"LETTER"));
1631 pb.setLogo1Url(rr.getPDFLogo1());
1632 pb.setLogo2Url(rr.getPDFLogo2());
1633 pb.setLogo1Size(rr.getPDFLogo1Size());
1634 pb.setLogo2Size(rr.getPDFLogo2Size());
1635 pb.setFullWebContextPath(request.getSession().getServletContext().getRealPath(File.separator));
1638 pb.setDisplayChart(nvl(rr.getChartType()).trim().length()>0 && rr.getDisplayChart());
1640 String id = nvl(request.getParameter("pdfAttachmentKey")).trim();
1641 String log_id = nvl(request.getParameter("log_id")).trim();
1642 if(id.length()>0 && log_id.length()>0)
1643 pb.setAttachmentOfEmail(true);
1648 private boolean trueORfalse(String str) {
1649 return (str != null) && (str.equalsIgnoreCase("true"));
1652 private boolean trueORfalse(String str,boolean b_default) {
1653 return str==null ? b_default : (str.equalsIgnoreCase("true"));