d030c994707dbb21090610cb648e7f16f7a7bed1
[portal/sdk.git] /
1 /*-
2  * ================================================================================
3  * eCOMP Portal SDK
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ================================================================================
19  */
20 /* ===========================================================================================
21  * This class is part of <I>RAPTOR (Rapid Application Programming Tool for OLAP Reporting)</I> 
22  * Raptor : This tool is used to generate different kinds of reports with lot of utilities
23  * ===========================================================================================
24  *
25  * -------------------------------------------------------------------------------------------
26  * ActionHandler.java - This class is used to call actions related to reports.
27  * -------------------------------------------------------------------------------------------
28  *
29  *  
30  *
31  * Changes
32  * -------
33  * 31-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> reportFormFieldPopup iterates form field collections. </LI></UL>       
34  * 18-Aug-2009 : Version 8.5.1 (Sundar);<UL><LI> request Object is passed to prevent caching user/roles - Datamining/Hosting. </LI></UL>        
35  * 13-Aug-2009 : Version 8.5 (Sundar);<UL><LI> reportFormFieldPopup is changed to have effect on textfield with popup. </LI></UL>       
36  * 06-Aug-2009 : Version 9.0 (Sundar);<UL><LI> reportFormFieldPopupB is changed. </LI></UL>     
37  * 29-Jul-2009 : Version 8.4 (Sundar);<UL><LI> Previously report data for dashboard stored only page level data. This has been changed to show all the data up to the maximum specified. </LI></UL>     
38  * 27-Jul-2009 : Version 8.4 (Sundar);<UL><LI>Bug due to not showing back button after child report in drilldown is navigated more than 
39  *                                                                              one page is resolved. </LI></UL>        
40  * 14-Jul-2009 : Version 8.4 (Sundar); <UL><LI>Dashboard reports can now be generated excel as separate sheets or group together in PDF. 
41  *                                             They can also be scheduled.</LI></UL>                                            
42  *
43  */
44 package org.openecomp.portalsdk.analytics.controller;
45
46 import java.io.BufferedWriter;
47 import java.io.File;
48 import java.io.FileWriter;
49 import java.io.IOException;
50 import java.io.PrintWriter;
51 import java.io.StringWriter;
52 import java.io.Writer;
53 import java.sql.Connection;
54 import java.sql.PreparedStatement;
55 import java.sql.SQLException;
56 import java.text.SimpleDateFormat;
57 import java.util.ArrayList;
58 import java.util.Enumeration;
59 import java.util.HashMap;
60 import java.util.Iterator;
61 import java.util.List;
62 import java.util.Map;
63 import java.util.Map.Entry;
64 import java.util.Set;
65 import java.util.TreeMap;
66 import java.util.Vector;
67 import java.util.regex.Matcher;
68 import java.util.regex.Pattern;
69
70 import javax.servlet.http.HttpServletRequest;
71 import javax.servlet.http.HttpSession;
72
73 import org.openecomp.portalsdk.analytics.error.RaptorException;
74 import org.openecomp.portalsdk.analytics.error.RaptorRuntimeException;
75 import org.openecomp.portalsdk.analytics.error.RaptorSchedularException;
76 import org.openecomp.portalsdk.analytics.error.ReportSQLException;
77 import org.openecomp.portalsdk.analytics.error.UserDefinedException;
78 import org.openecomp.portalsdk.analytics.error.ValidationException;
79 import org.openecomp.portalsdk.analytics.model.DataCache;
80 import org.openecomp.portalsdk.analytics.model.ReportHandler;
81 import org.openecomp.portalsdk.analytics.model.ReportLoader;
82 import org.openecomp.portalsdk.analytics.model.SearchHandler;
83 import org.openecomp.portalsdk.analytics.model.base.IdNameColLookup;
84 import org.openecomp.portalsdk.analytics.model.base.IdNameList;
85 import org.openecomp.portalsdk.analytics.model.base.IdNameSql;
86 import org.openecomp.portalsdk.analytics.model.base.ReportSecurity;
87 import org.openecomp.portalsdk.analytics.model.definition.ReportDefinition;
88 import org.openecomp.portalsdk.analytics.model.definition.ReportSchedule;
89 import org.openecomp.portalsdk.analytics.model.runtime.ChartWebRuntime;
90 import org.openecomp.portalsdk.analytics.model.runtime.ErrorJSONRuntime;
91 import org.openecomp.portalsdk.analytics.model.runtime.FormField;
92 import org.openecomp.portalsdk.analytics.model.runtime.FormatProcessor;
93 import org.openecomp.portalsdk.analytics.model.runtime.ReportFormFields;
94 import org.openecomp.portalsdk.analytics.model.runtime.ReportJSONRuntime;
95 import org.openecomp.portalsdk.analytics.model.runtime.ReportRuntime;
96 import org.openecomp.portalsdk.analytics.model.runtime.VisualManager;
97 import org.openecomp.portalsdk.analytics.model.search.ReportSearchResultJSON;
98 import org.openecomp.portalsdk.analytics.system.AppUtils;
99 import org.openecomp.portalsdk.analytics.system.ConnectionUtils;
100 import org.openecomp.portalsdk.analytics.system.DbUtils;
101 import org.openecomp.portalsdk.analytics.system.Globals;
102 import org.openecomp.portalsdk.analytics.system.fusion.domain.QuickLink;
103 import org.openecomp.portalsdk.analytics.util.AppConstants;
104 import org.openecomp.portalsdk.analytics.util.DataSet;
105 import org.openecomp.portalsdk.analytics.util.Utils;
106 import org.openecomp.portalsdk.analytics.view.DataRow;
107 import org.openecomp.portalsdk.analytics.view.DataValue;
108 import org.openecomp.portalsdk.analytics.view.ReportData;
109 import org.openecomp.portalsdk.analytics.xmlobj.DataColumnType;
110 import org.openecomp.portalsdk.analytics.xmlobj.FormFieldType;
111 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
112
113 import com.fasterxml.jackson.databind.DeserializationFeature;
114 import com.fasterxml.jackson.databind.ObjectMapper;
115 import com.fasterxml.jackson.databind.SerializationFeature;
116
117 public class ActionHandler extends org.openecomp.portalsdk.analytics.RaptorObject {
118
119         //private static Log debugLogger = LogFactory.getLog(ActionHandler.class.getName());
120         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ActionHandler.class);
121
122     private void preserveReportRuntimeAsBackup(HttpServletRequest request) {
123         HttpSession session = request.getSession();
124         ArrayList repAl = null;
125
126         if(session.getAttribute(AppConstants.DRILLDOWN_REPORTS_LIST)!=null) 
127                 repAl = ((ArrayList)session.getAttribute(AppConstants.DRILLDOWN_REPORTS_LIST));
128         int index = Integer.parseInt(nvl((String) session.getAttribute(AppConstants.DRILLDOWN_INDEX), "0"));
129         int form_index = Integer.parseInt(nvl((String) session.getAttribute(AppConstants.FORM_DRILLDOWN_INDEX), "0"));
130         int flag = 0;
131         if(repAl ==null || repAl.size() <= 0) {
132                 //session.setAttribute(AppConstants.SI_BACKUP_FOR_REP_ID, ((ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)).getReportID());
133                         //session.setAttribute(AppConstants.SI_REPORT_RUN_BACKUP, request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME));
134                 repAl = new ArrayList();
135                 repAl.add((ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME));
136                 
137         } else { 
138                         if(Globals.getMaxDrillDownLevel() < repAl.size()) {
139                                 repAl.remove(0);
140                                 if(index > 0) index--;
141                         } else  if(index < repAl.size())
142                                 repAl.remove(index);
143                         repAl.add(index, (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME));
144         }
145                 index = index + 1;
146                 // needed to differentiate form and report index to store form parameters for ZK
147                 form_index = form_index + 1;
148                 session.setAttribute(AppConstants.FORM_DRILLDOWN_INDEX, Integer.toString(form_index));
149                 session.setAttribute(AppConstants.DRILLDOWN_INDEX, Integer.toString(index));
150                         request.getSession().setAttribute(AppConstants.DRILLDOWN_REPORTS_LIST, repAl);
151         } // preserveReportRuntimeAsBackup
152
153         private void clearReportRuntimeBackup(HttpServletRequest request) {
154 //              debugLogger.debug("in Action Handler clear is been called.");
155                 HttpSession session = request.getSession();
156                 session.removeAttribute(AppConstants.DRILLDOWN_REPORTS_LIST);
157                 session.removeAttribute(AppConstants.DRILLDOWN_REPORTS_LIST);
158                 request.removeAttribute(AppConstants.DRILLDOWN_INDEX);
159                 request.removeAttribute(AppConstants.FORM_DRILLDOWN_INDEX);
160                 Enumeration<String> enum1 = session.getAttributeNames();
161                 String attributeName = "";
162                 while(enum1.hasMoreElements()) {
163                         attributeName = enum1.nextElement();
164                         if(attributeName.startsWith("parent_")) {
165                                 session.removeAttribute(attributeName);
166                         }
167                 }
168                 //request.getSession().removeAttribute(AppConstants.SI_REPORT_RUN_BACKUP);
169         //request.getSession().removeAttribute(AppConstants.SI_BACKUP_FOR_REP_ID);
170         } // clearReportRuntimeBackup
171
172         private boolean isDashboardInDrillDownList(HttpServletRequest request) throws RaptorException {
173                 ArrayList aL = (ArrayList) request.getSession().getAttribute(
174                                 AppConstants.DRILLDOWN_REPORTS_LIST);
175                 ReportRuntime rr = null;
176                 if(aL ==null || aL.size() <= 0) {
177                         return false;
178                 } else {
179                         for (int i =0; i<aL.size(); i++) {
180                                 rr = (ReportRuntime) aL.get(i);
181                                 if( rr!=null && rr.getReportType().equals(AppConstants.RT_DASHBOARD)) 
182                                         return true;
183                         }
184                 }
185                 return false;
186         }
187         private ReportRuntime getReportRuntimeFromBackup(HttpServletRequest request) {
188                 ArrayList aL = (ArrayList) request.getSession().getAttribute(
189                                 AppConstants.DRILLDOWN_REPORTS_LIST);
190                 ReportRuntime rr = null;
191                 HttpSession session = request.getSession();
192                 /*if(aL==null || (aL.size() <=0) ) {
193                         rr = (ReportRuntime) request.getSession().getAttribute(
194                                 AppConstants.SI_REPORT_RUN_BACKUP);
195                         request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr);
196                 } else {*/
197                         //clearReportRuntimeBackup(request);
198         
199                         int index = Integer.parseInt(nvl(AppUtils.getRequestValue(request, AppConstants.DRILLDOWN_INDEX), "0"));
200                         int form_index = Integer.parseInt(nvl(AppUtils.getRequestValue(request, AppConstants.FORM_DRILLDOWN_INDEX), "0"));
201                         index = index>0 ? --index : 0;
202                         form_index = form_index>0 ? --form_index : 0;
203                 request.setAttribute(AppConstants.DRILLDOWN_INDEX, Integer.toString(index));
204                 session.setAttribute(AppConstants.DRILLDOWN_INDEX, Integer.toString(index));
205                 request.setAttribute(AppConstants.FORM_DRILLDOWN_INDEX, Integer.toString(form_index));
206                 session.setAttribute(AppConstants.FORM_DRILLDOWN_INDEX, Integer.toString(form_index));
207         
208                         rr = (ReportRuntime)aL.get(index);
209                         request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr);
210                         //clearReportRuntimeBackup(request);
211                 //}
212                 return rr;
213         } // getReportRuntimeFromBackup
214
215         public String reportRun(HttpServletRequest request, String nextPage) {
216                 String action = nvl(request.getParameter(AppConstants.RI_ACTION), request.getParameter("action"));
217                 ReportRuntime rr = null;
218                 String userId = null;
219                 String formFields = "";
220                 ReportData rd = null;
221                 boolean isEmailAttachment = false;
222                 boolean fromDashboard = AppUtils.getRequestFlag(request,"fromDashboard");
223                 request.getSession().setAttribute("login_id", AppUtils.getUserBackdoorLoginId(request));
224                 
225                 boolean rDisplayContent = AppUtils.getRequestFlag(request,
226                                 AppConstants.RI_DISPLAY_CONTENT)
227                                 || AppUtils.getRequestFlag(request, "noFormFields");
228                 
229                 try {
230                         //if "refresh=Y" is in request parameter, session variables are removed.
231                  if(AppUtils.getRequestFlag(request, AppConstants.RI_REFRESH)) {
232                          removeVariablesFromSession(request);
233                  }
234          
235                  
236                 long currentTime = System.currentTimeMillis();
237                 request.setAttribute("triggeredStartTime", new Long(currentTime));
238                 String actionKey = nvl(request.getParameter(AppConstants.RI_ACTION), request.getParameter("action"));
239                 String pdfAttachmentKey = AppUtils.getRequestNvlValue(request, "pdfAttachmentKey");
240                 String parent = "";
241                 int parentFlag = 0;
242                 if(!nvl(request.getParameter("parent"), "").equals("N")) parent = nvl(request.getParameter("parent"), "");
243                 if(parent.startsWith("parent_")) parentFlag = 1; 
244                 
245                 if (pdfAttachmentKey.length()<=0) {
246                 if(actionKey.equals("report.download.page") || actionKey.equals("report.download") || actionKey.equals("report.download.pdf") || actionKey.equals("report.download.excel2007") || actionKey.equals("report.csv.download") || actionKey.equals("report.text.download")) {
247                         if(parentFlag == 1) rr = (ReportRuntime) request.getSession().getAttribute(parent+"_rr");
248                         if(rr==null)
249                         rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME); //changing session to request
250                         if(!(rr!=null && fromDashboard)) {
251                                 userId = AppUtils.getUserID(request);
252                                 boolean isFromReportLog = AppUtils.getRequestFlag(request, "fromReportLog");
253                                 int downloadLimit = 0;
254                                 if(rr!=null)
255                                         downloadLimit = (rr.getMaxRowsInExcelDownload()>0)?rr.getMaxRowsInExcelDownload():Globals.getDownloadLimit();
256                                 if(actionKey.equals("report.csv.download"))
257                                         downloadLimit = Globals.getCSVDownloadLimit();
258         
259                                 if(rr!=null && rr.getReportType().equals(AppConstants.RT_LINEAR)) {
260                                         String sql_whole = rr.getReportDataSQL(userId, downloadLimit, request);
261                                         request.setAttribute(AppConstants.RI_REPORT_SQL_WHOLE, sql_whole);
262                                 } else if(rr!=null && rr.getReportType().equals(AppConstants.RT_CROSSTAB)) {
263                                         rd              = rr.loadReportData(-1, userId, downloadLimit,request, false); /* TODO: should be changed to true */
264                                         request.getSession().setAttribute(AppConstants.RI_REPORT_DATA, rd);
265                                 }
266                                         if(!isFromReportLog) {
267                                                 if(pdfAttachmentKey!=null && pdfAttachmentKey.length()>0) {
268                                                         if(actionKey.equals("report.download")) {
269                                                                         rr.logReportExecutionTime(userId, "",AppConstants.RLA_SCHEDULED_DOWNLOAD_EXCEL, formFields);
270                                                         } else if (actionKey.equals("report.download.pdf")) {
271                                                                         rr.logReportExecutionTime(userId, "",AppConstants.RLA_SCHEDULED_DOWNLOAD_PDF, formFields);
272                                                         } else if (actionKey.equals("report.download.excel2007")) {
273                                                                 rr.logReportExecutionTime(userId, "",AppConstants.RLA_SCHEDULED_DOWNLOAD_EXCELX, formFields);
274                                                 } 
275                                                 } else {
276                                                          if(actionKey.equals("report.download") ) {
277                                                                         rr.logReportExecutionTime(userId, "",AppConstants.RLA_DOWNLOAD_EXCEL, formFields);
278                                                          } else if (actionKey.equals("report.download.pdf")) {
279                                                                         rr.logReportExecutionTime(userId, "",AppConstants.RLA_DOWNLOAD_PDF, formFields);
280                                                                  } else if (actionKey.equals("report.csv.download")) {
281                                                                         rr.logReportExecutionTime(userId, "",AppConstants.RLA_DOWNLOAD_CSV, formFields);
282                                                                  } else if (actionKey.equals("report.text.download")) {
283                                                                         rr.logReportExecutionTime(userId, "",AppConstants.RLA_DOWNLOAD_TEXT, formFields);
284                                                                  } else if (actionKey.equals("report.download.page")) {
285                                                                                 rr.logReportExecutionTime(userId, "",AppConstants.RLA_DOWNLOAD_PAGE_EXCEL, formFields);
286                                                                  } else if (actionKey.equals("report.download.excel2007")) {
287                                                                                 rr.logReportExecutionTime(userId, "",AppConstants.RLA_DOWNLOAD_EXCELX, formFields);
288                                                                  }
289                                                 }
290                                         }
291                                         return nextPage;
292                                 }
293                         
294                 }
295                 }// pdfAttachmentKey
296                 String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID);
297                 rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME); //changing session to request
298                 
299                 String reportIDFromSession = (rr!=null)?rr.getReportID():"";
300                 logger.debug(EELFLoggerDelegate.debugLogger, ("in Action Handler ********** " + reportID + " " + reportIDFromSession + " "+ actionKey));
301 //              ReportRuntime rr = (ReportRuntime) request.getAttribute(AppConstants.SI_REPORT_RUNTIME);
302                 logger.debug(EELFLoggerDelegate.debugLogger, ("^^^^^^^^^^^^^^report ID from session " + ((rr!=null)?rr.getReportID():"no report id in session")));
303                 //              if(rr!=null && !(rr.getReportID().equals(reportID))) {
304 //                      rr = null;
305 //                      request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, null);
306 //              }
307                 
308                 ReportHandler rh1 = new ReportHandler();
309                 ReportRuntime rr1 = null;
310                 
311                 //debugLogger.debug("Report ID B4 rr1 in ActionHandler " 
312                 //      + ( request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)!=null?((ReportRuntime)request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)).getReportID():"Not in session"));
313
314                 
315                 //try {
316                         boolean isGoBackAction = AppUtils.getRequestFlag(request, AppConstants.RI_GO_BACK);
317         
318                         if (AppUtils.getRequestFlag(request, AppConstants.RI_SHOW_BACK_BTN) && !isGoBackAction) {
319         //                      debugLogger.debug("Preserving report");
320                                 if(!reportID.equals(reportIDFromSession))
321                                         preserveReportRuntimeAsBackup(request);
322                 }
323                 
324                          if(reportID !=null)    
325                                  rr1 = rh1.loadReportRuntime(request, reportID, true, 1);
326                         //} catch(Exception e) {
327                                 
328                     // }
329 //                      debugLogger.debug("Report ID After rr1 in ActionHandler " 
330 //                                      + ( request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)!=null?((ReportRuntime)request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)).getReportID():"Not in session"));
331                         if(rr1!=null && rr1.getReportType().equals(AppConstants.RT_DASHBOARD)) {
332                                 int DASH=7;
333                                 int requestFlag = DASH;
334                                 ReportHandler rh = new ReportHandler();
335                                 // Added below statement to add parent dashboard report id in session.
336                                 request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REP_ID, reportID);
337                                 //rr = null;                            
338                                 // get dashboard HTML from report runtime. getListOfReportsFromDashBoardHTML
339                                  String strHTML = rr1.getDashboardLayoutHTML();
340                                  
341                                  //System.out.println("StrHTML " + strHTML);
342                                 // call getListOfReportsFromDashBoardHTML returns HashMap
343                                 
344                                 TreeMap treeMap = getListOfReportsFromDashBoardHTML(strHTML);
345                                 //System.out.println("Size " + hashMap.size());
346                                 Set set = treeMap.entrySet();
347                                 String value = "";
348                                 
349                                 HashMap reportsRuntimeMap       = new HashMap();
350                                 HashMap reportDataMap           = new HashMap();
351                                 HashMap reportChartDataMap = new HashMap();
352                                 // displayTypeMap differentiates whether report need to be displayed as data or chart
353                                 HashMap reportDisplayTypeMap = new HashMap();
354                                 
355                                 userId = null;
356                                 userId = AppUtils.getUserID(request);
357                                 int pageNo = -1;
358                                 //int downloadLimit = (rr1.getMaxRowsInExcelDownload()>0)?rr1.getMaxRowsInExcelDownload():Globals.getDownloadLimit();
359                                 int downloadLimit = 0;
360                                 int rep_idx = 0;
361                                 int widthFlag = 0;
362                                 int heightFlag = 0;
363                                 ReportRuntime rrDashboardReports = null;
364                                 Integer intObj = null;
365                                 ReportRuntime similiarReportRuntime = null;
366                                 rd = null;
367                                 DataSet ds = null;
368                                 String reportIDFromMap = null;
369                                 int record = 0;
370                                 boolean buildReportdata = true;
371
372                                         for(Iterator iter = set.iterator(); iter.hasNext(); ) {
373                                                 record++;
374                                                 Map.Entry entry = (Entry) iter.next();
375                                                 //System.out.println("Key "+ entry.getKey());
376                                                 //System.out.println("Value "+ entry.getValue());
377                                                 reportIDFromMap = entry.getValue().toString().substring(1);
378                                                 // The below line is used to optimize, so that if there is already same report id it wouldn't go through the whole process
379                                                 similiarReportRuntime = getSimiliarReportRuntime(reportsRuntimeMap, reportIDFromMap);
380                                                 if(similiarReportRuntime != null ) {
381                                                         rrDashboardReports = (ReportRuntime) getSimiliarReportRuntime(reportsRuntimeMap, reportIDFromMap).clone();
382                                                         intObj = getKey(reportsRuntimeMap,reportIDFromMap);
383                                                 } else {                                                
384                                                         rrDashboardReports = rh.loadReportRuntime(request, reportIDFromMap, true, requestFlag);
385                                                 }
386                                                 if(entry.getValue().toString().toLowerCase().startsWith("c")) {
387                                                         rrDashboardReports.setDisplayMode(ReportRuntime.DISPLAY_CHART_ONLY);
388                                                 } else {
389                                                         rrDashboardReports.setDisplayMode(ReportRuntime.DISPLAY_DATA_ONLY);
390                                                 }
391                                                 
392                                                 downloadLimit = (rrDashboardReports.getMaxRowsInExcelDownload()>0)?rrDashboardReports.getMaxRowsInExcelDownload():Globals.getDownloadLimit();
393                                             if (new Integer(nvl(rrDashboardReports.getDataContainerWidth(),"100")).intValue() >100) widthFlag = 1;
394                                             if (new Integer(nvl(rrDashboardReports.getDataContainerHeight(),"100")).intValue() >100) heightFlag = 1;
395                                             
396                                             if(record == 1) {
397                                                 if(rrDashboardReports.getReportFormFields()!=null && rrDashboardReports.getReportFormFields().size()>0) {
398                                                         buildReportdata = false;
399                                                         if(rDisplayContent) buildReportdata = true;
400                                                 }
401                                             }
402                                             
403                                             if(buildReportdata) {
404                                             if(similiarReportRuntime != null ) {
405                                                 rd = (ReportData) reportDataMap.get(intObj);
406                                                 ds = (DataSet) reportChartDataMap.get(intObj);
407                                             } else {
408                                                         if (!rrDashboardReports.getReportType().equals(AppConstants.RT_HIVE)) 
409                                                                 rd              = rrDashboardReports.loadReportData(pageNo, userId, downloadLimit,request, false /*download*/);
410                                                         else
411                                                                 rd =  rrDashboardReports.loadHiveLinearReportData(rrDashboardReports.getReportSQL(), userId, 2,request);
412                                                 ds = rrDashboardReports.loadChartData(userId,request);
413                                             }
414                                             }
415                                             
416                                             
417                                                 long totalTime = System.currentTimeMillis() - currentTime;
418                                                 formFields = AppUtils.getRequestNvlValue(request, "formFields");
419                                 if(buildReportdata) {
420                                                         rrDashboardReports.logReportRun(userId, String.valueOf(totalTime),formFields);
421                                                         rrDashboardReports.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_EXECUTION_TIME, formFields);
422                                 }
423
424                                                 /*reportsRuntimeMap.put(new Integer(entry.getKey().toString()), rrDashboardReports);
425                                                 reportDataMap.put(new Integer(entry.getKey().toString()), rd);
426                                                 reportChartDataMap.put(new Integer(entry.getKey().toString()), ds);
427                                                 reportDisplayTypeMap.put(new Integer(entry.getKey().toString()), entry.getValue().toString().substring(0,1));*/
428
429                                                 reportsRuntimeMap.put(new Integer(entry.getKey().toString())+"_"+rrDashboardReports.getReportID(), rrDashboardReports);
430                                                 reportDisplayTypeMap.put(new Integer(entry.getKey().toString())+"_"+rrDashboardReports.getReportID(), entry.getValue().toString().substring(0,1));
431                                                 if(buildReportdata) {
432                                                         reportDataMap.put(new Integer(entry.getKey().toString())+"_"+rrDashboardReports.getReportID(), rd);
433                                                         reportChartDataMap.put(new Integer(entry.getKey().toString())+"_"+rrDashboardReports.getReportID(), ds);
434                                                 }
435                                                 
436                                         }
437                                         
438                                         /*if(widthFlag ==1)  request.getSession().setAttribute("extendedWidth", "Y");
439                                         else request.getSession().removeAttribute("extendedWidth");
440                                         if(heightFlag ==1)  request.getSession().setAttribute("extendedHeight", "Y");
441                                         else request.getSession().removeAttribute("extendedHeight");
442                                         */
443                                         request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP, new TreeMap(reportsRuntimeMap));
444                                         request.getSession().setAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP, new TreeMap(reportDisplayTypeMap));
445                                         if(buildReportdata) {
446                                                 request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP, new TreeMap(reportDataMap));
447                                                 request.getSession().setAttribute(AppConstants.SI_DASHBOARD_CHARTDATA_MAP, new TreeMap(reportChartDataMap));
448                                         }
449 //                              debugLogger.debug("I am inside this if " + rr1.getReportType() + " "+rr1.getReportID());
450                                 request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr1); //changing session to request
451                                 //request.setAttribute(AppConstants.SI_REPORT_RUNTIME, rr1);
452                                 if((String) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID)!= null || rr1.getReportType().equals(AppConstants.RT_DASHBOARD)) {
453                                         request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME, rr1);
454                                 }
455                                 
456                                 return "raptor/report_dashboard_run_container.jsp";
457                         } else {
458                                 fromDashboard = AppUtils.getRequestFlag(request,"fromDashboard");
459                                 if(isDashboardInDrillDownList(request)) fromDashboard= true;
460                                 
461                                 if(!fromDashboard) {
462                                         request.getSession().removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP);
463                                         request.getSession().removeAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP);
464                                         request.getSession().removeAttribute(AppConstants.SI_DASHBOARD_CHARTDATA_MAP);
465                                         request.getSession().removeAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP);
466                                         request.getSession().removeAttribute(AppConstants.SI_DASHBOARD_REP_ID);
467                                         request.getSession().removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME);
468                                         request.getSession().removeAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP);
469                                         request.getSession().removeAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP);
470                                 }
471                                 //String pdfAttachmentKey = AppUtils.getRequestValue(request, "pdfAttachmentKey");
472                                 String report_email_sent_log_id = AppUtils.getRequestValue(request, "log_id");
473                                 logger.debug(EELFLoggerDelegate.debugLogger, ("Email PDF" + pdfAttachmentKey+" "+ report_email_sent_log_id));
474
475                                 //email pdf attachment specific
476                                 if(nvl(pdfAttachmentKey).length()>0 && report_email_sent_log_id !=null) 
477                                         isEmailAttachment = true;
478                                         if(isEmailAttachment) {
479                                         /*      String query =  "Select user_id, rep_id from CR_REPORT_EMAIL_SENT_LOG" +
480                                                                                 " where rownum = 1" +
481                                                                                 " and gen_key='"+pdfAttachmentKey.trim()+"'" + 
482                                                                                 " and log_id ="+report_email_sent_log_id.trim() +
483                                                                                 " and (sysdate - sent_date) < 1 ";*/
484                                                 
485                                                                                 
486                                                 String query = Globals.getDownloadAllEmailSent();
487                                                 query = query.replace("[pdfAttachmentKey.trim()]", pdfAttachmentKey.trim());
488                                                 query = query.replace("[report_email_sent_log_id.trim()]", report_email_sent_log_id.trim());
489                                                 
490                                                 DataSet ds = DbUtils.executeQuery(query, 1);
491                                                 if(!ds.isEmpty()) {
492                                                         userId = ds.getString(0,"user_id");
493                                                         reportID  = ds.getString(0, "rep_id");
494                                                         request.setAttribute("schedule_email_userId", userId);
495                                                 } else {
496                                                         request.setAttribute("message", "This link has expired, please <a href=''>login</a> and regenerate the report");
497                                                         return "raptor/message.jsp"; 
498                                                 }
499                                         } else userId = AppUtils.getUserID(request);
500 //                              debugLogger.debug("Report ID b4 showbutton in ActionHandler " 
501 //                                              + ( request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)!=null?((ReportRuntime)request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME)).getReportID():"Not in session"));
502 //                              debugLogger.debug("Report ID " + reportID + "  " + reportIDFromSession);
503                                         
504                                 // Scheduling Dashoard report
505                                          if(reportID !=null && nvl(pdfAttachmentKey).length()>0)        
506                                                  rr = rh1.loadReportRuntime(request, reportID, true, 1);                                        
507                                         if(rr!=null && rr.getReportType().equals(AppConstants.RT_DASHBOARD) && nvl(pdfAttachmentKey).length()>0) {
508                                                 int DASH=7;
509                                                 int requestFlag = DASH;
510                                                 ReportHandler rh = new ReportHandler();
511                                                 request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REP_ID, reportID);
512                                                 //rr = null;                            
513                                                 // get dashboard HTML from report runtime. getListOfReportsFromDashBoardHTML
514                                                  String strHTML = rr.getDashboardLayoutHTML();
515                                                  //System.out.println("StrHTML " + strHTML);
516                                                 // call getListOfReportsFromDashBoardHTML returns HashMap
517                                                 
518                                                 TreeMap treeMap = getListOfReportsFromDashBoardHTML(strHTML);
519                                                 //System.out.println("Size " + hashMap.size());
520                                                 Set set = treeMap.entrySet();
521                                                 String value = "";
522                                                 
523                                                 HashMap reportsRuntimeMap       = new HashMap();
524                                                 HashMap reportDataMap           = new HashMap();
525                                                 HashMap reportChartDataMap = new HashMap();
526                                                 HashMap reportDisplayTypeMap = new HashMap();
527                                                 
528                                                 userId = null;
529                                                 userId = AppUtils.getUserID(request);
530                                                 int pageNo = -1;
531                                                 int downloadLimit = 0;
532                                                 int rep_idx = 0;
533                                                 int widthFlag = 0;
534                                                 int heightFlag = 0;
535                                                 ReportRuntime rrDashboardReports = null;                                                
536                                                 Integer intObj = null;
537                                                 ReportRuntime similiarReportRuntime = null;
538                                                 rd = null;
539                                                 DataSet ds = null;
540                                                 String reportIDFromMap = null;
541                                                 int record = 0;
542                                                 boolean buildReportdata = true;
543                                                         for(Iterator iter = set.iterator(); iter.hasNext(); ) {
544                                                                 record++;
545                                                                 Map.Entry entry = (Entry) iter.next();
546
547                                                                 reportIDFromMap = entry.getValue().toString().substring(1);
548                                                                 similiarReportRuntime = getSimiliarReportRuntime(reportsRuntimeMap, reportIDFromMap);
549                                                                 if(similiarReportRuntime != null ) {
550                                                                         rrDashboardReports = getSimiliarReportRuntime(reportsRuntimeMap, reportIDFromMap);
551                                                                         intObj = getKey(reportsRuntimeMap,reportIDFromMap);
552                                                                 } else {                                                
553                                                                         rrDashboardReports = rh.loadReportRuntime(request, reportIDFromMap, true, requestFlag);
554                                                                 }
555
556                                                                 downloadLimit = (rrDashboardReports.getMaxRowsInExcelDownload()>0)?rrDashboardReports.getMaxRowsInExcelDownload():Globals.getDownloadLimit();
557                                                                 
558                                                             if (new Integer(nvl(rrDashboardReports.getDataContainerWidth(),"100")).intValue() >100) widthFlag = 1;
559                                                             if (new Integer(nvl(rrDashboardReports.getDataContainerHeight(),"100")).intValue() >100) heightFlag = 1;
560                                                             if(record == 1) {
561                                                                 if(rrDashboardReports.getReportFormFields()!=null && rrDashboardReports.getReportFormFields().size()>0) {
562                                                                         buildReportdata = false;
563                                                                         if(rDisplayContent) buildReportdata = true;
564                                                                 }
565                                                             }
566                                                             if(buildReportdata) {
567                                                             if(similiarReportRuntime != null ) {
568                                                                 rd = (ReportData) reportDataMap.get(intObj);
569                                                                 ds = (DataSet) reportChartDataMap.get(intObj);
570                                                             } else {
571                                                                 
572                                                                         if (!rrDashboardReports.getReportType().equals(AppConstants.RT_HIVE)) 
573                                                                                 rd              = rrDashboardReports.loadReportData(pageNo, userId, downloadLimit,request, false /*download*/);
574                                                                         else
575                                                                                 rd =  rrDashboardReports.loadHiveLinearReportData(rrDashboardReports.getReportSQL(), userId, 2,request);
576                                                                 ds = rrDashboardReports.loadChartData(userId,request);
577                                                             }
578                                                             }
579
580                                                             
581                                                             
582                                                                 long totalTime = System.currentTimeMillis() - currentTime;
583                                                                 formFields = AppUtils.getRequestNvlValue(request, "formFields");
584                                                 
585                                                                 rrDashboardReports.logReportRun(userId, String.valueOf(totalTime),formFields);
586                                                                 rrDashboardReports.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_EXECUTION_TIME, formFields);
587                                                                 
588                                                                 reportsRuntimeMap.put(new Integer(entry.getKey().toString()), rrDashboardReports);
589                                                                 reportDisplayTypeMap.put(new Integer(entry.getKey().toString()), entry.getValue().toString().substring(0,1));
590                                                                 if(buildReportdata) {
591                                                                 reportDataMap.put(new Integer(entry.getKey().toString()), rd);
592                                                                 reportChartDataMap.put(new Integer(entry.getKey().toString()), ds);
593                                                                         //reportDisplayTypeMap.put(new Integer(entry.getKey().toString()), entry.getValue().toString().substring(0,1));
594                                                         }
595                                                         }
596                                                         
597                                                         /*if(widthFlag ==1)  request.getSession().setAttribute("extendedWidth", "Y");
598                                                         else request.getSession().removeAttribute("extendedWidth");
599                                                         if(heightFlag ==1)  request.getSession().setAttribute("extendedHeight", "Y");
600                                                         else request.getSession().removeAttribute("extendedHeight");
601                                                         */
602                                                         request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP, new TreeMap(reportsRuntimeMap));
603                                                         request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr); //changing session to request
604                                                         if(buildReportdata) {
605                                                         request.getSession().setAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP, new TreeMap(reportDisplayTypeMap));
606                                                                 request.getSession().setAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP, new TreeMap(reportDataMap));
607                                                                 request.getSession().setAttribute(AppConstants.SI_DASHBOARD_CHARTDATA_MAP, new TreeMap(reportChartDataMap));
608                                                         }
609                                                         //request.setAttribute(AppConstants.SI_REPORT_RUNTIME, rr1);
610                                                         //return nextPage;                                                      
611                                         } else {
612                                         
613                                 // Ends 
614
615
616 //                              debugLogger.debug("Action Handler *****************" + new java.util.Date()+ " " + isGoBackAction);
617                                 ReportHandler rh = new ReportHandler();
618                                 //rr = null; // COMMENT THIS LINE
619                     boolean resetParams = AppUtils.getRequestFlag(request,
620                             AppConstants.RI_RESET_PARAMS);
621                     boolean resetAction = AppUtils.getRequestFlag(request,
622                             AppConstants.RI_RESET_ACTION);
623                     boolean refresh = false;
624                     if (resetAction) {
625                         rr  = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
626                         resetParams=true;
627                         refresh = true;
628                         if(rr!=null) {
629                                 rr.setParamValues(request, resetParams,refresh);
630                                 request.getSession().removeAttribute(AppConstants.RI_REPORT_DATA);
631                                 rr.resetVisualSettings();
632                         }
633                         return nextPage;
634                     }
635         
636                     /*if (isGoBackAction) {
637 //                      debugLogger.debug("Report back in action handler " + ((ReportRuntime) request.getSession().getAttribute(
638 //                                              AppConstants.SI_REPORT_RUN_BACKUP))!=null?((ReportRuntime) request.getSession().getAttribute(
639 //                                                      AppConstants.SI_REPORT_RUN_BACKUP)).getReportID():((ReportRuntime) request.getSession().getAttribute(
640 //                                                              AppConstants.SI_REPORT_RUN_BACKUP)));
641                         rr = null;
642                                         rr = getReportRuntimeFromBackup(request);
643                                         if (rr == null)
644                                                 throw new Exception("[ActionHandler.reportRun] Report backup not found");
645                                         reportID = rr.getReportID();
646                                 }  else {*/
647                         
648                                         logger.debug(EELFLoggerDelegate.debugLogger, ("Ocurring during Schedule "));
649                                         //TODO differentiate Schedule with other actions
650 //                                      if(isEmailAttachment) {
651 //                                              
652 //                                      } else {
653 //                                              
654 //                                      }
655                                         rr = rh.loadReportRuntime(request, reportID);
656                                         //setParamValues called for Drilldown to display formfield
657                                         //rr.setParamValues(request, false,true); 
658                                         
659                                 //} // else
660
661                                 ArrayList aL = (ArrayList)request.getSession().getAttribute(AppConstants.DRILLDOWN_REPORTS_LIST);
662                                 ReportRuntime aLR = null;
663                                 if(aL != null) {
664 //                                      for (int i = 1; i < aL.size(); i++) {
665 //                                              aLR = (ReportRuntime) aL.get(i);
666 //                                              if (!aLR.getReportID().equals(reportID)) {
667 //                                                      request.setAttribute(AppConstants.RI_SHOW_BACK_BTN, "Y");
668 //                                              }
669 //                                      }
670 //                                      if(reportID.equals(reportIDFromSession)) {
671                                                 aLR = (ReportRuntime) aL.get(0);
672                                                 if (aLR!=null && !aLR.getReportID().equals(reportID)) {
673                                                         request.setAttribute(AppConstants.RI_SHOW_BACK_BTN, "Y");
674                                                 }
675 //                                      }
676                                 }
677                                 
678                         if(rDisplayContent)
679                                 rr.setDisplayFlags(true, true);
680
681                         if (rr.getDisplayContent()) {
682                                         int pageNo = 0;
683                                         if (isGoBackAction)
684                                                 pageNo = rr.getCachedPageNo();
685                                         else {
686                                                 try {
687                                                         pageNo = Integer.parseInt(AppUtils.getRequestNvlValue(request, AppConstants.RI_NEXT_PAGE));
688                                                 } catch (Exception e) {
689                                                 }
690         
691                                                 String vAction = AppUtils.getRequestNvlValue(request,
692                                                                 AppConstants.RI_VISUAL_ACTION);
693                                                 String vCoId = AppUtils.getRequestNvlValue(request,
694                                                                 AppConstants.RI_DETAIL_ID);
695                                                 if (vAction.equals(AppConstants.VA_HIDE))
696                                                         rr.hideColVisual(vCoId);
697                                                 else if (vAction.equals(AppConstants.VA_SHOW))
698                                                         rr.showColVisual(vCoId);
699                                                 else if (vAction.equals(AppConstants.VA_SORT)) {
700                                                         rr.sortColVisual(vCoId);
701                                                         pageNo = 0;
702                                                 } // else
703                                         } // else
704                                         
705                                         int downloadLimit = (rr.getMaxRowsInExcelDownload()>0)?rr.getMaxRowsInExcelDownload():Globals.getDownloadLimit();
706                                         if(isEmailAttachment) {
707                                                 String limit = nvl(request.getParameter("download_limit"),"1000");
708                                                 downloadLimit = Integer.parseInt(limit);
709                                         }
710                                         //if (action.startsWith("mobile")) rr.setPageSize(5);
711                                         long reportTime = System.currentTimeMillis();
712                                         if (!rr.getReportType().equals(AppConstants.RT_HIVE)) 
713                                                 rd              = rr.loadReportData(pageNo, userId, downloadLimit,request,false /*download*/);
714                                         else
715                                                 rd =  rr.loadHiveLinearReportData(rr.getReportSQL(), userId, 2,request);
716                                         logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] ------->Time Taken for the loading report data --- " + (System.currentTimeMillis() - reportTime)));
717                                         ReportData rd_whole = null;
718                                         boolean hideReportMap   = rr.isDisplayOptionHideMap()||AppUtils.getRequestNvlValue(request, "noMap").equals("Y");
719 /*                                      if (Globals.getMapAllowedYN().equals("Y") && !hideReportMap && rr.getReportMap()!=null){
720                                                 rd_whole = rr.loadReportData(-1, userId, downloadLimit,request);
721                                         }
722 */                                      
723                                         request.getSession().setAttribute(AppConstants.RI_REPORT_DATA, rd);
724                                         //if (Globals.getMapAllowedYN().equals("Y") && !hideReportMap && (rr.getReportMap()!=null && rr.getReportMap().getLatColumn()!=null && rr.getReportMap().getLongColumn()!=null)) {
725                                         if(rr!=null && rr.getReportType().equals(AppConstants.RT_LINEAR)) {
726                                                 String sql_whole = rr.getReportDataSQL(userId, downloadLimit, request);
727                                                 request.setAttribute(AppConstants.RI_REPORT_SQL_WHOLE, sql_whole);
728                                         } else if(rr.getReportType().equals(AppConstants.RT_HIVE)) {
729                                                 String sql_whole = rr.getReportSQL();
730                                                 request.setAttribute(AppConstants.RI_REPORT_SQL_WHOLE, sql_whole);
731                                         }
732                                         //}
733                                         //request.setAttribute(AppConstants.RI_REPORT_DATA_WHOLE, rd_whole);
734         //                if(rr.getReportDataSize() > Globals.getFlatFileLowerLimit() && rr.getReportDataSize() <= Globals.getFlatFileUpperLimit() ) {
735         //                              rr.setFlatFileName(rh.saveFlatFile(request, rd, rr
736         //                                              .getParamNameValuePairs(), rr.getReportName(), rr.getReportDescr()));
737         //                }
738                                         //if(actionKey!=null && actionKey.equals("report.download")) {
739 //                                              rr.setExcelPageFileName(rh.saveAsExcelFile(request, rd, rr
740 //                                                              .getParamNameValuePairs(), rr.getReportName(), rr.getReportDescr()));
741                                         //}
742                                         if (!rr.getReportType().equals(AppConstants.RT_HIVE)) {
743                                                 long currentChartTime = System.currentTimeMillis();     
744                                                 DataSet chartDS = rr.loadChartData(userId,request);
745                                                 if(chartDS != null)
746                                                         request.getSession().setAttribute(AppConstants.RI_CHART_DATA, rr.loadChartData(userId,request));
747                                                 else
748                                                         request.getSession().removeAttribute(AppConstants.RI_CHART_DATA);
749                                                 logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] ------->Time Taken for the loading chart data --- " + (System.currentTimeMillis() - currentChartTime)));
750                                         }
751                                         
752 /*                                      if((String) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID)!=null) {
753                                                 request.getSession().setAttribute("FirstDashReport", rr);
754                                         }
755 */                                      
756                                 }
757                         request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rr); //changing session to request
758                         request.getSession().setAttribute(AppConstants.RI_REPORT_DATA, rd);
759                         } // else
760                                         long totalTime = System.currentTimeMillis() - currentTime;
761                                         formFields = AppUtils.getRequestNvlValue(request, "formFields");
762                                         request.setAttribute(AppConstants.RLA_EXECUTION_TIME, "" + totalTime);
763
764         
765                                         boolean isFromReportLog = AppUtils.getRequestFlag(request, "fromReportLog");
766                                         if(!isFromReportLog) {
767                                                 if(pdfAttachmentKey!=null && pdfAttachmentKey.length()>0) {
768                                                         if(actionKey.equals("report.download")) {
769                                                                 rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_SCHEDULED_DOWNLOAD_EXCEL, formFields);
770                                                         } else if (actionKey.equals("report.download.pdf")) {
771                                                                 rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_SCHEDULED_DOWNLOAD_PDF, formFields);
772                                                         } 
773                                                 } else {
774                                                          if(actionKey.equals("report.download") ) {
775                                                                         rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_DOWNLOAD_EXCEL, formFields);
776                                                          } else if (actionKey.equals("report.download.pdf")) {
777                                                                         rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_DOWNLOAD_PDF, formFields);
778                                                          } else if (actionKey.equals("report.csv.download")) {
779                                                                         rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_DOWNLOAD_CSV, formFields);
780                                                          } else if (actionKey.equals("report.text.download")) {
781                                                                         rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_DOWNLOAD_TEXT, formFields);
782                                                          } else {
783                                                                  
784                                                                 //rr.logReportRun(userId, String.valueOf(totalTime),formFields);
785                                                                  if(rd!=null && !action.equals("report.run.container"))
786                                                                 rr.logReportExecutionTime(userId, String.valueOf(totalTime),AppConstants.RLA_EXECUTION_TIME, formFields);
787                                                          }
788                                                 }
789                                         } else {
790                                                 rr.logReportExecutionTimeFromLogList(userId, String.valueOf(totalTime),formFields);                                     
791                                         }
792                                         
793 /*                                      if((String) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID)!=null) {
794                                                 reportID = (String) request.getSession().getAttribute(AppConstants.SI_DASHBOARD_REP_ID);
795                                                 ReportRuntime rrDash = rh1.loadReportRuntime(request, reportID, true, 1);
796                                                 request.getSession().setAttribute(AppConstants.SI_REPORT_RUNTIME, rrDash);
797                                         }
798 */                                      
799                                         if(rr.isDrillDownURLInPopupPresent())  {
800                                                 request.getSession().setAttribute("parent_"+rr.getReportID()+"_rr", rr);
801                                                 request.getSession().setAttribute("parent_"+rr.getReportID()+"_rd", rd);
802                                         }
803                                         
804                                         if(rr.getReportType().equals(AppConstants.RT_CROSSTAB)) {
805                                                 return "raptor/report_crosstab_run_container.jsp"; 
806                                         } else if (rr.getReportType().equals(AppConstants.RT_HIVE) && !isEmailAttachment) {
807                                                 return "raptor/report_hive_run_container.jsp";
808                                         }
809                   } // else
810                         
811                         boolean isEmbedded = false;
812                         Object temp = request.getSession().getAttribute("isEmbedded");
813                         if(temp!=null){
814                                 isEmbedded = (boolean)temp;
815                         }
816                         if(isEmbedded && !action.equals("chart.run")){
817                                 HashMap embeddedReportsRuntimeMap       = null;
818                                 HashMap embeddedReportsDataMap          = null;
819                                 if(request.getSession().getAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP)!= null){
820                                         embeddedReportsRuntimeMap = (HashMap)request.getSession().getAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP);
821                                 } else {
822                                         embeddedReportsRuntimeMap = new HashMap();
823                                 }
824                                 if(request.getSession().getAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP)!= null){
825                                         embeddedReportsDataMap = (HashMap)request.getSession().getAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP);
826                                 } else {
827                                         embeddedReportsDataMap = new HashMap();
828                                 }
829                                 embeddedReportsRuntimeMap.put(rr.getReportID(), rr);
830                                 embeddedReportsDataMap.put(rr.getReportID(), rd);
831
832
833                                 request.getSession().setAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP, embeddedReportsRuntimeMap);
834                                 request.getSession().setAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP, embeddedReportsDataMap);
835
836                         }
837                         
838                         ReportJSONRuntime reportJSONRuntime = rr.createReportJSONRuntime(request, rd);
839                         ObjectMapper mapper = new ObjectMapper();
840                         //mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
841                         //mapper.setVisibilityChecker(mapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE));
842                         mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
843                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
844                         String jsonInString = "";
845                         try {
846                                 jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(reportJSONRuntime);
847                         } catch (Exception ex) {
848                                 ex.printStackTrace();
849                                 
850                         }
851             return jsonInString;
852                 } catch (RaptorException e) {
853                         try {
854                                 e.printStackTrace();
855                                 
856                                 if(rr!=null) { // when user tries report they don't have access this should not throw exception that's why this if is added.
857                                         if(isEmailAttachment)
858                                                 rr.logReportExecutionTime(userId, "", "Scheduled: " + AppConstants.RLA_ERROR, formFields);
859                                         else
860                                                 rr.logReportExecutionTime(userId, "", "On Demand: " + AppConstants.RLA_ERROR, formFields);
861                                 }
862                                 
863                                 ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
864                                 errorJSONRuntime.setErrormessage(e.getMessage());
865                                 errorJSONRuntime.setStacktrace(getStackTrace(e));
866                                 ObjectMapper mapper = new ObjectMapper();
867                                 //mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
868                                 //mapper.setVisibilityChecker(mapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE));
869                                 mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
870                                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
871                                 String jsonInString = "";
872                                 try {
873                                         jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime);
874                                 } catch (Exception ex) {
875                                         ex.printStackTrace();
876                                         
877                                 }
878                     return jsonInString;
879                                 
880                         } catch (RaptorException ex) {
881                                 nextPage = (new ErrorHandler()).processFatalError(request, ex);
882                                 ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
883                                 errorJSONRuntime.setErrormessage(ex.getMessage());
884                                 errorJSONRuntime.setStacktrace(getStackTrace(ex));
885                                 ObjectMapper mapper = new ObjectMapper();
886                                 //mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
887                                 //mapper.setVisibilityChecker(mapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE));
888                                 mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
889                                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
890                                 String jsonInString = "";
891                                 try {
892                                         jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime);
893                                 } catch (Exception ex1) {
894                                         ex1.printStackTrace();
895                                 }
896                     return jsonInString;
897                         }
898                         //nextPage = (new ErrorHandler()).processFatalError(request, e);
899                 } catch (Throwable t) {
900                         t.printStackTrace();
901                         ErrorJSONRuntime errorJSONRuntime = new ErrorJSONRuntime();
902                         errorJSONRuntime.setErrormessage(t.toString());
903                         errorJSONRuntime.setStacktrace(getStackTrace(t));
904                         ObjectMapper mapper = new ObjectMapper();
905                         //mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
906                         //mapper.setVisibilityChecker(mapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE));
907                         mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
908                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
909                         String jsonInString = "";
910                         try {
911                                 jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorJSONRuntime);
912                         } catch (Exception ex) {
913                                 ex.printStackTrace();
914                                 
915                         }
916             return jsonInString;
917
918                 }
919                 //return nextPage;
920         } // reportRun
921         
922           public static String getStackTrace(Throwable aThrowable) {
923                     Writer result = new StringWriter();
924                     PrintWriter printWriter = new PrintWriter(result);
925                     aThrowable.printStackTrace(printWriter);
926                     return result.toString();
927                   }
928
929     /**
930      * The below method is used to optimize, so that if there is already same report id in hashMap it wouldn't go through the whole process again.
931      **/
932         private ReportRuntime getSimiliarReportRuntime(HashMap reportsRuntimeMap, String reportID) {
933                 Set set = reportsRuntimeMap.entrySet();
934                 for(Iterator iter = set.iterator(); iter.hasNext(); ) {
935                         Map.Entry entry = (Entry) iter.next();
936                         if (((ReportRuntime) entry.getValue()).getReportID().equals(reportID)) {
937                                 return (ReportRuntime) entry.getValue();
938                         }
939                 }
940                 return null;
941         }
942         
943         private Integer getKey(HashMap reportsRuntimeMap, String reportID) {
944                 Set set = reportsRuntimeMap.entrySet();
945                 for(Iterator iter = set.iterator(); iter.hasNext(); ) {
946                         Map.Entry entry = (Entry) iter.next();
947                         if (((ReportRuntime) entry.getValue()).getReportID().equals(reportID)) {
948                                 return new Integer(((String) entry.getKey()).substring(2));
949                         }
950                 }
951                 return null;
952         }       
953         
954         public String reportSearch(HttpServletRequest request, String nextPage) {
955                 return reportSearchExecute(request, nextPage);
956         } // reportSearch
957
958         public String reportSearchUser(HttpServletRequest request, String nextPage) {
959                 removeVariablesFromSession(request);            
960                 request.setAttribute(AppConstants.RI_USER_REPORTS, "Y");
961                 return reportSearchExecute(request, nextPage);
962         } // reportSearchUser
963
964         public String reportSearchPublic(HttpServletRequest request, String nextPage) {
965                 removeVariablesFromSession(request);            
966                 request.setAttribute(AppConstants.RI_PUBLIC_REPORTS, "Y");
967                 return reportSearchExecute(request, nextPage);
968         } // reportSearchPublic
969
970         public String reportSearchFavorites(HttpServletRequest request, String nextPage) {
971                 removeVariablesFromSession(request);            
972                 request.setAttribute(AppConstants.RI_FAVORITE_REPORTS, "Y");
973                 return reportSearchExecute(request, nextPage);
974         } // reportSearchFavorites
975
976         public String reportSearchExecute(HttpServletRequest request, String nextPage) {
977                 removeVariablesFromSession(request);            
978                 try {
979                         SearchHandler sh = new SearchHandler();
980                         ReportSearchResultJSON sr = sh.loadReportSearchResult(request);
981                         return sr.getJSONString();
982                         //request.setAttribute(AppConstants.RI_SEARCH_RESULT, sr);
983                 } catch (RaptorException e) {
984                         nextPage = (new ErrorHandler()).processFatalError(request, e);
985                 }
986
987                 return nextPage;
988         } // reportSearchExecute
989         
990         public String reportChartRun(HttpServletRequest request, String nextPage) {
991                         ChartWebRuntime cwr = new ChartWebRuntime();
992                         return cwr.generateChart(request, false); //no data 
993         } // reportSearchExecute
994
995         public String reportChartDataRun(HttpServletRequest request, String nextPage) {
996                         ChartWebRuntime cwr = new ChartWebRuntime();
997                         return cwr.generateChart(request); //data 
998         } // reportSearchExecute
999         
1000         
1001         //      public String reportRunExecute(HttpServletRequest request, String nextPage) {
1002 //              try {
1003 //                      ReportRunHandler rh = new ReportRunHandler();
1004 //                      ReportRunResultJSON sr = rh.loadReportRunResult(request);
1005 //                      return sr.getJSONString();
1006 //                      //request.setAttribute(AppConstants.RI_SEARCH_RESULT, sr);
1007 //              } catch (RaptorException e) {
1008 //                      nextPage = (new ErrorHandler()).processFatalError(request, e);
1009 //              }
1010 //
1011 //              return nextPage;                
1012 //      }
1013
1014         public String getQuickLinksJSON(HttpServletRequest request, String nextPage) {
1015                 String jsonInString = null;
1016                 try {
1017                         ArrayList<QuickLink> quickLinks = ReportLoader.getQuickLinksJSON(request, request.getParameter("quick_links_menu_id"),true);
1018                         ObjectMapper mapper = new ObjectMapper();
1019                         mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
1020                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
1021                         jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(quickLinks);
1022
1023                 } catch (Exception e) {
1024                         e.printStackTrace();
1025                 }
1026                 return jsonInString;
1027         }
1028         
1029         public String processScheduleReportList(HttpServletRequest request, String nextPage) {
1030                 String reportID = "";
1031                 reportID = AppUtils.getRequestNvlValue(request, "schedule_reports");
1032                 if (nvl(reportID).length()<=0)
1033                         reportID = AppUtils.getRequestNvlValue(request, AppConstants.RI_REPORT_ID);
1034                 // Added for form field chaining in schedule tab so that setParamValues() is called
1035                 request.setAttribute(AppConstants.SCHEDULE_ACTION, "Y");
1036                 
1037                         try {
1038                                 boolean isAdmin = AppUtils.isAdminUser(request);
1039                                 boolean check = ReportLoader.doesUserCanScheduleReport(request, null);
1040
1041                                 logger.debug(EELFLoggerDelegate.debugLogger, ("^^^^^^^^^^^^^Check " + check + " Admin "+ isAdmin));
1042
1043                                 if(check || isAdmin) { 
1044                                         if(reportID.length()>0) {
1045                                                 ReportHandler rh = new ReportHandler();
1046                                                 ReportDefinition rdef = rh.loadReportDefinition(request, reportID);
1047                                                 request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
1048                                                 ReportSchedule reportSchedule = null;
1049                                                 if(rdef!=null) {
1050                                                         reportSchedule = new ReportSchedule(reportID, AppUtils.getUserID(request), false, request); 
1051                                                 }
1052                                                 request.getSession().setAttribute(AppConstants.SI_REPORT_SCHEDULE, reportSchedule);
1053                                         }
1054                                 } else {
1055                                         //String message = "You have reached your schedule limit. Please visit this page again after removing your old schedules in \"My Schedule\" section.";
1056                                         String message = "You have reached the scheduled report limit for your Login ID.  Please remove any old schedule requests in the \"My Scheduled Reports\" screen before attempting to schedule any additional reports.";
1057                                         nextPage = (new ErrorHandler()).processFatalError(request, new RaptorSchedularException(message));
1058                                 }
1059                                 
1060                         } catch(Exception ex) { ex.printStackTrace();}
1061                 return nextPage;
1062         }
1063         
1064         public String processSchedule(HttpServletRequest request, String nextPage) {
1065
1066                 // Added for form field chaining in schedule tab so that setParamValues() is called
1067
1068                 request.setAttribute(AppConstants.SCHEDULE_ACTION, "Y");
1069                 if(request.getSession().getAttribute(AppConstants.SI_REPORT_SCHEDULE)!=null && (!AppUtils.getRequestNvlValue(request, AppConstants.RI_ACTION).equals("report.schedule_only_from_search"))) {
1070                         String action = nvl(request.getParameter(AppConstants.RI_WIZARD_ACTION),
1071                                         AppConstants.WA_BACK);
1072                         String scheduleID = "";
1073                         scheduleID = AppUtils.getRequestValue(request, AppConstants.RI_SCHEDULE_ID);
1074                         ReportSchedule reportSchedule = null;
1075
1076                         if( nvl(scheduleID).length() <= 0) {
1077                                 reportSchedule = (ReportSchedule) request.getSession().getAttribute(AppConstants.SI_REPORT_SCHEDULE);
1078                         scheduleID = reportSchedule.getScheduleID();
1079                         }
1080                         
1081                         String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID);
1082                         try {
1083                                 boolean isAdmin = AppUtils.isAdminUser(request);
1084                                 boolean check = ReportLoader.doesUserCanScheduleReport(request, scheduleID);
1085                                 if(!isAdmin && !check) {
1086                                         String message = "You have reached the scheduled report limit for your Login ID.  Please remove any old schedule requests in the My Scheduled Reports screen before attempting to schedule any additional reports.";
1087                                         nextPage = (new ErrorHandler()).processFatalError(request, new RaptorSchedularException(message));
1088                                         return nextPage;
1089                                 }
1090                                 
1091                         } catch (Exception ex) { ex.printStackTrace();} 
1092                         if(reportSchedule == null) reportSchedule = new ReportSchedule(reportID, scheduleID, AppUtils.getUserID(request), request);
1093                         String formFields = "";
1094                         formFields = reportSchedule.getFormFields();
1095                         formFields = (formFields.length()>1)?formFields.substring(1):formFields;
1096                         String formFieldsArr[] = formFields.split("&");
1097                     String  sessionParams[] = Globals.getSessionParamsForScheduling().split(",");
1098                     
1099                     for (int i=0; i<sessionParams.length; i++) {
1100                        for (int j = 0; j < formFieldsArr.length; j++) {
1101                                   if(formFieldsArr[j].startsWith(sessionParams[i])) {
1102                                           request.setAttribute(sessionParams[i], formFieldsArr[j].substring(formFieldsArr[j].indexOf("=")+1));
1103                                   }
1104                                  
1105                            }    
1106                     }
1107
1108                         boolean reportUpdated = false;
1109                         WizardProcessor wp = null;
1110                         Connection connection = null;
1111                         try {
1112                                 connection = DbUtils.startTransaction();
1113                                 wp = new WizardProcessor();
1114                                 String toListUpdated = nvl(request.getParameter("toListUpdated"),"false" );
1115                                 reportUpdated = wp.processAdhocSchedule(request, action);
1116                                 if(reportUpdated && toListUpdated.equals("false")) {
1117                                         request.setAttribute("message", "Report has been scheduled successfully");
1118                                         reportSchedule = (ReportSchedule) request.getSession().getAttribute(AppConstants.SI_REPORT_SCHEDULE);                                   
1119                                         //if(AppUtils.getRequestNvlValue(request, AppConstants.RI_SCHEDULE_ID).length()<=0) {
1120                                         reportSchedule.persistScheduleData(connection, request);
1121                                         DbUtils.commitTransaction(connection);
1122                                         //}
1123                                 }
1124                         } catch (ValidationException ve) {
1125                                 (new ErrorHandler()).processError(request, ve);
1126                         } catch (RaptorException e) {
1127                                 nextPage = (new ErrorHandler()).processFatalError(request, e);
1128                     e.printStackTrace();
1129                     try {
1130                         DbUtils.rollbackTransaction(connection);
1131                     } catch (Exception e1) {e1.printStackTrace();}
1132                         } catch (Throwable t) {
1133                                 t.printStackTrace();
1134                         }
1135                         finally {
1136                                 try {
1137                                         DbUtils.clearConnection(connection);
1138                                 } catch (Exception e1) {e1.printStackTrace();}
1139             }                   
1140                         request.setAttribute("schedule_only", "Y");
1141                 //request.getSession().removeAttribute(AppConstants.SI_REPORT_SCHEDULE);
1142                 
1143                         return nextPage;
1144                 } else {
1145                         try {
1146                                 String scheduleID = "";
1147                                 scheduleID = AppUtils.getRequestValue(request, AppConstants.RI_SCHEDULE_ID);
1148                                 String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID);
1149                                 request.setAttribute("schedule_only", "Y");
1150                                 ReportHandler rh = new ReportHandler();
1151                                 ReportDefinition rdef = rh.loadReportDefinition(request, reportID);
1152                                 ReportSchedule reportSchedule = null;
1153                                 if(rdef!=null) {
1154                                         reportSchedule = new ReportSchedule(reportID, scheduleID, AppUtils.getUserID(request), request);
1155                                 }
1156                                 String formFields = "";
1157                                 formFields = reportSchedule.getFormFields();
1158                                 formFields = (formFields.length()>1)?formFields.substring(1):formFields;
1159                                 String formFieldsArr[] = formFields.split("&");
1160                             String  sessionParams[] = Globals.getSessionParamsForScheduling().split(",");
1161                             
1162                             for (int i=0; i<sessionParams.length; i++) {
1163                                for (int j = 0; j < formFieldsArr.length; j++) {
1164                                           if(formFieldsArr[j].startsWith(sessionParams[i])) {
1165                                                   request.setAttribute(sessionParams[i], formFieldsArr[j].substring(formFieldsArr[j].indexOf("=")+1));
1166                                           }
1167                                          
1168                                    }    
1169                             }                           
1170                                 request.getSession().setAttribute(AppConstants.SI_REPORT_SCHEDULE, reportSchedule);
1171                                 request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
1172                         } catch (RaptorException e) {
1173                                 nextPage = (new ErrorHandler()).processFatalError(request, e);
1174                         }
1175
1176                         return nextPage;
1177                 }
1178         } // processSchedule
1179
1180         /****Remove Report Data from Session when Javascript throw error on onSubmit***/
1181         public String removeReportDataFromSession (HttpServletRequest request, String nextPage) {
1182                     HttpSession session = request.getSession(false);
1183 /*                      if (session.getAttribute(AppConstants.RI_REPORT_DATA)!=null)
1184                                 request.getSession().removeAttribute(AppConstants.RI_REPORT_DATA);
1185                         if (request.getAttribute(AppConstants.RI_REPORT_DATA)!=null)
1186                                 request.removeAttribute(AppConstants.RI_REPORT_DATA);
1187                         if (session.getAttribute(AppConstants.RI_CHART_DATA)!=null)
1188                                 request.getSession().removeAttribute(AppConstants.RI_CHART_DATA);
1189                         if (request.getAttribute(AppConstants.RI_CHART_DATA)!=null)
1190                                 request.removeAttribute(AppConstants.RI_CHART_DATA);
1191 */                      /*if (session.getAttribute(AppConstants.SI_REPORT_RUNTIME)!=null)
1192                                 request.getSession().removeAttribute(AppConstants.SI_REPORT_RUNTIME);*/
1193                         //request.setAttribute(AppConstants.RI_RESET_ACTION, "Y");
1194                         return nextPage;
1195                 
1196         } // processScheduleDelete
1197
1198         /****Added to delete a schedule***/
1199         public String processScheduleDelete(HttpServletRequest request, String nextPage) {
1200
1201                 // Added for form field chaining in schedule tab so that setParamValues() is called
1202                 request.setAttribute(AppConstants.SCHEDULE_ACTION, "Y");
1203                 try {
1204                         String scheduleID = "";
1205                         scheduleID = AppUtils.getRequestValue(request, AppConstants.RI_SCHEDULE_ID);
1206                         String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID);
1207                         ReportHandler rh = new ReportHandler();
1208                         ReportDefinition rdef = rh.loadReportDefinition(request, reportID);
1209                         String myScheduleRepID = AppUtils.getRequestNvlValue(request, "myScheduleRepId");
1210                         if (myScheduleRepID.equals(""))
1211                                 myScheduleRepID = "2670";
1212                         ReportSchedule reportSchedule = null;
1213                         if(rdef!=null) {
1214                                 reportSchedule = new ReportSchedule(reportID, scheduleID, AppUtils.getUserID(request), request);
1215                                 Connection connection = null;
1216                                 
1217                                 try {
1218                                         connection = DbUtils.startTransaction();
1219                                         reportSchedule.deleteScheduleData(connection);
1220                                         DbUtils.commitTransaction(connection);
1221                                 } catch (ValidationException ve) {
1222                                         (new ErrorHandler()).processError(request, ve);
1223                                 } catch (RaptorException e) {
1224                                         nextPage = (new ErrorHandler()).processFatalError(request, e);
1225                             e.printStackTrace();
1226                             try {
1227                                 DbUtils.rollbackTransaction(connection);
1228                             } catch (Exception e1) {e1.printStackTrace();}
1229                                 } catch (Throwable t) {
1230                                         t.printStackTrace();
1231                                 }
1232                                 finally {
1233                                         try {
1234                                                 DbUtils.clearConnection(connection);
1235                                         } catch (Exception e1) {e1.printStackTrace();}
1236                                 }
1237                         }
1238                         request.setAttribute(AppConstants.RI_REPORT_ID, myScheduleRepID);
1239                         request.setAttribute(AppConstants.RI_REFRESH, "y");
1240                         nextPage = this.reportRun(request, nextPage);
1241                 } catch (RaptorException e) {
1242                                 nextPage = (new ErrorHandler()).processFatalError(request, e);
1243                 }
1244                 return nextPage;
1245                 
1246         } // processScheduleDelete
1247         
1248         public String reportWizard(HttpServletRequest request, String nextPage) {
1249                 String action = nvl(request.getParameter(AppConstants.RI_WIZARD_ACTION),
1250                                 AppConstants.WA_BACK);
1251                 String goToStep = nvl(request.getParameter(AppConstants.RI_GO_TO_STEP));
1252                 try {
1253                         (new WizardProcessor()).processWizardStep(request);
1254
1255                         ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(
1256                                         AppConstants.SI_REPORT_DEFINITION);
1257                         WizardSequence ws = rdef.getWizardSequence();
1258                         //debugLogger.debug("Step Count " + ws.getStepCount());
1259                         //debugLogger.debug("Dashboard " + ((ws instanceof WizardSequenceDashboard) ? ws.getStepCount(): "Not a Dashboard"));
1260                         //debugLogger.debug("GO TO STEP LENGTH " + goToStep.length());
1261                         //debugLogger.debug("NumDash Cols in Action Handler " + AppUtils.getRequestNvlValue(request, "numDashCols"));
1262                         if (goToStep.length() > 0)
1263                                 ws.performGoToStep(goToStep);
1264                         else
1265                                 ws.performAction(action, rdef);
1266                 } catch (ValidationException ve) {
1267                         (new ErrorHandler()).processError(request, ve);
1268                 } catch (RaptorException e) {
1269                         nextPage = (new ErrorHandler()).processFatalError(request, e);
1270                 } catch (Throwable t) {
1271                         t.printStackTrace();
1272                 }
1273
1274                 return nextPage;
1275         } // reportWizard
1276
1277     public String refreshCache ( HttpServletRequest request, String nextPage ) {
1278         //DataCache.refreshReportTableSources();
1279         removeVariablesFromSession(request);
1280         DataCache.refreshAll();
1281         Globals.getAppUtils().resetUserCache();
1282         request.setAttribute("message", "Cache Refreshed");
1283         return nextPage;
1284     }
1285         public String reportCreate(HttpServletRequest request, String nextPage) {
1286                 try {
1287                         removeVariablesFromSession(request);            
1288                         ReportDefinition rdef = ReportDefinition.createBlank(request);
1289
1290                         request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
1291                         // request.setAttribute(AppConstants.RI_CUR_STEP,
1292                         // AppConstants.WS_DEFINITION);
1293                         DataCache.refreshReportTableSources();
1294                         request.getSession().removeAttribute("remoteDB");
1295                 } catch (RaptorException e) {
1296                         nextPage = (new ErrorHandler()).processFatalError(request, e);
1297                 }
1298
1299                 return nextPage;
1300         } // reportCreate
1301
1302         public String reportImportSave(HttpServletRequest request, String nextPage) {
1303                 try {
1304                         String reportXML = nvl(AppUtils.getRequestValue(request, "reportXML")).trim();
1305
1306                         ReportHandler rh = new ReportHandler();
1307                         ReportDefinition rdef = rh.createReportDefinition(request, "-1", reportXML);
1308                         rdef.updateReportDefType();
1309                         rdef.generateWizardSequence(request);
1310                         rdef.setReportName("Import: " + rdef.getReportName());
1311                         rdef.clearAllDrillDowns();
1312
1313                         request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
1314                 } catch (RaptorException e) {
1315                         request.setAttribute("error_extra_msg", "Unable to parse XML. Nested error: ");
1316                         nextPage = (new ErrorHandler()).processFatalError(request, e);
1317                 }
1318
1319                 return nextPage;
1320         } // reportImportSave
1321
1322         private String reportLoad(HttpServletRequest request, String nextPage, boolean asCopy) {
1323                 try {
1324                         String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID);
1325
1326                         ReportHandler rh = new ReportHandler();
1327                         ReportDefinition rdef = rh.loadReportDefinition(request, reportID);
1328                         if (asCopy)
1329                                 rdef.setAsCopy(request);
1330                         else
1331                                 rdef.checkUserWriteAccess(request);
1332
1333                         rdef.getWizardSequence().performGoToStep(AppConstants.WS_DEFINITION);
1334                         request.getSession().setAttribute(AppConstants.SI_REPORT_DEFINITION, rdef);
1335                         // request.setAttribute(AppConstants.RI_CUR_STEP,
1336                         // AppConstants.WS_DEFINITION);
1337                 } catch (RaptorException e) {
1338                         nextPage = (new ErrorHandler()).processFatalError(request, e);
1339                 }
1340
1341                 return nextPage;
1342         } // reportLoad
1343
1344         public String reportCopy(HttpServletRequest request, String nextPage) {
1345                 return reportLoad(request, nextPage, true);
1346         } // reportCopy
1347
1348         public String reportEdit(HttpServletRequest request, String nextPage) {
1349                 return reportLoad(request, nextPage, false);
1350         } // reportEdit
1351
1352         public String reportDelete(HttpServletRequest request, String nextPage) {
1353                 try {
1354                         String reportID = AppUtils.getRequestValue(request, AppConstants.RI_REPORT_ID);
1355                         try {
1356                                 int i = Integer.parseInt(reportID);
1357                         } catch(NumberFormatException ex) {
1358                                 throw new UserDefinedException("Not a valid report id");
1359                         }
1360                         String userID = AppUtils.getUserID(request);
1361
1362                         (new ReportSecurity(reportID)).checkUserDeleteAccess(request);
1363
1364                         ReportLoader.deleteReportRecord(reportID);
1365
1366                         return "{\"deleted\":true}";
1367                         //nextPage = reportSearchExecute(request, nextPage);
1368                 } catch (RaptorException e) {
1369                         nextPage = (new ErrorHandler()).processFatalError(request, e);
1370                 }
1371
1372                 //return nextPage;
1373                 return "{\"deleted\":false}";
1374         } // reportDelete
1375
1376         private String generateSearchString(HttpServletRequest request) {
1377                 String searchString = AppUtils.getRequestNvlValue(request, AppConstants.RI_SEARCH_STRING);
1378                 boolean containFlag = AppUtils.getRequestFlag(request, AppConstants.RI_CONTAIN_FLAG);
1379                 return (searchString.length() > 0) ? ((containFlag ? "%" : "") + searchString + "%"):"";
1380         } // generateSearchString
1381
1382         public String reportFormFieldPopup(HttpServletRequest request, String nextPage) {
1383                 try {
1384                         ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(
1385                                         AppConstants.SI_REPORT_RUNTIME);
1386                         
1387                         FormField ff = rr.getFormField(request.getParameter(AppConstants.RI_FIELD_NAME));
1388                         ReportFormFields rff = rr.getReportFormFields();
1389                         
1390                         int idx = 0;
1391                         FormField ff1 = null;
1392                         Map fieldNameMap = new HashMap();
1393                         int countOfFields = 0 ;
1394             String userId = AppUtils.getUserID(request);
1395                         IdNameList lookup = ff.getLookupList();
1396                         String oldSQL = lookup.getOldSql();
1397
1398                         if(AppUtils.getRequestFlag(request, AppConstants.RI_TEXTFIELD_POP)) {
1399                                         for(rff.resetNext(); rff.hasNext(); idx++) { 
1400                                                  ff1 = rff.getNext();
1401                                                  fieldNameMap.put(ff1.getFieldName(), ff1.getFieldDisplayName());
1402                                                  countOfFields++;
1403                                         }
1404                 
1405                                         
1406                                         //List formParameter = new ArrayList();
1407                                         String formField = "";
1408                                         HashMap valuesMap = new HashMap();
1409                                         for(int i = 0 ; i < rff.size(); i++) {
1410                                                 formField = ((FormField)rff.getFormField(i)).getFieldName();
1411                                                 if(request.getParameterValues(formField) != null && request.getParameterValues(formField).length > 1 ) {
1412                                                         String[] vals = (String[]) request.getParameterValues(formField);
1413                                                         String value = "";
1414                                                         StringBuffer valueBuf = new StringBuffer();
1415                                                         for(int ii = 0 ; ii < vals.length; ii++) {
1416                                                                 if(ii == 0) valueBuf.append("(");
1417                                                                 valueBuf.append(vals[ii]); 
1418                                                                 if(ii == vals.length-1) valueBuf.append(")");
1419                                                                 else valueBuf.append(",");
1420                                                         }
1421                                                         value = valueBuf.toString();
1422                                                         valuesMap.put(fieldNameMap.get(formField), value);
1423                                                 } else if(request.getParameter(formField) != null) {
1424                                                         valuesMap.put(fieldNameMap.get(formField), request.getParameter(formField));
1425                                                 }
1426                                         }
1427                                         if(countOfFields != 0) {
1428                                                 IdNameSql lu = (IdNameSql) lookup;
1429                                                 String SQL = (oldSQL==null)?lu.getSql():oldSQL;
1430                                                 oldSQL = SQL;
1431                                                 Set set = valuesMap.entrySet();
1432                                                 String value = "";
1433                                                 StringBuffer valueBuf = new StringBuffer();
1434                                                 for(Iterator iter = set.iterator(); iter.hasNext(); ) {
1435                                                         Map.Entry entry = (Entry) iter.next();
1436                                                         if(entry.getValue() instanceof String[]) {
1437                                                                 String[] vals = (String[]) entry.getValue();
1438                                                                 for(int i = 0 ; i < vals.length; i++) {
1439                                                                         if(i == 0) valueBuf.append("(");
1440                                                                         valueBuf.append(vals[i]); 
1441                                                                         if(i == vals.length-1) valueBuf.append(")");
1442                                                                         else valueBuf.append(",");
1443                                                                 }
1444                                                                 value = valueBuf.toString();
1445                                                         } else {
1446                                                                 value = (String) entry.getValue();
1447                                                         }
1448                                                         // added so empty string would be treated as null value if not given in single quotes.
1449                                                         if(value==null || value.trim().length()<=0) value="NULL";
1450                                                         SQL = Utils.replaceInString(SQL, "["+entry.getKey()+"]", Utils.oracleSafe(value));
1451                                                 }
1452                                                 if(request.getParameter(ff.getFieldName())!=null) {
1453                                                         lookup = new IdNameSql(-1,SQL,null);
1454                                                         lookup.setOldSql(oldSQL);
1455                                                 }
1456                                                 else {
1457                                                         lookup = new IdNameSql(-1,SQL,lu.getDefaultSQL());
1458                                                         lookup.setOldSql(oldSQL);
1459                                                 }
1460                                                 //lookup.loadData("0");
1461                                         }
1462                                         if(lookup instanceof IdNameSql)  ((IdNameSql)lookup).setDataSizeUsedinPopup(-3); // -3 indicates to run the count sql for pagination. 
1463                         }
1464                         if(lookup instanceof IdNameSql) {
1465                                 ((IdNameSql)lookup).loadUserData(request.getParameter(AppConstants.RI_NEXT_PAGE),
1466                                         nvl(generateSearchString(request),"%"), rr.getDBInfo(),userId);
1467                         }
1468
1469                         int dataSizeForPopUp = 0;
1470                         if(lookup instanceof IdNameSql) {
1471                                 dataSizeForPopUp = ((IdNameSql)lookup).getDataSizeUsedinPopup();
1472                         } else
1473                                 dataSizeForPopUp =  lookup.getDataSize();
1474                         
1475                         ff.setLookupList(lookup);
1476                         request.setAttribute("lookupList", lookup);
1477                         if(dataSizeForPopUp >= 0)
1478                                 request.getSession().setAttribute(AppConstants.SI_DATA_SIZE_FOR_TEXTFIELD_POPUP, ""+dataSizeForPopUp);
1479                 } catch (RaptorException e) {
1480                         e.printStackTrace();
1481                         nextPage = (new ErrorHandler()).processFatalError(request, e);
1482                 }
1483                 return nextPage;
1484         } // reportFormFieldPopup
1485
1486         public String reportValuesMapDefPopup(HttpServletRequest request, String nextPage) {
1487                 try {
1488                         ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(
1489                                         AppConstants.SI_REPORT_DEFINITION);
1490
1491                         String colName = AppUtils.getRequestNvlValue(request, "colName");
1492                         String colType = nvl(AppUtils.getRequestValue(request, "colType"),
1493                                         AppConstants.CT_CHAR);
1494                         String displayName = AppUtils.getRequestNvlValue(request, "displayName");
1495                         String displayFormat = AppUtils.getRequestNvlValue(request, "displayFormat");
1496                         String tableId = AppUtils.getRequestNvlValue(request, "tableId");
1497                         String dbInfo = rdef.getDBInfo();
1498                         if (Utils.isNull(dbInfo)) {
1499                                 dbInfo = (String) request.getSession().getAttribute("remoteDB");
1500                         }
1501                         /*String query = "SELECT x FROM (SELECT DISTINCT "
1502                                         + (colType.equals(AppConstants.CT_DATE) ? ("TO_CHAR(" + colName + ", '"
1503                                                         + nvl(displayFormat, AppConstants.DEFAULT_DATE_FORMAT) + "')")
1504                                                         : colName) + " x FROM "
1505                                         + rdef.getTableById(tableId).getTableName() + " WHERE " + colName
1506                                         + " IS NOT NULL ORDER BY 1) xx WHERE ROWNUM <= "
1507                                         + Globals.getDefaultPageSize();*/
1508                         
1509                         
1510                         String q1 = Globals.getReportValuesMapDefA();
1511
1512                         String q2 = Globals.getReportValuesMapDefB();
1513                         q2 = q2.replace("[colName]", colName);
1514                         q2 = q2.replace("[nvl(displayFormat, AppConstants.DEFAULT_DATE_FORMAT)]", nvl(displayFormat, AppConstants.DEFAULT_DATE_FORMAT));
1515                         
1516                         String q3 = Globals.getReportValuesMapDefC();
1517                         q3 = q3.replace("[colName]", colName);
1518                         
1519                         String q4 = Globals.getReportValuesMapDefD();
1520                         q4 = q4.replace("[rdef.getTableById(tableId).getTableName()]", rdef.getTableById(tableId).getTableName());
1521                         q4 = q4.replace("[colName]", colName);
1522                         q4 = q4.replace("[Globals.getDefaultPageSize()]", String.valueOf(Globals.getDefaultPageSize()));
1523                         
1524                         String query = q1 + (colType.equals(AppConstants.CT_DATE) ? q2 : q3) + q4;
1525
1526                         DataSet ds = ConnectionUtils.getDataSet(query, dbInfo);
1527                         request.setAttribute(AppConstants.RI_DATA_SET, ds);
1528                 } catch (RaptorException e) {
1529                         nextPage = (new ErrorHandler()).processFatalError(request, e);
1530                 }
1531
1532                 return nextPage;
1533         } // reportValuesMapDefPopup
1534
1535         public String reportDrillDownToReportDefPopup(HttpServletRequest request, String nextPage) {
1536                 try {
1537                         // ReportDefinition rdef = (ReportDefinition)
1538                         // request.getSession().getAttribute(AppConstants.SI_REPORT_DEFINITION);
1539                         String ddReportID = AppUtils
1540                                         .getRequestNvlValue(request, AppConstants.RI_REPORT_ID);
1541                         ReportRuntime ddRr = (new ReportHandler()).loadReportRuntime(request, ddReportID,
1542                                         false);
1543                         if (ddRr != null)
1544                                 request.setAttribute(AppConstants.RI_FORM_FIELDS, ddRr.getReportFormFields());
1545                 } catch (RaptorException e) {
1546                         nextPage = (new ErrorHandler()).processFatalError(request, e);
1547                 }
1548
1549                 return nextPage;
1550         } // reportDrillDownToReportDefPopup
1551
1552         public String reportFilterDataPopup(HttpServletRequest request, String nextPage) {
1553                 try {
1554                         ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(
1555                                         AppConstants.SI_REPORT_DEFINITION);
1556
1557                         String colId = AppUtils.getRequestNvlValue(request, AppConstants.RI_COLUMN_ID);
1558                         IdNameColLookup lookup = null;
1559                         String dbInfo = rdef.getDBInfo();
1560                         if (Utils.isNull(dbInfo)) {
1561                                 dbInfo = (String) request.getSession().getAttribute("remoteDB");
1562                         }
1563                         if (!AppUtils.getRequestFlag(request, AppConstants.RI_RESET_PARAMS))
1564                                 lookup = (IdNameColLookup) request.getSession().getAttribute(
1565                                                 AppConstants.SI_COLUMN_LOOKUP);
1566                         if (lookup == null || (!colId.equals(lookup.getColId()))) {
1567                                 DataColumnType dct = rdef.getColumnById(colId);
1568                                 lookup = new IdNameColLookup(colId, rdef.getTableById(dct.getTableId())
1569                                                 .getTableName(), dct.getColName(), rdef.getSelectExpr(dct), dct
1570                                                 .getColName()
1571                                                 + (dct.getColType().equals(AppConstants.CT_DATE) ? " DESC" : ""));
1572                                 request.getSession().setAttribute(AppConstants.SI_COLUMN_LOOKUP, lookup);
1573                         } // if
1574
1575                         lookup.loadData(nvl(request.getParameter(AppConstants.RI_NEXT_PAGE), "0"),
1576                                         generateSearchString(request), dbInfo);
1577                 } catch (RaptorException e) {
1578                         nextPage = (new ErrorHandler()).processFatalError(request, e);
1579                 }
1580
1581                 return nextPage;
1582         } // reportFilterDataPopup
1583
1584         public String reportShowSQLPopup(HttpServletRequest request, String nextPage) {
1585                 try {
1586                         ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(
1587                                         AppConstants.SI_REPORT_DEFINITION);
1588                         String reportSQL = rdef.generateSQL(AppUtils.getUserID(request),request);
1589
1590                         String[] sqlClause = { "SELECT ", "FROM ", "WHERE ", "GROUP BY ", "HAVING ",
1591                                         "ORDER BY " };
1592
1593                         int idxNext = 0;
1594                         StringBuffer sb = new StringBuffer();
1595                         while (idxNext < sqlClause.length) {
1596                                 sb.append("<b>");
1597                                 if (idxNext > 0)
1598                                         sb.append("&nbsp;&nbsp;&nbsp;&nbsp;");
1599                                 sb.append(sqlClause[idxNext]);
1600                                 sb.append("</b><br>\n");
1601
1602                                 int clauseStartPos = reportSQL.indexOf(sqlClause[idxNext])
1603                                                 + sqlClause[idxNext].length();
1604                                 do
1605                                         idxNext++;
1606                                 while ((idxNext < sqlClause.length)
1607                                                 && (reportSQL.indexOf(sqlClause[idxNext]) < 0));
1608
1609                                 String clauseContent = null;
1610                                 if (idxNext < sqlClause.length)
1611                                         clauseContent = reportSQL.substring(clauseStartPos, reportSQL
1612                                                         .indexOf(sqlClause[idxNext]) - 1);
1613                                 else
1614                                         clauseContent = reportSQL.substring(clauseStartPos);
1615
1616                                 while (clauseContent.length() > 0) {
1617                                         int braketCount = 0;
1618                                         StringBuffer nextToken = new StringBuffer();
1619                                         for (int i = 0; i < clauseContent.length(); i++) {
1620                                                 char ch = clauseContent.charAt(i);
1621                                                 nextToken.append(ch);
1622                                                 if (ch == '(')
1623                                                         braketCount++;
1624                                                 else if (ch == ')')
1625                                                         braketCount--;
1626                                                 else if (ch == ',')
1627                                                         if (braketCount == 0)
1628                                                                 break;
1629                                         } // for %>
1630
1631                                         sb.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
1632                                         sb.append(nextToken.toString());
1633                                         sb.append("<br>\n");
1634
1635                                         if (nextToken.length() < clauseContent.length())
1636                                                 clauseContent = clauseContent.substring(nextToken.length() + 1);
1637                                         else
1638                                                 clauseContent = "";
1639                                 } // while
1640                         } // while
1641
1642                         request.setAttribute(AppConstants.RI_FORMATTED_SQL, sb.toString());
1643                         request.setAttribute(AppConstants.RI_PAGE_TITLE, "Generated SQL");
1644                         request.setAttribute(AppConstants.RI_PAGE_SUBTITLE, "Generated SQL for report "
1645                                         + rdef.getReportName());
1646                 } catch (RaptorException e) {
1647                         nextPage = (new ErrorHandler()).processFatalError(request, e);
1648                 }
1649
1650                 return nextPage;
1651         } // reportShowSQLPopup
1652
1653         public String testSchedCondPopup(HttpServletRequest request, String nextPage) {
1654                 try {
1655                         ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(
1656                                         AppConstants.SI_REPORT_DEFINITION);
1657
1658                         String sql = AppUtils.getRequestNvlValue(request, AppConstants.RI_FORMATTED_SQL);
1659
1660                         request.setAttribute("msg_align", " align=center");
1661                         request.setAttribute(AppConstants.RI_PAGE_TITLE, "Test Scheduler Condition");
1662                         // request.setAttribute(AppConstants.RI_PAGE_SUBTITLE, ...);
1663                         //String query = "SELECT 1 FROM DUAL WHERE EXISTS (" + sql + ")";
1664                         
1665                         String query = Globals.getTestSchedCondPopup();
1666                         query = query.replace("[sql]", sql);
1667                         
1668                         DataSet ds = null;
1669                         String remoteDb = request.getParameter("remoteDbPrefix");
1670                         String remoteDbPrefix = (remoteDb != null && !remoteDb.equalsIgnoreCase("null")) ? remoteDb
1671                                         : rdef.getDBInfo();
1672                         ds = ConnectionUtils.getDataSet(sql, remoteDbPrefix);
1673                         // if ( (remoteDbPrefix!=null) &&
1674                         // (!remoteDbPrefix.equals(AppConstants.DB_LOCAL))) {
1675                         // Globals.getRDbUtils().setDBPrefix(remoteDbPrefix);
1676                         // ds = RemDbUtils.executeQuery(query);
1677                         // }
1678                         // else
1679                         // ds = DbUtils.executeQuery(query);
1680                         if (ds.getRowCount() == 0)
1681                                 request
1682                                                 .setAttribute(AppConstants.RI_FORMATTED_SQL,
1683                                                                 "<br><b>Condition NOT satisfied</b> - email notification will NOT be send.<br><br>");
1684                         else
1685                                 request
1686                                                 .setAttribute(AppConstants.RI_FORMATTED_SQL,
1687                                                                 "<br><b>Condition satisfied</b> - email notification will be send.<br><br>");
1688                 } catch (Exception e) {
1689                         // nextPage = (new ErrorHandler()).processFatalError(request, e);
1690                         request.setAttribute(AppConstants.RI_FORMATTED_SQL, "<br><b>SQL ERROR</b> "
1691                                         + e.getMessage() + "<br>Email notification will NOT be send.<br><br>");
1692                 }
1693
1694                 return nextPage;
1695         } // testSchedCondPopup
1696
1697         public String testRunSQLPopup(HttpServletRequest request, String nextPage) {
1698         String sql = AppUtils.getRequestNvlValue(request, AppConstants.RI_FORMATTED_SQL);
1699         if(nvl(sql).length()<=0) {
1700             sql = AppUtils.getRequestNvlValue(request, "reportSQL");
1701         }
1702         
1703
1704                 boolean chkFormFieldSQL = AppUtils.getRequestNvlValue(request,
1705                                 AppConstants.RI_CHK_FIELD_SQL).equals("Y");
1706                 try {
1707                         if (!sql.trim().toUpperCase().startsWith("SELECT"))
1708                                 throw new UserDefinedException(
1709                                                 "Invalid statement - the SQL must start with the keyword SELECT");
1710
1711                         ReportDefinition rdef = (ReportDefinition) request.getSession().getAttribute(
1712                                         AppConstants.SI_REPORT_DEFINITION);
1713                         if (!chkFormFieldSQL) {
1714                                 if (rdef.getFormFieldList() != null)
1715                                         for (Iterator iter = rdef.getFormFieldList().getFormField().iterator(); iter
1716                                                         .hasNext();) {
1717                                                 FormFieldType fft = (FormFieldType) iter.next();
1718                                                 String fieldId = fft.getFieldId();
1719                                                 String fieldDisplay = rdef.getFormFieldDisplayName(fft);
1720                                                 /*
1721                                                  * if(paramValues.isParameterMultiValue(fieldId))
1722                                                  * generatedSQL = Utils.replaceInString(generatedSQL,
1723                                                  * fieldDisplay, nvl(formatListValue((String)
1724                                                  * paramValues.get(fieldId), null, false, false, null),
1725                                                  * "NULL")); else
1726                                                  */
1727                                                 sql = Utils.replaceInString(sql, fieldDisplay, "NULL");
1728                                         } // for
1729                         } // if
1730                         DataSet ds = null;
1731                         String remoteDb = request.getParameter("remoteDbPrefix");
1732                         String remoteDbPrefix = (remoteDb != null && !remoteDb.equalsIgnoreCase("null")) ? remoteDb
1733                                         : rdef.getDBInfo();
1734             String userId = AppUtils.getUserID(request);
1735             sql = Utils.replaceInString(sql, "[LOGGED_USERID]", userId);
1736             String[] reqParameters = Globals.getRequestParams().split(",");
1737             String[] sessionParameters = Globals.getSessionParams().split(",");
1738             javax.servlet.http.HttpSession session = request.getSession();
1739             logger.debug(EELFLoggerDelegate.debugLogger, ("B4 testRunSQL " + sql));
1740             if(request != null ) {
1741                 for (int i = 0; i < reqParameters.length; i++) {
1742                     if(!reqParameters[i].startsWith("ff"))
1743                         sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i].toUpperCase()) );
1744                     else
1745                         sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) );   
1746                 }
1747              }
1748             if(session != null ) {
1749                 for (int i = 0; i < sessionParameters.length; i++) {
1750                     //if(!sessionParameters[i].startsWith("ff"))
1751                         //sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i].toUpperCase()) );
1752                     //else {
1753                         logger.debug(EELFLoggerDelegate.debugLogger, (" Session " + " sessionParameters[i] " + sessionParameters[i] + " " + (String)session.getAttribute(sessionParameters[i])));
1754                         sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) );
1755                     //}
1756                 }
1757              }
1758             logger.debug(EELFLoggerDelegate.debugLogger, ("After testRunSQL " + sql));
1759             
1760                         ds = ConnectionUtils.getDataSet(sql, remoteDbPrefix, true);
1761                         // if ( (remoteDbPrefix!=null) &&
1762                         // (!remoteDbPrefix.equals(AppConstants.DB_LOCAL))) {
1763                         // Globals.getRDbUtils().setDBPrefix(remoteDbPrefix);
1764                         // ds = RemDbUtils.executeQuery(sql,
1765                         // Globals.getDefaultPageSize()+1);
1766                         // }
1767                         // else
1768                         // ds = DbUtils.executeQuery(sql, Globals.getDefaultPageSize()+1);
1769                         if (chkFormFieldSQL && ds.getRowCount() > 0) {
1770                                         String id = ds.getString(0, "id");
1771                                         String name = ds.getString(0, "name");
1772                         } // if
1773
1774                         request.setAttribute(AppConstants.RI_DATA_SET, ds);
1775                 } catch (RaptorException e) {
1776                         request.setAttribute(AppConstants.RI_EXCEPTION, e);
1777                 }
1778
1779                 return nextPage;
1780         } // testRunSQLPopup
1781
1782         public String importSemaphorePopup(HttpServletRequest request, String nextPage) {
1783                 try {
1784                         (new WizardProcessor()).processImportSemaphorePopup(request);
1785                 } catch (RaptorException e) {
1786                         nextPage = (new ErrorHandler()).processFatalError(request, e);
1787                 }
1788
1789                 return nextPage;
1790         } // importSemaphorePopup
1791
1792         public String saveSemaphorePopup(HttpServletRequest request, String nextPage) {
1793                 try {
1794                         (new WizardProcessor()).processSemaphorePopup(request);
1795                 } catch (RaptorException e) {
1796                         nextPage = (new ErrorHandler()).processFatalError(request, e);
1797                 }
1798
1799                 return nextPage;
1800         } // saveSemaphorePopup
1801
1802         public String gotoJsp(HttpServletRequest request, String nextPage) {
1803                 return nextPage;
1804         } // gotoJsp
1805     
1806     public String downloadAll(HttpServletRequest request, String nextPage) throws InterruptedException, IOException, Exception {
1807         String emailId = null;
1808         String pdfAttachmentKey = AppUtils.getRequestValue(request, "pdfAttachmentKey");
1809         boolean isFromSchedule = nvl(pdfAttachmentKey).length()>0;
1810         if(!isFromSchedule)
1811                 emailId = AppUtils.getUserEmail(request);
1812         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
1813         SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
1814         java.util.Date currDate = new java.util.Date();
1815         String timestamp = sdf.format(currDate);
1816         String dateStr = sdf1.format(currDate);
1817         
1818         String userId = null;
1819         if(!isFromSchedule)
1820                 userId = AppUtils.getUserID(request);
1821         else
1822                 userId = AppUtils.getRequestValue(request, "user_id");
1823         Runtime runtime = Runtime.getRuntime();
1824         ReportRuntime rr = null;
1825         if(!isFromSchedule) {
1826                 rr = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
1827                 if(rr!=null) AppUtils.getUserEmail(request);
1828         }
1829         String scheduleId = "";
1830         
1831         if(isFromSchedule) {
1832                 String reportID =  null;
1833                         String report_email_sent_log_id = AppUtils.getRequestValue(request, "log_id");
1834                         /*String query =        "Select user_id, rep_id from CR_REPORT_EMAIL_SENT_LOG" +
1835                                                         " where rownum = 1" +
1836                                                         " and gen_key='"+pdfAttachmentKey.trim()+"'" + 
1837                                                         " and log_id ="+report_email_sent_log_id.trim() +
1838                                                         " and (sysdate - sent_date) < 1 ";*/
1839                         
1840                         String query = Globals.getDownloadAllEmailSent();
1841                         query = query.replace("[pdfAttachmentKey.trim()]", pdfAttachmentKey.trim());
1842                         query = query.replace("[report_email_sent_log_id.trim()]", report_email_sent_log_id.trim());
1843                         
1844                         DataSet ds = DbUtils.executeQuery(query, 1);
1845                         if(!ds.isEmpty()) {
1846                                 userId = ds.getString(0,"user_id");
1847                                 reportID  = ds.getString(0, "rep_id");
1848                                 request.setAttribute("schedule_email_userId", userId);
1849                         } else {
1850                                 request.setAttribute("message", "This link has expired, please <a href=''>login</a> and regenerate the report");
1851                                 return "raptor/message.jsp"; 
1852                         }
1853                         
1854                         ReportHandler rh1 = new ReportHandler();
1855                 
1856                 if(reportID !=null && nvl(pdfAttachmentKey).length()>0) {
1857                                  rr = rh1.loadReportRuntime(request, reportID, true, 1);
1858                                  rr.loadReportData(-1, userId, 1000 ,request, false /*download*/);
1859                 }
1860                 
1861                 String d_sql = Globals.getDownloadAllGenKey();
1862                 d_sql = d_sql.replace("[pdfAttachmentKey]", pdfAttachmentKey);
1863                 
1864                 //ds = DbUtils.executeQuery("select schedule_id from cr_report_email_sent_log u where U.GEN_KEY = '"+ pdfAttachmentKey + "'");
1865                 
1866                 ds = DbUtils.executeQuery(d_sql);
1867             for (int i = 0; i < ds.getRowCount(); i++) {
1868                 scheduleId = ds.getString(i,0); 
1869             }
1870         }
1871         logger.debug(EELFLoggerDelegate.debugLogger, ("SQL2:\n"+ rr.getCachedSQL()));
1872         String fileName = rr.getReportID()+"_"+userId+"_"+timestamp;
1873         boolean flag = false;
1874         logger.debug(EELFLoggerDelegate.debugLogger, (""+Utils.isDownloadFileExists(rr.getReportID()+"_"+userId+"_"+dateStr)));
1875        // if(Utils.isDownloadFileExists(rr.getReportID()+"_"+userId+"_"+dateStr)) {
1876        //     flag = true;
1877        // }
1878         
1879         if(flag){
1880             String strFileName = Utils.getLatestDownloadableFile(rr.getReportID()+"_"+userId+"_"+dateStr);
1881             //debugLogger.debug("File Name " + strFileName);
1882             StringBuffer messageBuffer = new StringBuffer("");            
1883             messageBuffer.append("Download data file using the following link<BR>");
1884             messageBuffer.append("<a href=\"" + request.getContextPath() + "/raptor/dwnld/data/" +
1885             strFileName + "\">click here</a>.</p>");
1886             request.setAttribute("message", messageBuffer.toString());  
1887         }
1888         else if(!flag) {
1889         String whole_fileName = (Globals.getShellScriptDir() +AppConstants.SHELL_QUERY_DIR+ fileName+AppConstants.FT_SQL);
1890         String whole_columnsfileName = (Globals.getShellScriptDir() +AppConstants.SHELL_QUERY_DIR+ fileName+AppConstants.FT_COLUMNS);        
1891         
1892         logger.debug(EELFLoggerDelegate.debugLogger, ("FILENAME "+whole_fileName));
1893
1894             List l = rr.getAllColumns();
1895             StringBuffer allColumnsBuffer = new StringBuffer();
1896             DataColumnType dct = null;
1897             
1898             for (Iterator iter = l.iterator(); iter.hasNext();) {
1899                 dct = (DataColumnType) iter.next();
1900                 allColumnsBuffer.append(dct.getDisplayName());
1901                 if(iter.hasNext())
1902                  allColumnsBuffer.append("|");
1903             }
1904             try {
1905             PrintWriter xmlOut = new PrintWriter(new BufferedWriter(new FileWriter(new File(whole_columnsfileName))));
1906             xmlOut.println(allColumnsBuffer.toString());
1907             xmlOut.flush();
1908             xmlOut.close();
1909             } catch (IOException e) {e.printStackTrace();}
1910             try {
1911             PrintWriter xmlOut = new PrintWriter(new BufferedWriter(new FileWriter(new File(whole_fileName))));
1912             logger.debug(EELFLoggerDelegate.debugLogger, ("**************************"));
1913             logger.debug(EELFLoggerDelegate.debugLogger, (rr.getWholeSQL()));
1914             logger.debug(EELFLoggerDelegate.debugLogger, ("************************"));
1915             logger.debug(EELFLoggerDelegate.debugLogger, ("************************"));
1916             logger.debug(EELFLoggerDelegate.debugLogger, (rr.parseReportSQL(rr.getWholeSQL())));
1917             xmlOut.println(rr.parseReportSQL(rr.getWholeSQL()));
1918             //xmlOut.println("******************");
1919             //xmlOut.println(rr.getWholeSQL());
1920             xmlOut.flush();
1921             xmlOut.close();
1922             } catch (IOException e) {e.printStackTrace();}
1923         
1924         StringBuffer command = new StringBuffer(Globals.getShellScriptDir() + AppConstants.SHELL_SCRIPTS_DIR);
1925         if(nvl(emailId).length()>0) {
1926                 command.append(AppConstants.SHELL_SCRIPT_NAME + " " + (fileName+AppConstants.FT_SQL));
1927                 command.append(" "+emailId);
1928         }
1929         else if (nvl(scheduleId).length()>0) {
1930                 command.append(AppConstants.SCHEDULE_SHELL_SCRIPT_NAME + " " + (fileName+AppConstants.FT_SQL));
1931                 command.append(" " + scheduleId);
1932         }
1933         logger.debug(EELFLoggerDelegate.debugLogger, ("Command " +  command));
1934         Process downloadProcess = runtime.exec(command.toString());
1935         logger.debug(EELFLoggerDelegate.debugLogger, ("Command Executed "));
1936         //Connection connection = DbUtils.getConnection();
1937         Enumeration enum1 = rr.getParamKeys();
1938         String value = "", key = "";
1939         String paramStr = "";
1940         StringBuffer paramBuffer = new StringBuffer();
1941         if(enum1!=null) {
1942             for (; enum1.hasMoreElements();) {
1943                  key = (String) enum1.nextElement();
1944                  value = rr.getParamValue(key);
1945                  paramBuffer.append(key+":"+value+" ");
1946             }
1947          paramStr = paramBuffer.toString();
1948         }
1949         
1950         StringBuffer retrieveUserEmailQry = null;
1951         ArrayList userEmailList = new ArrayList(); 
1952         if(nvl(scheduleId).length()>0) {
1953                 /*retrieveUserEmailQry = new StringBuffer();
1954                 retrieveUserEmailQry.append(" SELECT ");
1955                 retrieveUserEmailQry.append(" au.user_id ");
1956             retrieveUserEmailQry.append(" FROM ");
1957             retrieveUserEmailQry.append(" (SELECT rs.schedule_id, rs.rep_id FROM cr_report_schedule rs WHERE rs.enabled_yn='Y' AND rs.run_date IS NOT NULL "); 
1958             retrieveUserEmailQry.append(" AND rs.schedule_id = " + scheduleId + " ) x, cr_report r, app_user au ");
1959             retrieveUserEmailQry.append(" WHERE ");
1960             retrieveUserEmailQry.append("x.rep_id = r.rep_id "); 
1961             retrieveUserEmailQry.append(" AND au.user_id IN (SELECT rsu.user_id FROM cr_report_schedule_users rsu WHERE rsu.schedule_id = x.schedule_id and rsu.schedule_id = " + scheduleId );
1962             retrieveUserEmailQry.append(" UNION ");
1963             retrieveUserEmailQry.append(" SELECT ur.user_id FROM fn_user_role ur "); 
1964             retrieveUserEmailQry.append(" WHERE ur.role_id IN ");
1965             retrieveUserEmailQry.append(" (SELECT rsu2.role_id FROM cr_report_schedule_users rsu2 "); 
1966             retrieveUserEmailQry.append(" WHERE rsu2.schedule_id = x.schedule_id and ");
1967             retrieveUserEmailQry.append(" rsu2.schedule_id = "+ scheduleId + ")) ");*/
1968             
1969             String r_sql = Globals.getDownloadAllRetrieve();
1970             r_sql = r_sql.replace("[scheduleId]", scheduleId);
1971             
1972            // DataSet ds = DbUtils.executeQuery(retrieveUserEmailQry.toString());
1973             DataSet ds = DbUtils.executeQuery(r_sql);
1974             
1975             for (int i = 0; i < ds.getRowCount(); i++) {
1976                 userEmailList.add(ds.getString(i, 0));
1977             }            
1978             
1979          }
1980        // String insertQry = "insert into cr_report_dwnld_log (user_id,rep_id,file_name,dwnld_start_time,filter_params) values (?,?,?,?,?)";
1981         String insertQry = Globals.getDownloadAllInsert();
1982         
1983         
1984         Connection connection = null;
1985         PreparedStatement pst = null;
1986         try {
1987         connection = DbUtils.getConnection();
1988         pst = connection.prepareStatement(insertQry);
1989         if(nvl(emailId).length()>0){
1990                 pst.setInt(1, Integer.parseInt(userId));
1991                 pst.setInt(2, Integer.parseInt(rr.getReportID()));
1992                 pst.setString(3, fileName+AppConstants.FT_ZIP);
1993                 pst.setTimestamp(4,new java.sql.Timestamp(currDate.getTime()));
1994                 pst.setString(5,paramStr);
1995                 pst.execute();
1996                 connection.commit();
1997         } else {
1998                 for (int i = 0; i < userEmailList.size(); i++) {
1999                 pst.setInt(1, Integer.parseInt((String)userEmailList.get(i)));
2000                 pst.setInt(2, Integer.parseInt(rr.getReportID()));
2001                 pst.setString(3, fileName+AppConstants.FT_ZIP);
2002                 pst.setTimestamp(4,new java.sql.Timestamp(currDate.getTime()));
2003                 pst.setString(5,paramStr);
2004                 pst.execute();
2005                 connection.commit();
2006                         }
2007         }
2008         pst.close();
2009         connection.close();
2010         logger.debug(EELFLoggerDelegate.debugLogger, ("Data inserted"));
2011         } catch (SQLException ex) { 
2012                 throw new RaptorException(ex);
2013             } catch (ReportSQLException ex) { 
2014                 throw new RaptorException(ex);
2015             } catch (Exception ex) {
2016                 throw new RaptorException (ex);
2017             } finally {
2018                 try {
2019                         if(connection!=null)
2020                                 connection.close();
2021                         if(pst!=null)
2022                                 pst.close();
2023                 } catch (SQLException ex) {
2024                         throw new RaptorException(ex);
2025                 }
2026         }
2027         //DbUtils.commitTransaction(connection);
2028         //DbUtils.clearConnection(connection);
2029         
2030         
2031
2032 //        debugLogger.debug("|"+downloadProcess.toString() + "|");
2033 //        if (downloadProcess == null)
2034 //         throw new Exception("unable to create a process for command:" +
2035 //   command);
2036 //        int retCode= 1;
2037 //        try {
2038 //            retCode= downloadProcess.waitFor();
2039 //        } catch (InterruptedException e){
2040 //             e.printStackTrace();
2041 //        }        
2042 //        debugLogger.debug("retCode " + retCode);
2043 //        Process child = rtime.exec("/bin/bash");
2044 //        BufferedWriter outCommand = new BufferedWriter(new
2045 //        OutputStreamWriter(child.getOutputStream()));
2046 //        outCommand.write(Globals.getShellScriptName());
2047 //        outCommand.flush();
2048 //        int retCode = child.waitFor();
2049 //        debugLogger.debug("RetCode " + retCode);
2050           //request.setAttribute("message", "Shell Script is running in the background. You'll get an email once it is done");
2051         }
2052         
2053         return nextPage;
2054     }
2055         public String getChildDropDown(HttpServletRequest request, String nextPage) throws RaptorRuntimeException  {
2056                 
2057                 if(request.getParameter("firstTime") != null) { return nextPage; }
2058                 
2059                 /*ReportRuntime rr = (ReportRuntime) request.getSession().getAttribute(
2060                                 AppConstants.SI_REPORT_RUNTIME);
2061                 
2062                 String c_master = request.getParameter("c_master");
2063                 java.util.HashMap valuesMap = Globals.getRequestParamtersMap(request);
2064                 request.setAttribute("c_master", c_master);
2065                 
2066                 int idx = 0;
2067                 ReportFormFields rff = rr.getReportFormFields();
2068                 FormField ff = null;
2069                 for(rff.resetNext(); rff.hasNext(); idx++) { 
2070                          ff = rff.getNext();
2071                          
2072                          
2073                          if(ff.getDependsOn() != null && ff.getDependsOn().trim() != "")
2074                          {
2075                                  String val = request.getParameter(ff.getFieldName());
2076                                  request.setAttribute(ff.getFieldName(), ff.getHtml(val, valuesMap, rr));
2077                          }
2078                         
2079                 }
2080                 */
2081                 return nextPage;
2082                 
2083         }
2084     
2085         private void removeVariablesFromSession(HttpServletRequest request) {
2086                 HttpSession session = request.getSession(); 
2087         session.removeAttribute(AppConstants.DRILLDOWN_REPORTS_LIST);
2088         session.removeAttribute(AppConstants.DRILLDOWN_INDEX);
2089         session.removeAttribute(AppConstants.FORM_DRILLDOWN_INDEX);
2090                 session.removeAttribute(AppConstants.SI_BACKUP_FOR_REP_ID);
2091                 session.removeAttribute(AppConstants.SI_COLUMN_LOOKUP);
2092         session.removeAttribute(AppConstants.SI_DASHBOARD_REP_ID);
2093         session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME_MAP);
2094         session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTRUNTIME);
2095         session.removeAttribute(AppConstants.SI_DASHBOARD_REPORTDATA_MAP);
2096         session.removeAttribute(AppConstants.SI_DASHBOARD_CHARTDATA_MAP);
2097                 session.removeAttribute(AppConstants.SI_DASHBOARD_DISPLAYTYPE_MAP);
2098         session.removeAttribute(AppConstants.SI_DATA_SIZE_FOR_TEXTFIELD_POPUP);
2099         session.removeAttribute(AppConstants.SI_MAP);
2100                 session.removeAttribute(AppConstants.SI_MAP_OBJECT);
2101         session.removeAttribute(AppConstants.SI_REPORT_DEFINITION);                     
2102         session.removeAttribute(AppConstants.SI_REPORT_RUNTIME);                        
2103                 session.removeAttribute(AppConstants.SI_REPORT_RUN_BACKUP);
2104         session.removeAttribute(AppConstants.SI_REPORT_SCHEDULE);
2105         session.removeAttribute(AppConstants.RI_REPORT_DATA);
2106         session.removeAttribute(AppConstants.RI_CHART_DATA);
2107         session.removeAttribute(AppConstants.SI_FORMFIELD_INFO);
2108         session.removeAttribute(AppConstants.SI_FORMFIELD_DOWNLOAD_INFO);
2109         session.removeAttribute(AppConstants.EMBEDDED_REPORTRUNTIME_MAP);
2110         session.removeAttribute(AppConstants.EMBEDDED_REPORTDATA_MAP);
2111                 Enumeration<String> enum1 = session.getAttributeNames();
2112                 String attributeName = "";
2113                 while(enum1.hasMoreElements()) {
2114                         attributeName = enum1.nextElement();
2115                         if(attributeName.startsWith("parent_")) {
2116                                 session.removeAttribute(attributeName);
2117                         }
2118                 }       
2119         }
2120         
2121           
2122         private TreeMap getListOfReportsFromDashBoardHTML(String htmlString) {
2123           //String sourcestring = "<table border=1><tr><td>[Report#123]</td><td>[Report#124]</td></tr><tr><td>[Report#125]</td><td>[Report#126]</td></tr></table>";
2124                 String sourcestring = htmlString;
2125           //Pattern re = Pattern.compile("([a-z]+)\\[([a-z]+)([=<>]+)([a-z]+)\\]",Pattern.CASE_INSENSITIVE);
2126           //Pattern re = Pattern.compile("\\[([R][e][p][o][r][t][#])[(*)]\\]");
2127           Pattern re = Pattern.compile("\\[(.*?)\\]");   //\\[(.*?)\\]
2128           Matcher m = re.matcher(sourcestring);
2129           HashMap hashReports = new HashMap();
2130           int mIdx = 0;
2131             while (m.find()){
2132               for( int groupIdx = 0; groupIdx < m.groupCount(); groupIdx++ ){
2133                   String str = m.group(groupIdx);
2134                   //System.out.println(str);
2135                   hashReports.put(new String(Integer.toString(mIdx+1)), (str.substring(1).toLowerCase().startsWith("chart")?"c":"d") + str.substring(str.indexOf("#")+1, str.length()-1));
2136               }
2137               mIdx++;
2138             }
2139             // Sorting HashMap based on Keys 
2140             /*List mapKeys = new ArrayList(hashReports.keySet());
2141             List mapValues = new ArrayList(hashReports.values());
2142             hashReports.clear();
2143             hashReports = null;
2144             hashReports = new HashMap();
2145
2146             TreeSet sortedSet = new TreeSet(mapKeys);
2147             Object[] sortedArray = sortedSet.toArray();
2148             int size = sortedArray.length;
2149             for (int i=0; i<size; i++) {
2150                 hashReports.put(sortedArray[i], mapValues.get(mapKeys.indexOf(sortedArray[i])));
2151             }*/
2152             return new TreeMap(hashReports);
2153           }
2154         
2155         public ReportData getReportData(ReportRuntime reportRuntime, HttpServletRequest request, String sql, int maxRows) throws RaptorException {
2156                 
2157
2158         // replace the request parameter specified in the drill down
2159         List reportCols = reportRuntime.getAllColumns();
2160         StringBuffer colNames = new StringBuffer();
2161         for (Iterator<?> iter = reportCols.iterator(); iter.hasNext();) {
2162
2163             DataColumnType dc = (DataColumnType) iter.next();
2164                         if (colNames.length() > 0)
2165                                 colNames.append(", ");
2166                         colNames.append(dc.getColId());            
2167             if (dc.isVisible()) {
2168                 //TODO: Drilldown URL
2169                 //sql = reportRuntime.parseReportSQLForDrillDownParams(sql, dc, request);
2170             }
2171         }
2172
2173                 DataSet ds = null;
2174                 // try {
2175                 String dbInfo = reportRuntime.getDBInfo();
2176                 if(maxRows == 1)
2177                         sql += " limit "+ maxRows;
2178                 System.out.println("SQL getReportData()- " + sql);
2179                 ds = ConnectionUtils.getDataSet(sql, dbInfo);
2180                 int totalRows = 0;
2181                 /*if (reportRuntime.getReportDataSize() < 0) {*/
2182                                 //String countSQL = "SELECT count(*) FROM (" + sql + ") x";
2183                                 String dbType = "";
2184                                 
2185                                 if (dbInfo!=null && (!dbInfo.equals(AppConstants.DB_LOCAL))) {
2186                                         try {
2187                                          org.openecomp.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.openecomp.portalsdk.analytics.util.RemDbInfo();
2188                                          dbType = remDbInfo.getDBType(dbInfo);
2189                                         } catch (Exception ex) {
2190                                    throw new RaptorException(ex);                       
2191                                         }
2192                                 } 
2193
2194                                 totalRows = ds.getRowCount();
2195                 /*}*/
2196                 ReportData rd = new ReportData(0, true);
2197
2198         if(totalRows > 0) {
2199                 // Already defined changed for modifying request parameters 
2200         //List reportCols = getAllColumns();
2201                 Vector visibleCols = new Vector(reportCols.size());
2202                 Vector formatProcessors = new Vector(reportCols.size());
2203
2204                 // ColumnHeaderRow chr = new ColumnHeaderRow();
2205                 // rd.reportColumnHeaderRows.addColumnHeaderRow(chr);
2206                 // chr.setRowHeight("30");
2207         int count =0 ;
2208         
2209         /* ADDED */
2210                 ReportFormFields rff = reportRuntime.getReportFormFields();
2211                 ReportFormFields childReportFormFields = null;
2212                 String fieldDisplayName = "";
2213                 String fieldValue = "";
2214                 
2215                 for (int c = 0; c < reportCols.size(); c++) {
2216             if(reportCols.get(c)!=null) {
2217                                 DataColumnType dct = (DataColumnType) reportCols.get(c);
2218                                 if(nvl(dct.getDependsOnFormField()).length()>0 && nvl(dct.getDependsOnFormField()).indexOf("[")!=-1) {
2219                                         for(int i = 0 ; i < rff.size(); i++) {
2220                                                 fieldDisplayName = "["+((FormField)rff.getFormField(i)).getFieldDisplayName()+"]";
2221                                                 fieldValue = "";
2222                                                 //if(dct.getOriginalDisplayName()==null) dct.setOriginalDisplayName(dct.getDisplayName());
2223                                                 if (dct.getDependsOnFormField().equals(fieldDisplayName)) {
2224                                                         fieldValue = nvl(request.getParameter(((FormField)rff.getFormField(i)).getFieldName()));
2225                                                         
2226                                                         if (fieldValue.length()>0) {
2227                                                                 if(!fieldValue.toUpperCase().equals("Y"))
2228                                                                         dct.setDisplayName(fieldValue);
2229                                                                 if(!dct.isVisible())
2230                                                                         dct.setVisible(true);
2231                                                         } else {
2232                                                                 dct.setVisible(false);
2233                                                         }
2234                                                 }
2235                                         }
2236             }
2237                 }
2238                 }
2239         
2240         /* ADDED */
2241                 String displayName = "";
2242                 for (Iterator iter = reportCols.iterator(); iter.hasNext();) {
2243
2244             DataColumnType dc = (DataColumnType) iter.next();
2245                         
2246                         formatProcessors.add(count,new FormatProcessor(
2247                                         reportRuntime.getSemaphoreById(dc.getSemaphoreId()), dc.getColType(), dc
2248                                                         .getColFormat(), reportRuntime.getReportDefType().equals(
2249                                                         AppConstants.RD_SQL_BASED)));
2250             
2251                         /* TODO: Add Drilldown URL */
2252                         if (nvl(dc.getDrillDownURL()).length() > 0) {
2253                                 childReportFormFields = reportRuntime.getChildReportFormFields(request,dc.getDrillDownURL());
2254                         }
2255                         if (dc.isVisible()) {
2256                                 visibleCols.add(count,dc);
2257                                 //if(dc.getColId().startsWith("group")) {
2258                                         for (int d = 0; d < reportCols.size(); d++) {
2259                                                 if(reportCols.get(d)!=null) {
2260                                                         DataColumnType dct1 = (DataColumnType) reportCols.get(d);
2261                                                         if(dct1.getColId().equals(dc.getColId()+"_name") && ds.getRowCount()>0) {
2262                                                                         displayName = ds.getString(0,dct1.getColId());
2263                                                                 dc.setDisplayName(displayName);
2264                                                         }
2265                                                 }
2266                                         }
2267                                 //}
2268                                 
2269                                 VisualManager visualManager = reportRuntime.getVisualManager();
2270                                 rd.createColumn(dc.getColId(), dc.getDisplayName(), dc.getDisplayWidthInPxls(),dc.getDisplayHeaderAlignment(),
2271                                                 visualManager.isColumnVisible(dc.getColId()), visualManager
2272                                                                 .getSortByColId().equals(dc.getColId()) ? visualManager
2273                                                                 .getSortByAscDesc() : null, true, dc.getLevel()!=null?dc.getLevel():0, dc.getStart()!=null?dc.getStart():0, dc.getColspan()!=null?dc.getColspan():0, dc.isIsSortable()!=null?dc.isIsSortable():false);
2274                                 // chr.addColumnHeader(new ColumnHeader(dc.getDisplayName(),
2275                                 // (dc.getDisplayWidth()>100)?"10%":(""+dc.getDisplayWidth()+"%")));
2276                         } // if
2277             else {
2278               visibleCols.add(count,null);
2279                                 rd.createColumn(dc.getColId(), AppConstants.HIDDEN, dc.getDisplayWidthInPxls(), dc.getDisplayHeaderAlignment(), 
2280                                                 false, null,false,dc.getLevel()!=null?dc.getLevel():0, dc.getStart()!=null?dc.getStart():0, dc.getColspan()!=null?dc.getColspan():0, dc.isIsSortable()!=null?dc.isIsSortable():false);              
2281 //              formatProcessors.add(count,null);
2282             }
2283             count++;
2284                 } // for
2285
2286                 // Utils._assert(chr.size()==ds.getColumnCount(),
2287                 // "[ReportRuntime.loadLinearReportData] The number of visible columns
2288                 // does not match the number of data columns");
2289         //TODO: This should be optimized to accept -1 for flat file download
2290                 if(maxRows > totalRows) maxRows = totalRows;
2291                 ArrayList reportDataList = new ArrayList();
2292                 for (int r = 0; r < maxRows; r++) {
2293                         DataRow dr = new DataRow();
2294                         rd.reportDataRows.addDataRow(dr);
2295
2296                         for (int c = 0; c < reportCols.size(); c++) {
2297                 if(reportCols.get(c)!=null) {
2298                                 DataColumnType dct = (DataColumnType) reportCols.get(c);
2299                                 //Modified since ds is null.
2300                                 DataValue dv = new DataValue();
2301
2302                                         if(ds.getRowCount()>0){
2303                                                 if(ds.getColumnIndex(dct.getColId())!= -1) {
2304                                                 dr.addDataValue(dv);
2305                                                         dv.setDisplayValue(ds.getString(r, dct.getColId()));
2306                                                 } else {
2307                                                         continue;
2308                                                 }
2309                                                 
2310                                         } else {
2311                                                 dv.setDisplayValue("");
2312                                         }
2313                     dv.setColName(dct.getColName());
2314                     dv.setColId(dct.getColId());
2315                     dv.setNowrap(nvl(dct.getNowrap(),"null").equals("false")?"null":nvl(dct.getNowrap(),"null"));
2316                     
2317                     //Add Drilldown URL to dv
2318                                 if (nvl(dct.getDrillDownURL()).length() > 0) {
2319                         
2320                         if(dv.getDisplayValue().length() > 0) {                    
2321                                 dv.setDrillDownURL(reportRuntime.parseDrillDownURL(r, /* c, */ds, dct, request, childReportFormFields));
2322                                 dv.setDrillDowninPoPUp(dct.isDrillinPoPUp()!=null?dct.isDrillinPoPUp():false);
2323                         }
2324                                         
2325                         if (dv.getDisplayValue().length() == 0) {
2326                                                 //dv.setDisplayValue("[NULL]");
2327                             dv.setDisplayValue("");
2328                         }
2329                                 } // if
2330                                 
2331                     StringBuffer indentation = new StringBuffer("");
2332                     if(dct.getIndentation()!=null && dct.getIndentation()>0) {
2333                         for (int indent=0; indent< dct.getIndentation(); indent++) {
2334                                 indentation.append("\t");
2335                         }
2336                         dv.setNowrap("true");
2337                     }
2338                     dv.setIndentation(indentation.toString());
2339                     
2340                     if(dct.isVisible()) {
2341
2342                         dv.setVisible(true);
2343                                         dv.setAlignment(dct.getDisplayAlignment());
2344                             dv.setDisplayTotal(dct.getDisplayTotal());
2345                             dv.setDisplayName(dct.getDisplayName());                    
2346                             
2347 //                                      if (nvl(dct.getDrillDownURL()).length() > 0) {
2348                                 
2349 //                              if(dv.getDisplayValue().length() > 0) { 
2350                                         //TODO: Below Drilldown URL
2351 //                                      dv.setDrillDownURL(reportRuntime.parseDrillDownURL(r, /* c, */ds, dct,request, childReportFormFields));
2352 //                                      dv.setDrillDowninPoPUp(dct.isDrillinPoPUp());
2353 //                              }
2354 //                                              
2355 //                              if (dv.getDisplayValue().length() == 0) {
2356 //                                                      //dv.setDisplayValue("[NULL]");
2357 //                                  dv.setDisplayValue("");
2358 //                              }
2359 //                                      } // if
2360                             
2361                                 } else {
2362                                         dv.setVisible(false);
2363                                         dv.setHidden(true);  
2364                                 }
2365                     //System.out.println("in Linear report b4" + dr.getFormatId() + dr.getBgColorHtml() + dv.getDisplayValue());
2366                     
2367                     if(dr.getFormatId()!=null) 
2368                                  ((FormatProcessor) formatProcessors.get(c)).setHtmlFormatters(dv, dr, true);
2369                     else
2370                                  ((FormatProcessor) formatProcessors.get(c)).setHtmlFormatters(dv, dr, false);
2371
2372                     //System.out.println("in Linear report After" + dr.getFormatId() + dr.getBgColorHtml() + dv.getDisplayValue());
2373                 } // if reportCols
2374                         } // for
2375                         reportDataList.add(dr); 
2376                 } // for
2377
2378                 rd.setReportDataList(reportDataList);
2379                 //Only if rownumber options is needed
2380                 //rd.addRowNumbers(pageNo, getPageSize());
2381                 DataRow colDataTotalsLinear = null;
2382                 if (colDataTotalsLinear == null)
2383                         colDataTotalsLinear = reportRuntime.generateColumnDataTotalsLinear(new ArrayList(reportCols), AppUtils.getUserID(request),
2384                                         reportRuntime.getDbInfo(),request);
2385
2386                 if(colDataTotalsLinear!=null)   
2387                         rd.setColumnDataTotalsLinear(colDataTotalsLinear, "Total");
2388         // Please note the below function doesn't set the visibility for dv since this is set in this function. - Sundar
2389                 rd.applyVisibility();
2390         }
2391                 return rd;
2392         } // loadLinearReportData       
2393         
2394         public String formFieldRun(HttpServletRequest request, String nextPage) {
2395                 ReportRuntime rr = null;
2396                 rr  = (ReportRuntime) request.getSession().getAttribute(AppConstants.SI_REPORT_RUNTIME);
2397                 if(rr!=null) {
2398                         ReportJSONRuntime reportJSONRuntime = rr.createFormFieldJSONRuntime(request);
2399                         ObjectMapper mapper = new ObjectMapper();
2400                                         //mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
2401                                         //mapper.setVisibilityChecker(mapper.getVisibilityChecker().with(JsonAutoDetect.Visibility.NONE));
2402                                         mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
2403                                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2404                                         String jsonInString = "";
2405                                         try {
2406                                                 jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(reportJSONRuntime);
2407                                         } catch (Exception ex) {
2408                                                 ex.printStackTrace();
2409                                                 
2410                                         }
2411                             return jsonInString;
2412                 }
2413
2414                 return "";
2415         }
2416
2417 } // ActionHandler