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