1cd9b9187383869b5b43eb231e47a0f1e1ebad1d
[portal/sdk.git] /
1 /*
2  * ============LICENSE_START==========================================
3  * ONAP Portal SDK
4  * ===================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
37  */
38 package org.onap.portalsdk.analytics.model.definition;
39
40 import java.io.IOException;
41 import java.io.InputStreamReader;
42 import java.io.Reader;
43 import java.io.Serializable;
44 import java.io.Writer;
45 import java.sql.Connection;
46 import java.sql.PreparedStatement;
47 import java.sql.ResultSet;
48 import java.sql.SQLException;
49 import java.util.ArrayList;
50 import java.util.Collections;
51 import java.util.Iterator;
52 import java.util.List;
53 import java.util.Vector;
54 import java.util.regex.Matcher;
55 import java.util.regex.Pattern;
56
57 import javax.servlet.http.HttpServletRequest;
58
59 import org.onap.portalsdk.analytics.RaptorObject;
60 import org.onap.portalsdk.analytics.error.RaptorException;
61 import org.onap.portalsdk.analytics.error.RaptorRuntimeException;
62 import org.onap.portalsdk.analytics.error.ReportSQLException;
63 import org.onap.portalsdk.analytics.error.UserDefinedException;
64 import org.onap.portalsdk.analytics.model.base.IdNameValue;
65 import org.onap.portalsdk.analytics.model.base.NameComparator;
66 import org.onap.portalsdk.analytics.model.runtime.FormField;
67 import org.onap.portalsdk.analytics.model.runtime.ReportParamValues;
68 import org.onap.portalsdk.analytics.model.runtime.ReportRuntime;
69 import org.onap.portalsdk.analytics.system.AppUtils;
70 import org.onap.portalsdk.analytics.system.ConnectionUtils;
71 import org.onap.portalsdk.analytics.system.DbUtils;
72 import org.onap.portalsdk.analytics.system.Globals;
73 import org.onap.portalsdk.analytics.util.AppConstants;
74 import org.onap.portalsdk.analytics.util.DataSet;
75 import org.onap.portalsdk.analytics.util.Utils;
76 import org.onap.portalsdk.analytics.xmlobj.FormFieldType;
77 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
78 import org.onap.portalsdk.core.util.SecurityCodecUtil;
79 import org.owasp.esapi.ESAPI;
80
81 public class ReportSchedule extends RaptorObject implements Serializable{
82         
83         /**
84          * 
85          */
86         private static final long serialVersionUID = 6936844475227328201L;
87
88         private static transient final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ReportSchedule.class);
89         
90         private String reportID = null;
91
92         private String scheduleUserID = null;
93         
94         private String scheduleID = "";
95         
96         private boolean infoUpdated = false;
97
98         private String schedEnabled = "Y";
99
100         private String startDate = "";
101
102         private String endDate = "";
103
104         private String runDate = "";
105
106         private String runHour = "12";
107
108         private String runMin = "00";
109
110         private String runAMPM = "AM";
111
112         private String endHour = "11";
113
114         private String endMin = "45";
115
116         private String endAMPM = "PM";
117
118         private String recurrence = "";
119
120         private String conditional = "N";
121
122         private String conditionSQL = "";
123         
124         private String notify_type = "1"; //1 -- link, 2 -- pdf,  4 -- excel, 3 -- csv
125         
126         private String encryptMode = "N"; //1 -- link, 2 -- pdf,  4 -- excel, 3 -- csv
127         
128         private String attachment = "Y"; //1 -- link, 2 -- pdf,  4 -- excel, 3 -- csv
129
130         private String downloadLimit = "0";
131         
132         private String formFields = "";
133         
134         private Vector emailToUsers = new Vector();
135
136         private Vector emailToRoles = new Vector();
137
138         public ReportSchedule(String reportID, String scheduleUserID, boolean loadData, HttpServletRequest request) {
139                 super();
140
141                 setReportID(reportID);
142                 setScheduleUserID(scheduleUserID);
143                 if(loadData)
144                         loadScheduleData(request);
145                 else
146                         newScheduleData();
147         } // ReportSchedule
148
149         public ReportSchedule(String reportID, String scheduleID, String scheduleUserID, HttpServletRequest request) {
150                 super();
151
152                 setReportID(reportID);
153                 setScheduleID(scheduleID);
154                 setScheduleUserID(scheduleUserID);
155                 loadScheduleData(request);
156         } // ReportSchedule
157         
158         void setReportID(String reportID) {
159                 this.reportID = reportID;
160         }
161
162         public String getSchedEnabled() {
163                 return schedEnabled;
164         }
165
166         public String getStartDate() {
167                 return startDate;
168         }
169
170         public String getEndDate() {
171                 return endDate;
172         }
173
174         public String getRunDate() {
175                 return runDate;
176         }
177
178         public String getRunHour() {
179                 return runHour;
180         }
181
182         public String getRunMin() {
183                 return runMin;
184         }
185
186         public String getRunAMPM() {
187                 return runAMPM;
188         }
189
190         public String getRecurrence() {
191                 return recurrence;
192         }
193
194         public String getConditional() {
195                 return conditional;
196         }
197
198         public String getConditionSQL() {
199                 return conditionSQL;
200         }
201
202         public List getEmailToUsers() {
203                 return emailToUsers;
204         }
205
206         public List getEmailToRoles() {
207                 return emailToRoles;
208         }
209
210         /**
211          * @return the downloadLimit
212          */
213         public String getDownloadLimit() {
214                 return downloadLimit;
215         }
216
217         /**
218          * @param downloadLimit the downloadLimit to set
219          */
220         public void setDownloadLimit(String downloadLimit) {
221                 if(nvl(downloadLimit).equals(this.downloadLimit))
222                         return;
223                 this.downloadLimit = nvl(downloadLimit,"0");
224                 infoUpdated = true;
225         }
226
227         /**
228          * @return the formFields
229          */
230         public String getFormFields() {
231                 return formFields;
232         }
233
234         /**
235          * @param formFields the formFields to set
236          */
237         public void setFormFields(String formFields) {
238                 if(nvl(formFields).equals(this.formFields))
239                         return;
240                 this.formFields = nvl(formFields);
241                 infoUpdated = true;
242         }
243         
244         public String getNotify_type() {
245                 return notify_type;
246         }
247
248         /**
249          * @param notify_type the notify_type to set
250          * 1 -- link (default), 2 -- pdf,  4 -- excel
251          */
252         public void setNotify_type(String notify_type) {
253                 if(nvl(notify_type).equals(this.notify_type))
254                         return;
255                 this.notify_type = nvl(notify_type,"1");
256                 infoUpdated = true;
257         }
258
259         public void setSchedEnabled(String schedEnabled) {
260                 if (nvl(schedEnabled).equals(this.schedEnabled))
261                         return;
262                 infoUpdated = true;
263                 this.schedEnabled = nvl(schedEnabled, "N");
264         }
265
266         public void setStartDate(String startDate) {
267                 if (nvl(startDate).equals(this.startDate))
268                         return;
269                 infoUpdated = true;
270                 this.startDate = nvl(startDate);
271         }
272
273         public void setEndDate(String endDate) {
274                 if (nvl(endDate).equals(this.endDate))
275                         return;
276                 infoUpdated = true;
277                 this.endDate = nvl(endDate);
278         }
279
280         public void setRunDate(String runDate) {
281                 if (nvl(runDate).equals(this.runDate))
282                         return;
283                 infoUpdated = true;
284                 this.runDate = nvl(runDate);
285         }
286
287         public void setRunHour(String runHour) {
288                 if (nvl(runHour).equals(this.runHour))
289                         return;
290                 infoUpdated = true;
291                 this.runHour = nvl(runHour, "12");
292         }
293
294         public void setRunMin(String runMin) {
295                 if (nvl(runMin).equals(this.runMin))
296                         return;
297                 infoUpdated = true;
298                 this.runMin = nvl(runMin, "00");
299         }
300
301         public void setRunAMPM(String runAMPM) {
302                 if (nvl(runAMPM).equals(this.runAMPM))
303                         return;
304                 infoUpdated = true;
305                 this.runAMPM = nvl(runAMPM, "AM");
306         }
307
308         public void setRecurrence(String recurrence) {
309                 if (nvl(recurrence).equals(this.recurrence))
310                         return;
311                 infoUpdated = true;
312                 this.recurrence = nvl(recurrence);
313         }
314
315         public void setConditional(String conditional) {
316                 if (nvl(conditional).equals(this.conditional))
317                         return;
318                 infoUpdated = true;
319                 this.conditional = nvl(conditional, "N");
320         }
321
322         public void setConditionSQL(String conditionSQL) {
323                 if (nvl(conditionSQL).equals(this.conditionSQL))
324                         return;
325                 infoUpdated = true;
326                 this.conditionSQL = nvl(conditionSQL);
327         }
328
329         public void addEmailToUser(String userId, String userName) {
330                 if (nvl(userId).length() == 0)
331                         return;
332
333                 for (int i = 0; i < emailToUsers.size(); i++) {
334                         IdNameValue selUser = (IdNameValue) emailToUsers.get(i);
335                         if (userId.equals(selUser.getId()))
336                                 return;
337                 } // for
338
339                 emailToUsers.add(new IdNameValue(userId, userName));
340                 Collections.sort(emailToUsers, new NameComparator());
341                 infoUpdated = true;
342         } // addEmailToUser
343         
344         
345         public void addEmailArrayToUser(ArrayList<IdNameValue> allSelectedUsers) {
346                 if (allSelectedUsers==null || allSelectedUsers.size()<=0)
347                         return;
348                 emailToUsers.removeAllElements();
349                 for (int i = 0; i < allSelectedUsers.size(); i++) {
350                         emailToUsers.add(allSelectedUsers.get(i));
351                 }
352                 Collections.sort(emailToUsers, new NameComparator());
353                 infoUpdated = true;
354         } // addEmailArrayToUser
355
356         public void removeEmailToUser(String userId) {
357                 if (nvl(userId).length() == 0)
358                         return;
359
360                 for (int i = 0; i < emailToUsers.size(); i++) {
361                         IdNameValue selUser = (IdNameValue) emailToUsers.get(i);
362                         if (userId.equals(selUser.getId())) {
363                                 infoUpdated = true;
364                                 emailToUsers.remove(i);
365                                 return;
366                         } // if
367                 } // for
368         } // removeEmailToUser
369
370         public void addEmailToRole(String roleId, String roleName) {
371                 if (nvl(roleId).length() == 0)
372                         return;
373
374                 for (int i = 0; i < emailToRoles.size(); i++) {
375                         IdNameValue selRole = (IdNameValue) emailToRoles.get(i);
376                         if (roleId.equals(selRole.getId()))
377                                 return;
378                 } // for
379
380                 emailToRoles.add(new IdNameValue(roleId, roleName));
381                 Collections.sort(emailToRoles, new NameComparator());
382                 infoUpdated = true;
383         } // addEmailToRole
384
385         public void addEmailArrayToRole(ArrayList<IdNameValue> allSelectedRoles) {
386                 if (allSelectedRoles==null || allSelectedRoles.size()<=0)
387                         return;
388                 emailToRoles.removeAllElements();
389                 for (int i = 0; i < allSelectedRoles.size(); i++) {
390                         emailToRoles.add(allSelectedRoles.get(i));
391                 }
392                 Collections.sort(emailToRoles, new NameComparator());
393                 infoUpdated = true;
394         } // addEmailArrayToRole
395
396         public void removeEmailToRole(String roleId) {
397                 if (nvl(roleId).length() == 0)
398                         return;
399
400                 for (int i = 0; i < emailToRoles.size(); i++) {
401                         IdNameValue selRole = (IdNameValue) emailToRoles.get(i);
402                         if (roleId.equals(selRole.getId())) {
403                                 infoUpdated = true;
404                                 emailToRoles.remove(i);
405                                 return;
406                         } // if
407                 } // for
408         } // addEmailToRole
409
410         private void loadScheduleData(HttpServletRequest request) {
411                 try {           
412             StringBuffer query = new StringBuffer("");
413             //query.append("SELECT rs.enabled_yn, TO_CHAR(rs.start_date, 'MM/DD/YYYY') start_date, TO_CHAR(rs.end_date, 'MM/DD/YYYY') end_date, TO_CHAR(rs.run_date, 'MM/DD/YYYY') run_date, NVL(TO_CHAR(rs.run_date, 'HH'), '12') run_hour, NVL(TO_CHAR(rs.run_date, 'MI'), '00') run_min, NVL(TO_CHAR(rs.run_date, 'AM'), 'AM') run_ampm, rs.recurrence, rs.conditional_yn, rs.notify_type, rs.max_row, rs.initial_formfields, rs.schedule_id, NVL(TO_CHAR(rs.end_date, 'HH'), '11') end_hour, NVL(TO_CHAR(rs.end_date, 'MI'), '45') end_min, NVL(TO_CHAR(rs.end_date, 'AM'), 'PM') end_ampm, encrypt_yn, attachment_yn FROM cr_report_schedule rs WHERE rs.rep_id = "
414                         //      + reportID);
415             String q_sql = Globals.getLoadScheduleData();
416             q_sql = q_sql.replace("[reportID]", reportID);
417             query.append(q_sql);
418             
419             if(!AppUtils.isAdminUser(request))
420                 query.append(" and rs.sched_user_id = " + getScheduleUserID());
421             if(nvl(getScheduleID()).length()>0) {
422                         query.append(" and rs.schedule_id = " + getScheduleID());               
423             }
424             query.append(" order by rs.run_date desc ");
425             
426                         DataSet ds = DbUtils
427                                         .executeQuery(query.toString()); 
428
429                         if (ds.getRowCount() > 0) {
430                                 schedEnabled = nvl(ds.getString(0, 0), "N");
431                                 startDate = nvl(ds.getString(0, 1));
432                                 endDate = nvl(ds.getString(0, 2));
433                                 runDate = nvl(ds.getString(0, 3));
434                                 runHour = nvl(ds.getString(0, 4), "12");
435                                 runMin = nvl(ds.getString(0, 5), "00");
436                                 runAMPM = nvl(ds.getString(0, 6), "AM");
437                                 recurrence = nvl(ds.getString(0, 7));
438                                 conditional = nvl(ds.getString(0, 8), "N");
439                                 //conditionSQL = nvl(ds.getString(0, 9));
440                                 notify_type = nvl(ds.getString(0, 9), "1");
441                                 downloadLimit = nvl(ds.getString(0, 10), "1000");
442                                 //if(nvl(ds.getString(0, 13).)
443                                 formFields = nvl(ds.getString(0, 11));
444                                 setScheduleID(ds.getString(0, 12));
445                                 endHour = nvl(ds.getString(0, 13), "11");
446                                 endMin = nvl(ds.getString(0, 14), "45");
447                                 endAMPM = nvl(ds.getString(0, 15), "PM");
448                                 encryptMode = nvl(ds.getString(0, "encrypt_yn"), "N");
449                                 attachment = nvl(ds.getString(0, "attachment_yn"), "Y");
450                                 conditionSQL = loadConditionalSQL(getScheduleID());
451                         } else { // if
452                                 //DataSet dsSeq = DbUtils.executeQuery("select SEQ_CR_REPORT_SCHEDULE.nextval from dual" );
453                                 String n_sql = Globals.getNewScheduleData();
454                                 DataSet dsSeq = DbUtils.executeQuery(n_sql);
455                                 String schedule_id = dsSeq.getString(0,0);
456                                 setScheduleID(schedule_id);
457                         }
458             if(getScheduleID().length() > 0) {
459                                 //ds = DbUtils
460                                 //              .executeQuery("SELECT rsu.user_id, fuser.last_name||', '||fuser.first_name, fuser.login_id FROM cr_report_schedule_users rsu, fn_user fuser WHERE rsu.rep_id = "
461                                 //                              + reportID + " AND rsu.schedule_id = " + getScheduleID() + " and rsu.user_id IS NOT NULL and rsu.user_id = fuser.user_id");
462                                 
463                                 String t_sql = Globals.getLoadScheduleGetId();  
464                                 t_sql = t_sql.replace("[reportID]", reportID);
465                                 t_sql = t_sql.replace("[getScheduleID()]", getScheduleID());
466                                 
467                                 ds = DbUtils.executeQuery(t_sql);
468                                 
469                                         for (int i = 0; i < ds.getRowCount(); i++){
470                                         String nameToDisplay = ds.getString(i, 1);
471                                         if (Globals.getUseLoginIdInSchedYN()!= null && Globals.getUseLoginIdInSchedYN().equals("Y")) {
472                                                 nameToDisplay = ds.getString(i, 2);
473                                         }
474                                         if(nameToDisplay!=null && nameToDisplay.length() > 0)
475                                                 emailToUsers.add(new IdNameValue(ds.getString(i, 0), nameToDisplay));
476                                         else
477                                                 emailToUsers.add(new IdNameValue(ds.getString(i, 0), ds.getString(i, 1)));
478                                 }
479                                 Collections.sort(emailToUsers, new NameComparator());
480         
481                                 //ds = DbUtils
482                                         //      .executeQuery("SELECT rsu.role_id FROM cr_report_schedule_users rsu WHERE rsu.rep_id = "
483                                                 //              + reportID + " AND rsu.schedule_id = " + getScheduleID() + " AND rsu.role_id IS NOT NULL");
484                                 
485                                 String r_sql = Globals.getLoadScheduleUsers();  
486                                 r_sql = r_sql.replace("[reportID]", reportID);
487                                 r_sql = r_sql.replace("[getScheduleID()]", getScheduleID());
488                                 
489                                 ds = DbUtils.executeQuery(r_sql);
490                                 
491                                 for (int i = 0; i < ds.getRowCount(); i++)
492                                         emailToRoles.add(new IdNameValue(ds.getString(i, 0), AppUtils.getRoleName(ds
493                                                         .getString(i, 0))));
494                                 Collections.sort(emailToRoles, new NameComparator());
495         
496                                 infoUpdated = false;
497             }
498                 } catch (Exception e) {
499                         throw new RuntimeException(
500                                         "[ReportSchedule.loadScheduleData] Unable to load Report " + reportID
501                                                         + " schedule. Error: " + e.getMessage());
502                 }
503         } // loadScheduleData
504
505         private void newScheduleData() {
506                 try {           
507                         //DataSet dsSeq = DbUtils.executeQuery("select SEQ_CR_REPORT_SCHEDULE.nextval from dual" );
508                         String sql = Globals.getNewScheduleData();
509                         DataSet dsSeq = DbUtils.executeQuery(sql);
510                                         
511                         String schedule_id = dsSeq.getString(0,0);
512                         setScheduleID(schedule_id);
513                 } catch (Exception e) {
514                         throw new RuntimeException(
515                                         "[ReportSchedule.newScheduleData] Unable to load Report " + reportID
516                                                         + " schedule. Error: " + e.getMessage());
517                 }
518         } // newScheduleData
519
520         private String parseScheduleSQL(HttpServletRequest request, String sql) throws RaptorException {
521         DataSet ds = null;
522         
523         logger.debug(EELFLoggerDelegate.debugLogger, (sql));
524         String[] reqParameters = Globals.getRequestParams().split(",");
525         String[] sessionParameters = Globals.getSessionParams().split(",");
526         String[] scheduleSessionParameters = Globals.getSessionParamsForScheduling().split(",");
527         javax.servlet.http.HttpSession session = request.getSession();
528         ReportRuntime rr = (ReportRuntime) session.getAttribute(AppConstants.SI_REPORT_RUNTIME);
529         String userId = AppUtils.getUserID(request);
530         String dbType = "";
531         String dbInfo = rr.getDBInfo();
532         ReportParamValues paramValues = rr.getReportParamValues();
533                 int fieldCount = 0;
534         // For Daytona removing all formfields which has null param value
535         Pattern re1 = null;
536         Matcher matcher = null;
537         int index = 0;
538         int posFormField = 0;
539         int posAnd = 0;
540                 if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) {
541                         try {
542                          org.onap.portalsdk.analytics.util.RemDbInfo remDbInfo = new org.onap.portalsdk.analytics.util.RemDbInfo();
543                          dbType = remDbInfo.getDBType(dbInfo);  
544                         } catch (Exception ex) {
545                            throw new RaptorException(ex);                       
546                                 }
547                 }
548
549                 sql = sql + " ";
550                 sql = Pattern.compile("(^[\r\n]*|([\\s]))[Ss][Ee][Ll][Ee][Cc][Tt]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" SELECT ");
551                 sql = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Rr][Ee]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" WHERE ");
552                 sql = Pattern.compile("(^[\r\n]*|([\\s]))[Aa][Nn][Dd]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" AND ");
553                 
554                 if (rr.getFormFieldList() != null) {
555                         for (Iterator iter = rr.getFormFieldList().getFormField().iterator(); iter.hasNext();) {
556                                 
557                                 FormFieldType fft = (FormFieldType) iter.next();
558                                 String fieldId = fft.getFieldId();
559                                 String fieldDisplay = rr.getFormFieldDisplayName(fft);
560                                 if(!fft.getFieldType().equals(FormField.FFT_BLANK)) {
561                                 if (paramValues.isParameterMultiValue(fieldId)) {
562                                         String replaceValue = rr.formatListValue(fieldDisplay, nvl(paramValues.getParamValue(fieldId)), null, false,
563                                                         true, null, paramValues.getParamBaseSQL(fieldId));
564                                         if(replaceValue.length() > 0) {
565                                                 sql = Utils.replaceInString(sql, fieldDisplay, replaceValue);
566                                         } else {
567                                                 fieldCount++;
568                                                 if(fieldCount == 1) {
569                                                         //sql = sql + " ";
570                                                         //sql = Pattern.compile("(^[\r\n]*|([\\s]))[Ss][Ee][Ll][Ee][Cc][Tt]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" SELECT ");
571                                                         //sql = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Rr][Ee]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" WHERE ");
572                                                         //sql = Pattern.compile("(^[\r\n]*|([\\s]))[Aa][Nn][Dd]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" AND ");
573                                                 }
574                                                 //sql = getReportSQL();
575                                                 while(sql.indexOf(fieldDisplay) > 0) {
576 /*                                              sql = Utils.replaceInString(sql, "SELECT ", "select ");
577                                                 sql = Utils.replaceInString(sql, "WHERE", "where");
578                                                 sql = Utils.replaceInString(sql, " AND ", " and ");
579 */                                              
580                                         re1 = Pattern.compile("(^[\r\n]|[\\s])AND(.*?[^\r\n]*)"+ "\\["+fft.getFieldName()+ "\\](.*?)\\s", Pattern.DOTALL);
581                                                 //re1 = Pattern.compile("(^[\r\n]|[\\s])AND(.*?[^\r\n]*)"+ "\\["+fft.getFieldName()+ "\\]", Pattern.DOTALL);
582 /*                              posFormField = sql.indexOf(fieldDisplay);
583                                 posAnd = sql.lastIndexOf("and", posFormField);                                          
584                                 if(posAnd < 0) posAnd = 0;
585                                 else if (posAnd > 2) posAnd = posAnd - 2;
586                                         matcher = re1.matcher(sql);
587 */
588                                         posFormField = sql.indexOf(fieldDisplay);
589                                         int posSelectField = sql.lastIndexOf("SELECT ", posFormField);
590                                         int whereField = sql.indexOf(" WHERE" , posSelectField);
591                                         int andField = 0;
592                                         if(posFormField > whereField) 
593                                                 andField = sql.lastIndexOf(" AND ", posFormField);
594                                         if (posFormField > andField && andField > whereField)
595                                                 posAnd = andField;
596                                         else
597                                                 posAnd = 0;
598                                         matcher = re1.matcher(sql);
599                                         
600                                         
601                                         if (posAnd > 0 && matcher.find(posAnd-1)) { 
602                                                         //sql = Utils.replaceInString(sql, matcher.group(), " ");
603                                                         matcher = re1.matcher(sql);
604                                                         index = sql!=null?sql.lastIndexOf("["+fft.getFieldName()+"]"):-1;
605                                                         
606                                                         if(andField>0) 
607                                                                 index = andField;
608                                                         else
609                                                                 index = whereField;
610                                                         if(index >= 0 && matcher.find(index-1)) {
611                                                                 sql = sql.replace(matcher.group(), " ");
612                                                         } 
613                                         } else {
614                                                 
615                                                 //sql = sql.replace
616                                                 re1 = Pattern.compile("(^[\r\n]|[\\s])WHERE(.*?[^\r\n]*)\\["+fft.getFieldName()+ "\\](.*?)\\s", Pattern.DOTALL);
617                                                 matcher = re1.matcher(sql);
618                                                 if(matcher.find(whereField-1)) {
619                                                         matcher = re1.matcher(sql);
620                                                         index = sql!=null?sql.lastIndexOf("["+fft.getFieldName()+"]"):-1;
621                                                         if(index >= 0 && matcher.find(index-30)) {
622                                                                 sql = sql.replace(matcher.group(), " WHERE 1=1 ");
623                                                 }                                                       
624                                                         //sql = Utils.replaceInString(sql, matcher.group(), " where 1=1 ");
625                                                 } /*else {
626                                                         replaceValue = formatListValue("", Utils
627                                                                         .oracleSafe(nvl(paramValues.getParamValue(fieldId))), null, false,
628                                                                         true, null, paramValues.getParamBaseSQL(fieldId));
629                                                         sql = Utils.replaceInString(sql, fieldDisplay, replaceValue);
630                                                 }*/
631
632                                         }
633                                                 }
634                                         }
635                                         
636                                 //sql = Utils.replaceInString(sql, " select ", " SELECT ");
637                                 //sql = Utils.replaceInString(sql, " where ", " WHERE ");
638                                 //sql = Utils.replaceInString(sql, " and ", " AND ");
639
640                                 } else {
641                                         String paramValue = "";
642                                         if(paramValues.isParameterTextAreaValueAndModified(fieldId)) {
643                                                 String value = "";
644                                                 value = nvl(paramValues
645                                                                 .getParamValue(fieldId));
646 //                                              value = Utils.oracleSafe(nvl(value));
647 //                                              if (!(dbType.equals("DAYTONA") && sql.trim().toUpperCase().startsWith("SELECT"))) { 
648 //                                                      value = "('" + Utils.replaceInString(value, ",", "'|'") + "')";
649 //                                                      value = Utils.replaceInString(value, "|", ",");
650 //                                                      paramValue = XSSFilter.filterRequestOnlyScript(value);
651 //                                              } else if (nvl(value.trim()).length()>0) {
652 //                                                      value = "('" + Utils.replaceInString(value, ",", "'|'") + "')";
653 //                                                      value = Utils.replaceInString(value, "|", ",");
654 //                                                      paramValue = XSSFilter.filterRequestOnlyScript(value);
655 //                                              }
656                                                 paramValue = value;
657                                         } else 
658                                                 paramValue = nvl(paramValues
659                                                                 .getParamValue(fieldId));
660
661                                         if (paramValue!=null && paramValue.length() > 0) {
662                         if(paramValue.toLowerCase().trim().startsWith("select ")) {
663                             paramValue = Utils.replaceInString(paramValue, "[LOGGED_USERID]", ESAPI.encoder().encodeForSQL( SecurityCodecUtil.getCodec(),userId));
664                             paramValue = Utils.replaceInString(paramValue, "[USERID]", ESAPI.encoder().encodeForSQL( SecurityCodecUtil.getCodec(),userId));
665                             paramValue = Utils.replaceInString(paramValue, "[USER_ID]", ESAPI.encoder().encodeForSQL( SecurityCodecUtil.getCodec(),userId));
666                             
667                             paramValue = Utils.replaceInString(paramValue, "''", "'");
668                             ds = ConnectionUtils.getDataSet(paramValue, dbInfo);
669                             if (ds.getRowCount() > 0) paramValue = ds.getString(0, 0);
670                         }
671                         logger.debug(EELFLoggerDelegate.debugLogger, ("SQLSQLBASED B4^^^^^^^^^ " + sql + " " + fft.getValidationType() + " " + fft.getFieldName() + " " + fft.getFieldId()));
672                         if(fft!=null && (fft.getValidationType()!=null && (fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR) || fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN) ||fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC) ||fft.getValidationType().equals(FormField.VT_DATE) ))) {
673                                 //System.out.println("paramValues.getParamValue(fieldId_Hr) Inside if " + fft.getValidationType()  + " " + fieldDisplay);
674                                 if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)) {
675                                             sql = Utils.replaceInString(sql, fieldDisplay, nvl(
676                                                     paramValue) +((nvl(paramValues
677                                                                                         .getParamValue(fieldId+"_Hr") ).length()>0)?" "+addZero(nvl(paramValues
678                                                                                                         .getParamValue(fieldId+"_Hr")  ) ):""));
679                                         }
680                                         else if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)) {
681 /*                                              System.out.println("paramValues.getParamValue(fieldId_Hr)" + paramValues
682                                                                                 .getParamValue(fieldId+"_Hr") + " " + paramValues
683                                                                                 .getParamValue(fieldId+"_Min")) ;
684 */                                                  sql = Utils.replaceInString(sql, fieldDisplay, nvl(
685                                                             paramValue) + ((nvl(paramValues
686                                                                                                 .getParamValue(fieldId+"_Hr") ).length()>0)?" "+addZero(nvl(paramValues
687                                                                                                 .getParamValue(fieldId+"_Hr") )  ):"") + ((nvl(paramValues
688                                                                                                                 .getParamValue(fieldId+"_Min") ).length()>0)?":" + addZero(nvl(paramValues
689                                                                                                                 .getParamValue(fieldId+"_Min") ) ) : "")                )  ;
690                                         }
691                                         else if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
692                                                     sql = Utils.replaceInString(sql, fieldDisplay, nvl(
693                                                             paramValue) + ((nvl(paramValues
694                                                                                                 .getParamValue(fieldId+"_Hr") ).length()>0)?" "+addZero(nvl(paramValues
695                                                                                                                 .getParamValue(fieldId+"_Hr")  ) ):"") + ((nvl(paramValues
696                                                                                                                                 .getParamValue(fieldId+"_Min") ).length()>0)?":" + addZero(nvl(paramValues
697                                                                                                                                 .getParamValue(fieldId+"_Min")  ) ) : "")                + ((nvl(paramValues
698                                                                                                                                 .getParamValue(fieldId+"_Sec") ).length()>0)?":"+addZero(nvl(paramValues
699                                                                                                                                 .getParamValue(fieldId+"_Sec") ) ) : ""                 ) ) ;
700                                         } else {
701                                                         sql = Utils.replaceInString(sql, fieldDisplay, nvl(
702                                                                 paramValue, "NULL"));                                           
703                                         }
704                                         
705
706                         } else {
707                         if(paramValue!=null && paramValue.length() > 0) {
708                                 if(sql.indexOf("'"+fieldDisplay+"'")!=-1 || sql.indexOf("'"+fieldDisplay)!=-1 || sql.indexOf(fieldDisplay+"'")!=-1 
709                                                 || sql.indexOf("'%"+fieldDisplay+"%'")!=-1 || sql.indexOf("'%"+fieldDisplay)!=-1 || sql.indexOf(fieldDisplay+"%'")!=-1 
710                                                 || sql.indexOf("'_"+fieldDisplay+"_'")!=-1 || sql.indexOf("'_"+fieldDisplay)!=-1 || sql.indexOf(fieldDisplay+"_'")!=-1 
711                                         || sql.indexOf("'%_"+fieldDisplay+"_%'")!=-1 || sql.indexOf("^"+fieldDisplay+"^")!=-1 || sql.indexOf("'%_"+fieldDisplay)!=-1 || sql.indexOf(fieldDisplay+"_%'")!=-1) {
712                                           sql = Utils.replaceInString(sql, fieldDisplay, nvl(
713                                                 paramValue, "NULL"));
714                                 } else {
715                                         if(sql.indexOf(fieldDisplay)!=-1) {
716                                                 if(nvl(paramValue).length()>0) {
717                                                         try {
718                                                                 double vD = Double.parseDouble(paramValue);
719                                                                 sql = Utils.replaceInString(sql, fieldDisplay, nvl(
720                                                                 paramValue, "NULL"));
721                                                                 
722                                                         } catch (NumberFormatException ex) {
723                                                                  if (/*dbType.equals("DAYTONA") &&*/ sql.trim().toUpperCase().startsWith("SELECT")) {
724                                                                                 sql = Utils.replaceInString(sql, fieldDisplay, nvl(
725                                                                                         paramValue, "NULL"));
726                                                                  } else
727                                                                     throw new UserDefinedException("Expected number, Given String for the form field \"" + fieldDisplay+"\"");
728                                                         }
729                                                         /*sql = Utils.replaceInString(sql, fieldDisplay, nvl(
730                                                                 paramValue, "NULL"));*/
731                                                 } else
732                                                         sql = Utils.replaceInString(sql, fieldDisplay, nvl(
733                                                                 paramValue, "NULL"));
734
735                                         }
736                                 }
737                         }
738                         else {
739                                  if (dbType.equals("DAYTONA") && sql.trim().toUpperCase().startsWith("SELECT")) {
740                                         sql = sql + " ";
741                                         re1 = Pattern.compile("(^[\r\n]|[\\s]|[^0-9a-zA-Z])AND(.*?[^\r\n]*)"+ "\\["+fft.getFieldName()+ "\\](.*?)\\s", Pattern.DOTALL);
742                                 posFormField = sql.indexOf(fieldDisplay);
743                                 posAnd = sql.lastIndexOf(" AND ", posFormField);                                                
744                                 if(posAnd < 0) posAnd = 0;
745                                 else if (posAnd > 2) posAnd = posAnd - 2;
746                                         matcher = re1.matcher(sql);
747                                         if (matcher.find(posAnd)) {
748                                                 sql = sql.replace(matcher.group(), "");
749                                         }
750                                  } else {
751                                 sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl(
752                                     paramValue, "NULL"));
753                             sql = Utils.replaceInString(sql,  fieldDisplay, nvl(
754                                     paramValue, "NULL"));
755                                  }
756                         }
757                        }
758                             
759                    }
760                                         
761                                  if (dbType.equals("DAYTONA") && sql.trim().toUpperCase().startsWith("SELECT")) {
762                                         sql = sql + " ";
763                                         re1 = Pattern.compile("(^[\r\n]|[\\s]|[^0-9a-zA-Z])AND(.*?[^\r\n]*)"+ "\\["+fft.getFieldName()+ "\\](.*?)\\s", Pattern.DOTALL); //+[\'\\)|\'|\\s]
764                                 posFormField = sql.indexOf(fieldDisplay);
765                                 posAnd = sql.lastIndexOf(" AND ", posFormField);
766                                 if(posAnd < 0) posAnd = 0;
767                                 else if (posAnd > 2) posAnd = posAnd - 2;
768                                         matcher = re1.matcher(sql);
769                                         if (matcher.find(posAnd)) {
770                                                 sql = sql.replace(matcher.group(), " ");
771                                         }
772                                  } else {                                       
773                                         
774                                         logger.debug(EELFLoggerDelegate.debugLogger, ("ParamValue |" + paramValue + "| Sql |" + sql  + "| Multi Value |" + paramValues.isParameterMultiValue(fieldId)));
775                                         sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl(
776                             paramValue, "NULL"));
777                     sql = Utils.replaceInString(sql,  fieldDisplay , nvl(
778                             paramValue, "NULL"));
779                     logger.debug(EELFLoggerDelegate.debugLogger, ("SQLSQLBASED AFTER^^^^^^^^^ " + sql));
780                                  }
781
782                                 } // else
783                                 } // if BLANK   
784                         } // for
785             if(request != null ) {
786                 for (int i = 0; i < reqParameters.length; i++) {
787                     if(!reqParameters[i].startsWith("ff")) {
788                         if (nvl(request.getParameter(reqParameters[i].toUpperCase())).length() > 0)
789                                 sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i].toUpperCase()) );
790                     }
791                     else
792                       sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) );   
793                 }
794                 
795                 for (int i = 0; i < scheduleSessionParameters.length; i++) {
796                         if(nvl(request.getParameter(scheduleSessionParameters[i])).trim().length()>0 )
797                                 sql = Utils.replaceInString(sql, "[" + scheduleSessionParameters[i].toUpperCase()+"]", request.getParameter(scheduleSessionParameters[i]) );
798                                 }
799              }
800             if(session != null ) {
801                 for (int i = 0; i < sessionParameters.length; i++) {
802                     //if(!sessionParameters[i].startsWith("ff"))
803                      // paramValue = Utils.replaceInString(paramValue, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i].toUpperCase()) );
804                    // else {
805                       logger.debug(EELFLoggerDelegate.debugLogger, (" Session " + " sessionParameters[i] " + sessionParameters[i] + " " + (String)session.getAttribute(sessionParameters[i])));
806                       sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) );
807                     //}
808                 }
809              }                  
810                 } else {
811         logger.debug(EELFLoggerDelegate.debugLogger, ("BEFORE LOGGED USERID REPLACE " + sql));
812         //sql = Utils.replaceInString(sql, "'[logged_userId]'", "'"+userId+"'");
813         //debugLogger.debug("Replacing string 2 " + sql);
814         sql = Utils.replaceInString(sql, "[LOGGED_USERID]", userId);
815         sql = Utils.replaceInString(sql, "[USERID]", userId);
816         sql = Utils.replaceInString(sql, "[USER_ID]", userId);
817         logger.debug(EELFLoggerDelegate.debugLogger, ("AFTER LOGGED USERID REPLACE " + sql));
818         // Added for Simon's GM Project where they need to get page_id in their query
819         logger.debug(EELFLoggerDelegate.debugLogger, ("SQLSQLBASED no formfields " + sql));
820         if(request != null ) {
821            for (int i = 0; i < reqParameters.length; i++) {
822              sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) );
823            }
824         }
825         if(session != null ) {
826             for (int i = 0; i < sessionParameters.length; i++) {
827                 logger.debug(EELFLoggerDelegate.debugLogger, (" Session " + " sessionParameters[i] " + sessionParameters[i] + " " + (String)session.getAttribute(sessionParameters[i])));
828                 sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) );
829             }
830          }      
831                 }
832                 // if it is not multiple select and ParamValue is empty this is the place it can be replaced.
833                 sql = Utils.replaceInString(sql, "[LOGGED_USERID]", userId);
834                 sql = Utils.replaceInString(sql, "[USERID]", userId);
835                 sql = Utils.replaceInString(sql, "[USER_ID]", userId);
836         logger.debug(EELFLoggerDelegate.debugLogger, ("SQLSQLBASED no formfields after"  + sql));
837         //debugLogger.debug("Replacing String 2 "+ sql);
838         //debugLogger.debug("Replaced String " + sql);
839         
840                 sql = Pattern.compile("([\n][\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" ");
841                 return sql;
842                 
843         }
844         public void persistScheduleData(Connection conn, HttpServletRequest request) throws RaptorException {
845                 if (!infoUpdated)
846                         return;
847                 if (reportID.equals("-1"))
848                         return;
849        
850                 
851                 try {
852                 String sched_id = "";
853                         StringBuffer query = new StringBuffer("");
854                         query.append(" SELECT 1 FROM cr_report_schedule WHERE rep_id = " + reportID +  " and schedule_id = " + getScheduleID());
855                         if(!AppUtils.isAdminUser(request))
856                                 query.append(" and sched_user_id = " + getScheduleUserID());
857                         DataSet ds = DbUtils.executeQuery(conn, query.toString());
858                         if (ds.getRowCount() > 0) {
859                                 StringBuffer sb = new StringBuffer();
860                                 sb.append("UPDATE cr_report_schedule SET enabled_yn = '");
861                                 sb.append(getSchedEnabled());
862                                 sb.append("', start_date = ");
863                                 if (getStartDate().length() > 0) {
864                                         sb.append("TO_DATE('");
865                                         sb.append(getStartDate());
866                                         sb.append("', 'MM/DD/YYYY')");
867                                 } else
868                                         sb.append("NULL");
869                                 sb.append(", end_date = ");
870                                 if (getEndDate().length() > 0) {
871                                         sb.append("TO_DATE('");
872                                         sb.append(getEndDate());
873                                         sb.append(" ");
874                                         sb.append(getEndHour());
875                                         sb.append(":");
876                                         sb.append(getEndMin());
877                                         sb.append(" ");
878                                         sb.append(getEndAMPM());
879                                         sb.append("', 'MM/DD/YYYY HH:MI AM')");
880                                 } else
881                                         sb.append("NULL");
882                                 sb.append(", run_date = ");
883                                 if (getRunDate().length() > 0) {
884                                         sb.append("TO_DATE('");
885                                         sb.append(getRunDate());
886                                         sb.append(" ");
887                                         sb.append(getRunHour());
888                                         sb.append(":");
889                                         sb.append(getRunMin());
890                                         sb.append(" ");
891                                         sb.append(getRunAMPM());
892                                         sb.append("', 'MM/DD/YYYY HH:MI AM')");
893                                 } else
894                                         sb.append("NULL");
895                                 sb.append(", recurrence = ");
896                                 if (getRecurrence().length() > 0) {
897                                         sb.append("'");
898                                         sb.append(getRecurrence());
899                                         sb.append("'");
900                                 } else
901                                         sb.append("NULL");
902                                 sb.append(", conditional_yn = '");
903                                 sb.append(getConditional());
904                                 //sb.append("', condition_sql = ");
905                                         sb.append("'");
906 /*                              if (getConditionSQL().length() > 0) {
907                                         sb.append("'");
908                                         sb.append(parseScheduleSQL(request, Utils.oracleSafe(getConditionSQL())));
909                                         sb.append("'");
910                                 } else
911                                         sb.append("NULL");
912 */
913                                 sb.append(", notify_type = ");
914                                 sb.append(getNotify_type());                            
915                                 sb.append(", encrypt_yn = '");
916                                 sb.append(getEncryptMode()+"'");                                
917                                 sb.append(", attachment_yn = '");
918                                 sb.append(getAttachmentMode()+"'");                             
919                                 sb.append(", max_row = ");
920                                 sb.append(getDownloadLimit());                          
921                                 sb.append(", initial_formFields = '");
922                                 sb.append(getFormFields()+"'");
923                                 sb.append(", processed_formfields = ''");
924                                 sb.append(" WHERE rep_id = ");
925                                 sb.append(reportID + " and sched_user_id = ");
926                                 sb.append(getScheduleUserID());
927                                 sb.append(" and schedule_id = ");
928                                 sb.append(getScheduleID());                             
929                                 
930                                 DbUtils.executeUpdate(conn, sb.toString());
931                         } else {
932                                 //DataSet dsSeq = DbUtils.executeQuery("select seq_cr_report_schedule.nextval from dual " );
933                                 String w_sql = Globals.getNewScheduleData();
934                                 DataSet dsSeq = DbUtils.executeQuery(w_sql);
935                                 String schedule_id = dsSeq.getString(0,0);
936                                 setScheduleID(schedule_id);
937                                 StringBuffer sb = new StringBuffer();
938                                 sb.append("INSERT INTO cr_report_schedule (schedule_id, sched_user_id, rep_id, enabled_yn, start_date, end_date, run_date, recurrence, conditional_yn, notify_type, max_row, initial_formfields, encrypt_yn, attachment_yn) VALUES(");
939                                 sb.append(getScheduleID() + ", ");
940                                 sb.append(getScheduleUserID() + ", ");
941                                 sb.append(reportID);
942                                 sb.append(", '");
943                                 sb.append(getSchedEnabled());
944                                 sb.append("', ");
945                                 if (getStartDate().length() > 0) {
946                                         sb.append("TO_DATE('");
947                                         sb.append(getStartDate());
948                                         sb.append("', 'MM/DD/YYYY')");
949                                 } else
950                                         sb.append("NULL");
951                                 sb.append(", ");
952                                 if (getEndDate().length() > 0) {
953                                         sb.append("TO_DATE('");
954                                         sb.append(getEndDate());
955                                         sb.append(" ");
956                                         sb.append(getEndHour());
957                                         sb.append(":");
958                                         sb.append(getEndMin());
959                                         sb.append(" ");
960                                         sb.append(getEndAMPM());
961                                         sb.append("', 'MM/DD/YYYY HH:MI AM')");
962                                 } else
963                                         sb.append("NULL");
964                                 sb.append(", ");
965                                 if (getRunDate().length() > 0) {
966                                         sb.append("TO_DATE('");
967                                         sb.append(getRunDate());
968                                         sb.append(" ");
969                                         sb.append(getRunHour());
970                                         sb.append(":");
971                                         sb.append(getRunMin());
972                                         sb.append(" ");
973                                         sb.append(getRunAMPM());
974                                         sb.append("', 'MM/DD/YYYY HH:MI AM')");
975                                 } else
976                                         sb.append("NULL");
977                                 sb.append(", ");
978                                 if (getRecurrence().length() > 0) {
979                                         sb.append("'");
980                                         sb.append(getRecurrence());
981                                         sb.append("'");
982                                 } else
983                                         sb.append("NULL");
984                                 sb.append(", '");
985                                 sb.append(getConditional());
986                                 sb.append("', ");
987 /*                              if (getConditionSQL().length() > 0) {
988                                         sb.append("'");
989                                         sb.append(parseScheduleSQL(request, Utils.oracleSafe(getConditionSQL())));
990                                         sb.append("'");
991                                 } else
992                                         sb.append("NULL");
993                                 sb.append(", ");
994 */
995                                 sb.append(getNotify_type());
996                                 sb.append(", ");
997                                 sb.append(getDownloadLimit());
998                                 sb.append(", '");
999                                 sb.append(getFormFields()+"'");
1000                                 sb.append(",'");
1001                                 sb.append(getEncryptMode()+"'");                                
1002                                 sb.append(",'");
1003                                 sb.append(getAttachmentMode()+"'");                             
1004                                 sb.append(")");                         
1005                                 DbUtils.executeUpdate(conn, sb.toString());
1006                                 
1007                         } // else
1008
1009                         
1010                         //DbUtils.executeUpdate(conn,
1011                                 //      "DELETE cr_report_schedule_users WHERE rep_id = " + reportID+ " and schedule_id = " + getScheduleID());
1012                         
1013                         String d_sql = Globals.getExecuteUpdate();
1014                         d_sql = d_sql.replace("[reportID]", reportID);
1015                         d_sql = d_sql.replace("[getScheduleID()]", getScheduleID());
1016                         
1017                         DbUtils.executeUpdate(conn, d_sql);
1018                         
1019                         for (int i = 0; i < emailToUsers.size(); i++){
1020                                 //DbUtils.executeUpdate(conn,
1021                                         //      "INSERT INTO cr_report_schedule_users (schedule_id, rep_id, user_id, role_id, order_no) VALUES("
1022                                         //              + getScheduleID() + ", "
1023                                         //                      + reportID + ", "
1024                                         //                      + ((IdNameValue) emailToUsers.get(i)).getId() + ", NULL, "
1025                                         //                      + (i + 1) + ")");
1026                                 
1027                                 String sql = Globals.getExecuteUpdateUsers();
1028                                 sql = sql.replace("[getScheduleID()]", getScheduleID());
1029                                 sql = sql.replace("[reportID]", reportID);
1030                                 sql = sql.replace("[emailToUsers.get(i)).getId()]", ((IdNameValue) emailToUsers.get(i)).getId()); 
1031                                 sql = sql.replace("[(i + 1)]", String.valueOf(i + 1));
1032                                 DbUtils.executeUpdate(conn, sql);
1033                                                                 
1034                         }
1035                         for (int i = 0; i < emailToRoles.size(); i++){
1036                                 //DbUtils.executeUpdate(conn,
1037                                 //              "INSERT INTO cr_report_schedule_users (schedule_id, rep_id, user_id, role_id, order_no) VALUES("
1038                                 //                              + getScheduleID() +", " 
1039                                 //                              + reportID + ", NULL, "
1040                                 //                              + ((IdNameValue) emailToRoles.get(i)).getId() + ", "
1041                                 //                              + (emailToUsers.size() + i + 1) + ")");
1042                                 
1043                                 String sql = Globals.getExecuteUpdateRoles();
1044                                 sql = sql.replace("[getScheduleID()]", getScheduleID());
1045                                 sql = sql.replace("[reportID]", reportID);
1046                                 sql = sql.replace("[emailToRoles.get(i)).getId()]", ((IdNameValue) emailToRoles.get(i)).getId()); 
1047                                 sql = sql.replace("[((emailToUsers.size() + i + 1)]", String.valueOf(emailToUsers.size() + i + 1));
1048                                 
1049                                 DbUtils.executeUpdate(conn, sql);
1050                         }
1051                         //if (conn == null)
1052                                 DbUtils.commitTransaction(conn);
1053
1054                         persistConditionSql(conn, getScheduleID(), parseScheduleSQL(request, getConditionSQL()));
1055                         
1056                         
1057                         logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] DB update report " + reportID + " - schedule data updated"));
1058                         //DbUtils.executeUpdate(conn,
1059                         //              "INSERT into cr_schedule_activity_log (schedule_id, notes, run_time) values ("+getScheduleID()+",'Submitted:Schedule',TO_DATE('"+ getRunDate()+" "+ getRunHour()+":"+getRunMin()+" "+getRunAMPM()+"', 'MM/DD/YYYY HH:MI AM'))");
1060                         String e_sql = Globals.getExecuteUpdateActivity();
1061                         e_sql = e_sql.replace("[getScheduleID()]", getScheduleID());
1062                         e_sql = e_sql.replace("[getRunDate()]", getRunDate());
1063                         e_sql = e_sql.replace("[getRunHour()]", getRunHour());
1064                         e_sql = e_sql.replace("[getRunMin()]", getRunMin());    
1065                         e_sql = e_sql.replace("[getRunAMPM()]", getRunAMPM());  
1066                                         
1067                         DbUtils.executeUpdate(conn, e_sql);     
1068                                         
1069                         infoUpdated = false;
1070                         
1071                 } catch (RaptorException e) {
1072                         if (conn != null)
1073                                 DbUtils.rollbackTransaction(conn);
1074                         throw e;
1075                 } // catch
1076             
1077         } // persistScheduleData
1078
1079         //deleting the schedule - Start
1080         public void deleteScheduleData(Connection conn) throws RaptorException {
1081                 if (reportID.equals("-1"))
1082                         return;
1083
1084                 Connection connection = (conn != null) ? conn : DbUtils.startTransaction();
1085                 String sched_id = "";
1086                 try {
1087                         //DataSet ds = DbUtils.executeQuery(connection,
1088                         //              "SELECT 1 FROM cr_report_schedule WHERE rep_id = " + reportID +" and sched_user_id = " + getScheduleUserID() + " and schedule_id = " + getScheduleID());
1089                         String a_sql = Globals.getDeleteScheduleData();
1090                         a_sql = a_sql.replace("[reportID]", reportID);
1091                         a_sql = a_sql.replace("[getScheduleUserID()]", getScheduleUserID());
1092                         a_sql = a_sql.replace("[getScheduleID()]", getScheduleID());
1093                         DataSet ds = DbUtils.executeQuery(connection, a_sql);
1094                         
1095                         if (ds.getRowCount() > 0) {
1096                                 //DbUtils.executeUpdate(connection,
1097                                 //              "DELETE cr_report_schedule_users WHERE rep_id = " + reportID+ " and schedule_id = " + getScheduleID());
1098                                 String b_sql = Globals.getDeleteScheduleDataUsers();
1099                                 b_sql = b_sql.replace("[reportID]", reportID);
1100                                 b_sql = b_sql.replace("[getScheduleID()]", getScheduleID());
1101                                                 
1102                                 DbUtils.executeUpdate(connection, b_sql);
1103                                                                 
1104                                 StringBuffer sb = new StringBuffer();
1105                                 String c_sql = Globals.getDeleteScheduleDataId();
1106                                 c_sql = c_sql.replace("[reportID]", reportID);
1107                                 c_sql = c_sql.replace("[getScheduleUserID()]", getScheduleUserID());
1108                                 c_sql = c_sql.replace("[getScheduleID()]", getScheduleID());
1109                                 
1110                                 sb.append(c_sql);
1111                                 //sb.append("DELETE FROM cr_report_schedule where rep_id = " + reportID +" and sched_user_id = " + getScheduleUserID() + " and schedule_id = " + getScheduleID());
1112                                 
1113                                 DbUtils.executeUpdate(connection, sb.toString());
1114                         }
1115                         if (conn == null)
1116                                 DbUtils.commitTransaction(connection);
1117
1118                         logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] DB update report " + reportID + " - schedule data deleted"));
1119                 } catch (RaptorException e) {
1120                         if (conn == null)
1121                                 DbUtils.rollbackTransaction(connection);
1122                         throw e;
1123                 } // catch
1124         finally {
1125             if (conn == null)
1126             DbUtils.clearConnection(connection);
1127         }
1128         }       //deleteScheduleData
1129         
1130         public String getScheduleUserID() {
1131                 return scheduleUserID;
1132         }
1133
1134         public void setScheduleUserID(String scheduleUserID) {
1135                 this.scheduleUserID = scheduleUserID;
1136         }
1137
1138         public String getScheduleID() {
1139                 return nvl(scheduleID);
1140         }
1141
1142         public void setScheduleID(String scheduleID) {
1143                 this.scheduleID = scheduleID;
1144         }
1145
1146         public String getEndAMPM() {
1147                 return endAMPM;
1148         }
1149
1150         public void setEndAMPM(String endAMPM) {
1151                 if (nvl(endAMPM).equals(this.endAMPM))
1152                         return;
1153                 infoUpdated = true;
1154                 this.endAMPM = nvl(endAMPM, "PM");
1155         }
1156
1157         public String getEndHour() {
1158                 return endHour;
1159         }
1160
1161         public void setEndHour(String endHour) {
1162                 if (nvl(endHour).equals(this.endHour))
1163                         return;
1164                 infoUpdated = true;
1165                 this.endHour = nvl(endHour, "11");
1166         }
1167
1168         public String getEndMin() {
1169                 return endMin;
1170         }
1171
1172         public void setEndMin(String endMin) {
1173                 if (nvl(endMin).equals(this.endMin))
1174                         return;
1175                 infoUpdated = true;
1176                 this.endMin = nvl(endMin, "45");                
1177         }
1178         
1179         public static boolean isNull(String a) {
1180                 if ((a == null) || (a.length() == 0) || a.equalsIgnoreCase("null"))
1181                         return true;
1182                 else
1183                         return false;
1184         }
1185         
1186     public String addZero(String num) {
1187         int numInt = 0;
1188         try {
1189                 numInt = Integer.parseInt(num);
1190         }catch(NumberFormatException ex){
1191                 numInt = 0;
1192         }
1193         if(numInt < 10) return "0"+numInt;
1194         else return ""+numInt;
1195     }
1196     
1197         public static String loadConditionalSQL(String scheduleId)
1198                 throws RaptorException {
1199                 StringBuffer sb = new StringBuffer();
1200                  
1201                 PreparedStatement stmt = null;
1202                 
1203                 ResultSet rs = null;
1204                 String condition_sql = "";
1205                 Connection connection = null;
1206                 
1207                 try {
1208                         connection = DbUtils.getConnection();
1209
1210                         //String sql = "SELECT condition_large_sql FROM cr_report_schedule WHERE schedule_id=?";
1211                         String sql = Globals.getLoadCondSql();
1212                         stmt = connection.prepareStatement(sql);
1213                         stmt.setString(1,scheduleId);
1214                         rs = stmt.executeQuery();
1215                         if(Globals.isWeblogicServer()) {
1216                                         java.sql.Clob clob= null;
1217                                         Object obj = null;
1218                                         if (rs.next()) {
1219                                                 clob = rs.getClob(1);
1220                                         }
1221                                         else
1222                                                 throw new RuntimeException("Schedule ID " + scheduleId + " not found in the database");
1223                 
1224                                         int len = 0;
1225                                         char[] buffer = new char[512];
1226                                         Reader in = null;
1227                                         in = new InputStreamReader(clob.getAsciiStream());
1228                 //                      if(obj instanceof oracle.sql.CLOB) {
1229                 //                              in = ((oracle.sql.CLOB) obj).getCharacterStream();
1230                 //                      } else if (obj instanceof weblogic.jdbc.wrapper.Clob) {
1231                 //                              in = ((weblogic.jdbc.base.BaseClob) obj).getCharacterStream();
1232                 //                      }
1233                                                 while ((len = in.read(buffer)) != -1)
1234                                                         sb.append(buffer, 0, len);
1235                                                 in.close();
1236             } else if (Globals.isPostgreSQL() || Globals.isMySQL()) {
1237                    String clob= null;
1238                                         Object obj = null;
1239                                         if (rs.next()) {
1240                                                 sb.append(rs.getString(1));
1241                                         }
1242                                         else
1243                                                 throw new RaptorException("Schedule ID " + scheduleId + " not found in the database");                                          
1244                        } else {
1245                                 /*oracle.sql.CLOB clob = null;
1246                                 if (rs.next())
1247                                         clob = (oracle.sql.CLOB) rs.getObject(1);
1248                                 else
1249                                         throw new RuntimeException("Schedule ID " + scheduleId + " not found in the database");
1250                                 int len = 0;
1251                                 char[] buffer = new char[512];
1252                                 Reader in = null;
1253                                 if(clob!=null) {
1254                                         in = clob.getCharacterStream();
1255                                         while ((len = in.read(buffer)) != -1)
1256                                                 sb.append(buffer, 0, len);
1257                                         in.close();
1258                                 }*/
1259                     throw new RaptorException("only maria db support for this ");
1260
1261                     }
1262                 } catch (SQLException ex) {
1263                         try {
1264                         StringBuffer query = new StringBuffer("");
1265                         
1266                         query.append(" SELECT condition_sql FROM cr_report_schedule WHERE schedule_id = " + scheduleId);
1267                         DataSet ds = DbUtils.executeQuery(query.toString());
1268                         if(ds.getRowCount()>0) {
1269                                 condition_sql = ds.getString(0,0);
1270                         }
1271                          return condition_sql;
1272                         //throw new ReportSQLException (ex.getMessage(), ex.getCause());
1273                         } catch (RaptorException e) {
1274                                 DbUtils.rollbackTransaction(connection);
1275                                 throw e;
1276                         } // catch
1277                         
1278                 finally {
1279                     DbUtils.clearConnection(connection);
1280                 }
1281                 
1282                 } catch (IOException ex) {
1283                         throw new RaptorRuntimeException (ex.getMessage(), ex.getCause());
1284            } finally {
1285                    try {
1286                         if (connection != null)
1287                                 DbUtils.clearConnection(connection);
1288                            if(rs!=null)
1289                                    rs.close();
1290                            if(stmt!=null)
1291                                    stmt.close();
1292                    } catch (SQLException ex) {
1293                                 throw new ReportSQLException (ex.getMessage(), ex.getCause());
1294                    }
1295                 }
1296                 return sb.toString();
1297         } // loadConditionalSQL
1298     
1299         private static void persistConditionSql(Connection connection, String scheduleId, String conditional_sql) throws RaptorException {
1300                 PreparedStatement stmt = null;
1301                 ResultSet rs = null;
1302
1303                 try {
1304                         //String sql = "update cr_report_schedule set condition_large_sql = EMPTY_CLOB() where  schedule_id = " + scheduleId;
1305                         String sql = Globals.getPersistCondSqlUpdate();
1306                         sql = sql.replace("[scheduleId]", scheduleId);
1307                         
1308                         DbUtils.executeUpdate(sql);
1309                         //sql = "SELECT condition_large_sql FROM cr_report_schedule cr WHERE schedule_id=?       FOR UPDATE";
1310                         sql = Globals.getPersistCondSqlLarge();
1311                         stmt = connection.prepareStatement(sql);
1312                         stmt.setString(1,scheduleId);
1313                         rs = stmt.executeQuery();
1314                         //Writer out = null;
1315             /*if(Globals.isWeblogicServer()) {
1316                 java.sql.Clob clob = null;
1317                 if (rs.next())
1318                         clob = rs.getClob(1);
1319                 else
1320                         throw new RuntimeException("Schedule ID " + scheduleId + " not found in the database");
1321
1322                 if (clob.length() > conditional_sql.length())
1323                         clob.truncate(0);
1324                         //clob.trim(reportXML.length());
1325                         out = ((weblogic.jdbc.vendor.oracle.OracleThinClob)clob).getCharacterOutputStream();    
1326             } else*/
1327                         if (Globals.isPostgreSQL() || Globals.isMySQL()) {
1328                                         if (rs.next()) {
1329                                                 rs.updateString(1,conditional_sql);
1330                                                 rs.updateRow();
1331                                                 //sb.append(rs.getString(1));
1332                                         }
1333                                         else
1334                                                 throw new RaptorException("Schedule ID " + scheduleId + " not found in the database");                                  
1335              } else {/*
1336                         oracle.sql.CLOB clob = null;
1337                         if (rs.next())
1338                                 clob = (oracle.sql.CLOB) rs.getObject(1);
1339                         else
1340                                 throw new RuntimeException("Schedule ID " + scheduleId + " not found in the database");
1341
1342                         if (clob.length() > conditional_sql.length())
1343                                 clob.trim(conditional_sql.length());
1344                  out = clob.getCharacterOutputStream();*/
1345             throw new RaptorException("only maria db support for this ");
1346
1347               }
1348                         //out.write(conditional_sql);
1349                         //out.flush();
1350                         //out.close();
1351                 } catch (RaptorException ex) {
1352                         if(ex.getMessage().indexOf("invalid identifier")!= -1) {
1353                                 try {
1354                                 //String sql = "update cr_report_schedule set condition_sql = ? where schedule_id = " + scheduleId;
1355                                 String sql = Globals.getPersistCondSqlSet();
1356                                 sql = sql.replace("[scheduleId]", scheduleId);
1357                                         stmt = connection.prepareStatement(sql);
1358                                         stmt.setString(1,conditional_sql);
1359                                         stmt.executeUpdate();
1360                                         connection.commit();
1361                                 } catch (SQLException ex1) {
1362                                         try {
1363                                                 connection.rollback();
1364                                                 } catch (SQLException ex2) {}
1365                                         
1366                                         }
1367                         } else {
1368                                 try {
1369                                         connection.rollback();
1370                                 } catch (SQLException ex2) {
1371                                                 throw new ReportSQLException (ex2.getMessage(), ex2.getCause());
1372                                 } 
1373                         }
1374                 } catch (SQLException ex) {
1375                         try {
1376                                 connection.rollback();
1377                         } catch (SQLException ex2) {
1378                                         throw new ReportSQLException (ex2.getMessage(), ex2.getCause());
1379                         } 
1380                 } catch (Exception ex) {
1381                         throw new RaptorRuntimeException (ex.getMessage(), ex.getCause());
1382                 } finally {
1383                            try {        
1384                                    if(rs!=null)
1385                                            rs.close();
1386                                         if(stmt!=null) 
1387                                                 stmt.close();
1388                                    } catch (SQLException ex) {
1389                                                 throw new ReportSQLException (ex.getMessage(), ex.getCause());
1390                                    }
1391                 }
1392         } // persistConditionSql
1393         
1394         /**
1395          * Used to get encryption mode
1396          * @return the encryptMode
1397          */
1398         public String getEncryptMode() {
1399                 return encryptMode;
1400         }
1401
1402         /**
1403          * Used to set encryption mode
1404          * @param encryptMode the encryptMode to set
1405          */
1406         public void setEncryptMode(String encryptMode) {
1407                 this.encryptMode = encryptMode;
1408                 infoUpdated = true;
1409         }
1410
1411         
1412         /**
1413          * Used to get Attachment mode
1414          * @return the attachment
1415          */
1416         public String getAttachmentMode() {
1417                 return attachment;
1418         }
1419         
1420         public boolean isAttachmentMode() {
1421                 return nvl(attachment).toUpperCase().startsWith("Y");
1422         }
1423
1424         /**
1425          * Used to set Attachment mode
1426          * @param attachment to set
1427          */
1428         public void setAttachmentMode(String attachment) {
1429                 this.attachment = attachment;
1430                 infoUpdated = true;
1431         }       
1432 } // ReportSchedule