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