2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
8 * Unless otherwise specified, all software contained herein is licensed
9 * under the Apache License, Version 2.0 (the "License");
10 * you may not use this software except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * Unless otherwise specified, all documentation contained herein is licensed
22 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23 * you may not use this documentation except in compliance with the License.
24 * You may obtain a copy of the License at
26 * https://creativecommons.org/licenses/by/4.0/
28 * Unless required by applicable law or agreed to in writing, documentation
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
34 * ============LICENSE_END============================================
38 package org.onap.portalsdk.analytics.model.definition;
40 import java.io.IOException;
41 import java.io.InputStreamReader;
42 import java.io.Reader;
43 import java.io.Serializable;
44 import java.io.Writer;
45 import java.sql.Connection;
46 import java.sql.PreparedStatement;
47 import java.sql.ResultSet;
48 import java.sql.SQLException;
49 import java.util.ArrayList;
50 import java.util.Collections;
51 import java.util.Iterator;
52 import java.util.List;
53 import java.util.Vector;
54 import java.util.regex.Matcher;
55 import java.util.regex.Pattern;
57 import javax.servlet.http.HttpServletRequest;
59 import org.onap.portalsdk.analytics.RaptorObject;
60 import org.onap.portalsdk.analytics.error.RaptorException;
61 import org.onap.portalsdk.analytics.error.RaptorRuntimeException;
62 import org.onap.portalsdk.analytics.error.ReportSQLException;
63 import org.onap.portalsdk.analytics.error.UserDefinedException;
64 import org.onap.portalsdk.analytics.model.base.IdNameValue;
65 import org.onap.portalsdk.analytics.model.base.NameComparator;
66 import org.onap.portalsdk.analytics.model.runtime.FormField;
67 import org.onap.portalsdk.analytics.model.runtime.ReportParamValues;
68 import org.onap.portalsdk.analytics.model.runtime.ReportRuntime;
69 import org.onap.portalsdk.analytics.system.AppUtils;
70 import org.onap.portalsdk.analytics.system.ConnectionUtils;
71 import org.onap.portalsdk.analytics.system.DbUtils;
72 import org.onap.portalsdk.analytics.system.Globals;
73 import org.onap.portalsdk.analytics.util.AppConstants;
74 import org.onap.portalsdk.analytics.util.DataSet;
75 import org.onap.portalsdk.analytics.util.RemDbInfo;
76 import org.onap.portalsdk.analytics.util.Utils;
77 import org.onap.portalsdk.analytics.xmlobj.FormFieldType;
78 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
79 import org.onap.portalsdk.core.util.SecurityCodecUtil;
80 import org.owasp.esapi.ESAPI;
81 import org.springframework.beans.factory.annotation.Autowired;
82 import org.springframework.stereotype.Component;
85 public class ReportSchedule extends RaptorObject implements Serializable{
90 private static final long serialVersionUID = 6936844475227328201L;
92 private static transient final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ReportSchedule.class);
94 private static RemDbInfo remDbInfo;
96 @SuppressWarnings("static-access")
98 public void setRemDbInfo(RemDbInfo remDbInfo) {
99 this.remDbInfo = remDbInfo;
102 private String reportID = null;
104 private String scheduleUserID = null;
106 private String scheduleID = "";
108 private boolean infoUpdated = false;
110 private String schedEnabled = "Y";
112 private String startDate = "";
114 private String endDate = "";
116 private String runDate = "";
118 private String runHour = "12";
120 private String runMin = "00";
122 private String runAMPM = "AM";
124 private String endHour = "11";
126 private String endMin = "45";
128 private String endAMPM = "PM";
130 private String recurrence = "";
132 private String conditional = "N";
134 private String conditionSQL = "";
136 private String notify_type = "1"; //1 -- link, 2 -- pdf, 4 -- excel, 3 -- csv
138 private String encryptMode = "N"; //1 -- link, 2 -- pdf, 4 -- excel, 3 -- csv
140 private String attachment = "Y"; //1 -- link, 2 -- pdf, 4 -- excel, 3 -- csv
142 private String downloadLimit = "0";
144 private String formFields = "";
146 private Vector emailToUsers = new Vector();
148 private Vector emailToRoles = new Vector();
150 public ReportSchedule() {
154 public ReportSchedule(String reportID, String scheduleUserID, boolean loadData, HttpServletRequest request) {
157 setReportID(reportID);
158 setScheduleUserID(scheduleUserID);
160 loadScheduleData(request);
165 public ReportSchedule(String reportID, String scheduleID, String scheduleUserID, HttpServletRequest request) {
168 setReportID(reportID);
169 setScheduleID(scheduleID);
170 setScheduleUserID(scheduleUserID);
171 loadScheduleData(request);
174 void setReportID(String reportID) {
175 this.reportID = reportID;
178 public String getSchedEnabled() {
182 public String getStartDate() {
186 public String getEndDate() {
190 public String getRunDate() {
194 public String getRunHour() {
198 public String getRunMin() {
202 public String getRunAMPM() {
206 public String getRecurrence() {
210 public String getConditional() {
214 public String getConditionSQL() {
218 public List getEmailToUsers() {
222 public List getEmailToRoles() {
227 * @return the downloadLimit
229 public String getDownloadLimit() {
230 return downloadLimit;
234 * @param downloadLimit the downloadLimit to set
236 public void setDownloadLimit(String downloadLimit) {
237 if(nvl(downloadLimit).equals(this.downloadLimit))
239 this.downloadLimit = nvl(downloadLimit,"0");
244 * @return the formFields
246 public String getFormFields() {
251 * @param formFields the formFields to set
253 public void setFormFields(String formFields) {
254 if(nvl(formFields).equals(this.formFields))
256 this.formFields = nvl(formFields);
260 public String getNotify_type() {
265 * @param notify_type the notify_type to set
266 * 1 -- link (default), 2 -- pdf, 4 -- excel
268 public void setNotify_type(String notify_type) {
269 if(nvl(notify_type).equals(this.notify_type))
271 this.notify_type = nvl(notify_type,"1");
275 public void setSchedEnabled(String schedEnabled) {
276 if (nvl(schedEnabled).equals(this.schedEnabled))
279 this.schedEnabled = nvl(schedEnabled, "N");
282 public void setStartDate(String startDate) {
283 if (nvl(startDate).equals(this.startDate))
286 this.startDate = nvl(startDate);
289 public void setEndDate(String endDate) {
290 if (nvl(endDate).equals(this.endDate))
293 this.endDate = nvl(endDate);
296 public void setRunDate(String runDate) {
297 if (nvl(runDate).equals(this.runDate))
300 this.runDate = nvl(runDate);
303 public void setRunHour(String runHour) {
304 if (nvl(runHour).equals(this.runHour))
307 this.runHour = nvl(runHour, "12");
310 public void setRunMin(String runMin) {
311 if (nvl(runMin).equals(this.runMin))
314 this.runMin = nvl(runMin, "00");
317 public void setRunAMPM(String runAMPM) {
318 if (nvl(runAMPM).equals(this.runAMPM))
321 this.runAMPM = nvl(runAMPM, "AM");
324 public void setRecurrence(String recurrence) {
325 if (nvl(recurrence).equals(this.recurrence))
328 this.recurrence = nvl(recurrence);
331 public void setConditional(String conditional) {
332 if (nvl(conditional).equals(this.conditional))
335 this.conditional = nvl(conditional, "N");
338 public void setConditionSQL(String conditionSQL) {
339 if (nvl(conditionSQL).equals(this.conditionSQL))
342 this.conditionSQL = nvl(conditionSQL);
345 public void addEmailToUser(String userId, String userName) {
346 if (nvl(userId).length() == 0)
349 for (int i = 0; i < emailToUsers.size(); i++) {
350 IdNameValue selUser = (IdNameValue) emailToUsers.get(i);
351 if (userId.equals(selUser.getId()))
355 emailToUsers.add(new IdNameValue(userId, userName));
356 Collections.sort(emailToUsers, new NameComparator());
361 public void addEmailArrayToUser(ArrayList<IdNameValue> allSelectedUsers) {
362 if (allSelectedUsers==null || allSelectedUsers.size()<=0)
364 emailToUsers.removeAllElements();
365 for (int i = 0; i < allSelectedUsers.size(); i++) {
366 emailToUsers.add(allSelectedUsers.get(i));
368 Collections.sort(emailToUsers, new NameComparator());
370 } // addEmailArrayToUser
372 public void removeEmailToUser(String userId) {
373 if (nvl(userId).length() == 0)
376 for (int i = 0; i < emailToUsers.size(); i++) {
377 IdNameValue selUser = (IdNameValue) emailToUsers.get(i);
378 if (userId.equals(selUser.getId())) {
380 emailToUsers.remove(i);
384 } // removeEmailToUser
386 public void addEmailToRole(String roleId, String roleName) {
387 if (nvl(roleId).length() == 0)
390 for (int i = 0; i < emailToRoles.size(); i++) {
391 IdNameValue selRole = (IdNameValue) emailToRoles.get(i);
392 if (roleId.equals(selRole.getId()))
396 emailToRoles.add(new IdNameValue(roleId, roleName));
397 Collections.sort(emailToRoles, new NameComparator());
401 public void addEmailArrayToRole(ArrayList<IdNameValue> allSelectedRoles) {
402 if (allSelectedRoles==null || allSelectedRoles.size()<=0)
404 emailToRoles.removeAllElements();
405 for (int i = 0; i < allSelectedRoles.size(); i++) {
406 emailToRoles.add(allSelectedRoles.get(i));
408 Collections.sort(emailToRoles, new NameComparator());
410 } // addEmailArrayToRole
412 public void removeEmailToRole(String roleId) {
413 if (nvl(roleId).length() == 0)
416 for (int i = 0; i < emailToRoles.size(); i++) {
417 IdNameValue selRole = (IdNameValue) emailToRoles.get(i);
418 if (roleId.equals(selRole.getId())) {
420 emailToRoles.remove(i);
426 private void loadScheduleData(HttpServletRequest request) {
428 StringBuffer query = new StringBuffer("");
429 String q_sql = Globals.getLoadScheduleData();
430 q_sql = q_sql.replace("[reportID]", reportID);
433 if(!AppUtils.isAdminUser(request))
434 query.append(" and rs.sched_user_id = " + getScheduleUserID());
435 if(nvl(getScheduleID()).length()>0) {
436 query.append(" and rs.schedule_id = " + getScheduleID());
438 query.append(" order by rs.run_date desc ");
441 .executeQuery(query.toString());
443 if (ds.getRowCount() > 0) {
444 schedEnabled = nvl(ds.getString(0, 0), "N");
445 startDate = nvl(ds.getString(0, 1));
446 endDate = nvl(ds.getString(0, 2));
447 runDate = nvl(ds.getString(0, 3));
448 runHour = nvl(ds.getString(0, 4), "12");
449 runMin = nvl(ds.getString(0, 5), "00");
450 runAMPM = nvl(ds.getString(0, 6), "AM");
451 recurrence = nvl(ds.getString(0, 7));
452 conditional = nvl(ds.getString(0, 8), "N");
453 notify_type = nvl(ds.getString(0, 9), "1");
454 downloadLimit = nvl(ds.getString(0, 10), "1000");
455 formFields = nvl(ds.getString(0, 11));
456 setScheduleID(ds.getString(0, 12));
457 endHour = nvl(ds.getString(0, 13), "11");
458 endMin = nvl(ds.getString(0, 14), "45");
459 endAMPM = nvl(ds.getString(0, 15), "PM");
460 encryptMode = nvl(ds.getString(0, "encrypt_yn"), "N");
461 attachment = nvl(ds.getString(0, "attachment_yn"), "Y");
462 conditionSQL = loadConditionalSQL(getScheduleID());
464 String n_sql = Globals.getNewScheduleData();
465 DataSet dsSeq = DbUtils.executeQuery(n_sql);
466 String schedule_id = dsSeq.getString(0,0);
467 setScheduleID(schedule_id);
469 if(getScheduleID().length() > 0) {
470 String t_sql = Globals.getLoadScheduleGetId();
471 t_sql = t_sql.replace("[reportID]", reportID);
472 t_sql = t_sql.replace("[getScheduleID()]", getScheduleID());
474 ds = DbUtils.executeQuery(t_sql);
476 for (int i = 0; i < ds.getRowCount(); i++){
477 String nameToDisplay = ds.getString(i, 1);
478 if (Globals.getUseLoginIdInSchedYN()!= null && Globals.getUseLoginIdInSchedYN().equals("Y")) {
479 nameToDisplay = ds.getString(i, 2);
481 if(nameToDisplay!=null && nameToDisplay.length() > 0)
482 emailToUsers.add(new IdNameValue(ds.getString(i, 0), nameToDisplay));
484 emailToUsers.add(new IdNameValue(ds.getString(i, 0), ds.getString(i, 1)));
486 Collections.sort(emailToUsers, new NameComparator());
488 String r_sql = Globals.getLoadScheduleUsers();
489 r_sql = r_sql.replace("[reportID]", reportID);
490 r_sql = r_sql.replace("[getScheduleID()]", getScheduleID());
492 ds = DbUtils.executeQuery(r_sql);
494 for (int i = 0; i < ds.getRowCount(); i++)
495 emailToRoles.add(new IdNameValue(ds.getString(i, 0), AppUtils.getRoleName(ds
497 Collections.sort(emailToRoles, new NameComparator());
501 } catch (Exception e) {
502 throw new RuntimeException(
503 "[ReportSchedule.loadScheduleData] Unable to load Report " + reportID
504 + " schedule. Error: " + e.getMessage());
506 } // loadScheduleData
508 private void newScheduleData() {
510 String sql = Globals.getNewScheduleData();
511 DataSet dsSeq = DbUtils.executeQuery(sql);
513 String schedule_id = dsSeq.getString(0,0);
514 setScheduleID(schedule_id);
515 } catch (Exception e) {
516 throw new RuntimeException(
517 "[ReportSchedule.newScheduleData] Unable to load Report " + reportID
518 + " schedule. Error: " + e.getMessage());
522 private String parseScheduleSQL(HttpServletRequest request, String sql) throws RaptorException {
525 logger.debug(EELFLoggerDelegate.debugLogger, (sql));
526 String[] reqParameters = Globals.getRequestParams().split(",");
527 String[] sessionParameters = Globals.getSessionParams().split(",");
528 String[] scheduleSessionParameters = Globals.getSessionParamsForScheduling().split(",");
529 javax.servlet.http.HttpSession session = request.getSession();
530 ReportRuntime rr = (ReportRuntime) session.getAttribute(AppConstants.SI_REPORT_RUNTIME);
531 String userId = AppUtils.getUserID(request);
533 String dbInfo = rr.getDBInfo();
534 ReportParamValues paramValues = rr.getReportParamValues();
536 // For Daytona removing all formfields which has null param value
538 Matcher matcher = null;
540 int posFormField = 0;
542 if (!isNull(dbInfo) && (!dbInfo.equals(AppConstants.DB_LOCAL))) {
544 dbType = remDbInfo.getDBType(dbInfo);
545 } catch (Exception ex) {
546 throw new RaptorException(ex);
551 sql = Pattern.compile("(^[\r\n]*|([\\s]))[Ss][Ee][Ll][Ee][Cc][Tt]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" SELECT ");
552 sql = Pattern.compile("(^[\r\n]*|([\\s]))[Ww][Hh][Ee][Rr][Ee]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" WHERE ");
553 sql = Pattern.compile("(^[\r\n]*|([\\s]))[Aa][Nn][Dd]([\r\n]*|[\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" AND ");
555 if (rr.getFormFieldList() != null) {
556 for (Iterator iter = rr.getFormFieldList().getFormField().iterator(); iter.hasNext();) {
558 FormFieldType fft = (FormFieldType) iter.next();
559 String fieldId = fft.getFieldId();
560 String fieldDisplay = rr.getFormFieldDisplayName(fft);
561 if(!fft.getFieldType().equals(FormField.FFT_BLANK)) {
562 if (paramValues.isParameterMultiValue(fieldId)) {
563 String replaceValue = rr.formatListValue(fieldDisplay, nvl(paramValues.getParamValue(fieldId)), null, false,
564 true, null, paramValues.getParamBaseSQL(fieldId));
565 if(replaceValue.length() > 0) {
566 sql = Utils.replaceInString(sql, fieldDisplay, replaceValue);
569 if(fieldCount == 1) {
571 while(sql.indexOf(fieldDisplay) > 0) {
573 re1 = Pattern.compile("(^[\r\n]|[\\s])AND(.*?[^\r\n]*)"+ "\\["+fft.getFieldName()+ "\\](.*?)\\s", 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);
580 posFormField = sql.indexOf(fieldDisplay);
581 int posSelectField = sql.lastIndexOf("SELECT ", posFormField);
582 int whereField = sql.indexOf(" WHERE" , posSelectField);
584 if(posFormField > whereField)
585 andField = sql.lastIndexOf(" AND ", posFormField);
586 if (posFormField > andField && andField > whereField)
590 matcher = re1.matcher(sql);
593 if (posAnd > 0 && matcher.find(posAnd-1)) {
594 matcher = re1.matcher(sql);
595 index = sql!=null?sql.lastIndexOf("["+fft.getFieldName()+"]"):-1;
601 if(index >= 0 && matcher.find(index-1)) {
602 sql = sql.replace(matcher.group(), " ");
607 re1 = Pattern.compile("(^[\r\n]|[\\s])WHERE(.*?[^\r\n]*)\\["+fft.getFieldName()+ "\\](.*?)\\s", Pattern.DOTALL);
608 matcher = re1.matcher(sql);
609 if(matcher.find(whereField-1)) {
610 matcher = re1.matcher(sql);
611 index = sql!=null?sql.lastIndexOf("["+fft.getFieldName()+"]"):-1;
612 if(index >= 0 && matcher.find(index-30)) {
613 sql = sql.replace(matcher.group(), " WHERE 1=1 ");
616 replaceValue = formatListValue("", Utils
617 .oracleSafe(nvl(paramValues.getParamValue(fieldId))), null, false,
618 true, null, paramValues.getParamBaseSQL(fieldId));
619 sql = Utils.replaceInString(sql, fieldDisplay, replaceValue);
628 String paramValue = "";
629 if(paramValues.isParameterTextAreaValueAndModified(fieldId)) {
631 value = nvl(paramValues
632 .getParamValue(fieldId));
635 paramValue = nvl(paramValues
636 .getParamValue(fieldId));
638 if (paramValue!=null && paramValue.length() > 0) {
639 if(paramValue.toLowerCase().trim().startsWith("select ")) {
640 paramValue = Utils.replaceInString(paramValue, "[LOGGED_USERID]", ESAPI.encoder().encodeForSQL( SecurityCodecUtil.getCodec(),userId));
641 paramValue = Utils.replaceInString(paramValue, "[USERID]", ESAPI.encoder().encodeForSQL( SecurityCodecUtil.getCodec(),userId));
642 paramValue = Utils.replaceInString(paramValue, "[USER_ID]", ESAPI.encoder().encodeForSQL( SecurityCodecUtil.getCodec(),userId));
644 paramValue = Utils.replaceInString(paramValue, "''", "'");
645 ds = ConnectionUtils.getDataSet(paramValue, dbInfo);
646 if (ds.getRowCount() > 0){
647 paramValue = ds.getString(0, 0);
650 logger.debug(EELFLoggerDelegate.debugLogger, ("SQLSQLBASED B4^^^^^^^^^ " + sql + " " + fft.getValidationType() + " " + fft.getFieldName() + " " + fft.getFieldId()));
651 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) ))) {
652 if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_HR)) {
653 sql = Utils.replaceInString(sql, fieldDisplay, nvl(
654 paramValue) +((nvl(paramValues
655 .getParamValue(fieldId+"_Hr") ).length()>0)?" "+addZero(nvl(paramValues
656 .getParamValue(fieldId+"_Hr") ) ):""));
658 else if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_MIN)) {
659 sql = Utils.replaceInString(sql, fieldDisplay, nvl(
660 paramValue) + ((nvl(paramValues
661 .getParamValue(fieldId+"_Hr") ).length()>0)?" "+addZero(nvl(paramValues
662 .getParamValue(fieldId+"_Hr") ) ):"") + ((nvl(paramValues
663 .getParamValue(fieldId+"_Min") ).length()>0)?":" + addZero(nvl(paramValues
664 .getParamValue(fieldId+"_Min") ) ) : "") ) ;
666 else if(fft.getValidationType().equals(FormField.VT_TIMESTAMP_SEC)) {
667 sql = Utils.replaceInString(sql, fieldDisplay, nvl(
668 paramValue) + ((nvl(paramValues
669 .getParamValue(fieldId+"_Hr") ).length()>0)?" "+addZero(nvl(paramValues
670 .getParamValue(fieldId+"_Hr") ) ):"") + ((nvl(paramValues
671 .getParamValue(fieldId+"_Min") ).length()>0)?":" + addZero(nvl(paramValues
672 .getParamValue(fieldId+"_Min") ) ) : "") + ((nvl(paramValues
673 .getParamValue(fieldId+"_Sec") ).length()>0)?":"+addZero(nvl(paramValues
674 .getParamValue(fieldId+"_Sec") ) ) : "" ) ) ;
676 sql = Utils.replaceInString(sql, fieldDisplay, nvl(
677 paramValue, "NULL"));
682 if(paramValue!=null && paramValue.length() > 0) {
683 if(sql.indexOf("'"+fieldDisplay+"'")!=-1 || sql.indexOf("'"+fieldDisplay)!=-1 || sql.indexOf(fieldDisplay+"'")!=-1
684 || sql.indexOf("'%"+fieldDisplay+"%'")!=-1 || sql.indexOf("'%"+fieldDisplay)!=-1 || sql.indexOf(fieldDisplay+"%'")!=-1
685 || sql.indexOf("'_"+fieldDisplay+"_'")!=-1 || sql.indexOf("'_"+fieldDisplay)!=-1 || sql.indexOf(fieldDisplay+"_'")!=-1
686 || sql.indexOf("'%_"+fieldDisplay+"_%'")!=-1 || sql.indexOf("^"+fieldDisplay+"^")!=-1 || sql.indexOf("'%_"+fieldDisplay)!=-1 || sql.indexOf(fieldDisplay+"_%'")!=-1) {
687 sql = Utils.replaceInString(sql, fieldDisplay, nvl(
688 paramValue, "NULL"));
690 if(sql.indexOf(fieldDisplay)!=-1) {
691 if(nvl(paramValue).length()>0) {
693 double vD = Double.parseDouble(paramValue);
694 sql = Utils.replaceInString(sql, fieldDisplay, nvl(
695 paramValue, "NULL"));
697 } catch (NumberFormatException ex) {
698 if (/*dbType.equals("DAYTONA") &&*/ sql.trim().toUpperCase().startsWith("SELECT")) {
699 sql = Utils.replaceInString(sql, fieldDisplay, nvl(
700 paramValue, "NULL"));
702 throw new UserDefinedException("Expected number, Given String for the form field \"" + fieldDisplay+"\"");
705 sql = Utils.replaceInString(sql, fieldDisplay, nvl(
706 paramValue, "NULL"));
712 if (dbType.equals("DAYTONA") && sql.trim().toUpperCase().startsWith("SELECT")) {
714 re1 = Pattern.compile("(^[\r\n]|[\\s]|[^0-9a-zA-Z])AND(.*?[^\r\n]*)"+ "\\["+fft.getFieldName()+ "\\](.*?)\\s", Pattern.DOTALL);
715 posFormField = sql.indexOf(fieldDisplay);
716 posAnd = sql.lastIndexOf(" AND ", posFormField);
721 matcher = re1.matcher(sql);
722 if (matcher.find(posAnd)) {
723 sql = sql.replace(matcher.group(), "");
726 sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl(
727 paramValue, "NULL"));
728 sql = Utils.replaceInString(sql, fieldDisplay, nvl(
729 paramValue, "NULL"));
736 if (dbType.equals("DAYTONA") && sql.trim().toUpperCase().startsWith("SELECT")) {
738 re1 = Pattern.compile("(^[\r\n]|[\\s]|[^0-9a-zA-Z])AND(.*?[^\r\n]*)"+ "\\["+fft.getFieldName()+ "\\](.*?)\\s", Pattern.DOTALL); //+[\'\\)|\'|\\s]
739 posFormField = sql.indexOf(fieldDisplay);
740 posAnd = sql.lastIndexOf(" AND ", posFormField);
745 matcher = re1.matcher(sql);
746 if (matcher.find(posAnd)) {
747 sql = sql.replace(matcher.group(), " ");
751 logger.debug(EELFLoggerDelegate.debugLogger, ("ParamValue |" + paramValue + "| Sql |" + sql + "| Multi Value |" + paramValues.isParameterMultiValue(fieldId)));
752 sql = Utils.replaceInString(sql, "'" + fieldDisplay + "'", nvl(
753 paramValue, "NULL"));
754 sql = Utils.replaceInString(sql, fieldDisplay , nvl(
755 paramValue, "NULL"));
756 logger.debug(EELFLoggerDelegate.debugLogger, ("SQLSQLBASED AFTER^^^^^^^^^ " + sql));
762 if(request != null ) {
763 for (int i = 0; i < reqParameters.length; i++) {
764 if(!reqParameters[i].startsWith("ff")) {
765 if (nvl(request.getParameter(reqParameters[i].toUpperCase())).length() > 0)
766 sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i].toUpperCase()) );
769 sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) );
772 for (int i = 0; i < scheduleSessionParameters.length; i++) {
773 if(nvl(request.getParameter(scheduleSessionParameters[i])).trim().length()>0 )
774 sql = Utils.replaceInString(sql, "[" + scheduleSessionParameters[i].toUpperCase()+"]", request.getParameter(scheduleSessionParameters[i]) );
777 if(session != null ) {
778 for (int i = 0; i < sessionParameters.length; i++) {
779 logger.debug(EELFLoggerDelegate.debugLogger, (" Session " + " sessionParameters[i] " + sessionParameters[i] + " " + (String)session.getAttribute(sessionParameters[i])));
780 sql = Utils.replaceInString(sql, "[" + sessionParameters[i].toUpperCase()+"]", (String)session.getAttribute(sessionParameters[i]) );
785 logger.debug(EELFLoggerDelegate.debugLogger, ("BEFORE LOGGED USERID REPLACE " + sql));
786 sql = Utils.replaceInString(sql, "[LOGGED_USERID]", userId);
787 sql = Utils.replaceInString(sql, "[USERID]", userId);
788 sql = Utils.replaceInString(sql, "[USER_ID]", userId);
789 logger.debug(EELFLoggerDelegate.debugLogger, ("AFTER LOGGED USERID REPLACE " + sql));
790 // Added for Simon's GM Project where they need to get page_id in their query
791 logger.debug(EELFLoggerDelegate.debugLogger, ("SQLSQLBASED no formfields " + sql));
792 if(request != null ) {
793 for (int i = 0; i < reqParameters.length; i++) {
794 sql = Utils.replaceInString(sql, "[" + reqParameters[i].toUpperCase()+"]", request.getParameter(reqParameters[i]) );
797 if(session != null ) {
798 for (int i = 0; i < sessionParameters.length; i++) {
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]) );
804 // if it is not multiple select and ParamValue is empty this is the place it can be replaced.
805 sql = Utils.replaceInString(sql, "[LOGGED_USERID]", userId);
806 sql = Utils.replaceInString(sql, "[USERID]", userId);
807 sql = Utils.replaceInString(sql, "[USER_ID]", userId);
808 logger.debug(EELFLoggerDelegate.debugLogger, ("SQLSQLBASED no formfields after" + sql));
810 sql = Pattern.compile("([\n][\\s]*)",Pattern.DOTALL).matcher(sql).replaceAll(" ");
814 public void persistScheduleData(Connection conn, HttpServletRequest request) throws RaptorException {
817 if (reportID.equals("-1"))
822 String sched_id = "";
823 StringBuffer query = new StringBuffer("");
824 query.append(" SELECT 1 FROM cr_report_schedule WHERE rep_id = " + reportID + " and schedule_id = " + getScheduleID());
825 if(!AppUtils.isAdminUser(request))
826 query.append(" and sched_user_id = " + getScheduleUserID());
827 DataSet ds = DbUtils.executeQuery(conn, query.toString());
828 if (ds.getRowCount() > 0) {
829 StringBuffer sb = new StringBuffer();
830 sb.append("UPDATE cr_report_schedule SET enabled_yn = '");
831 sb.append(getSchedEnabled());
832 sb.append("', start_date = ");
833 if (getStartDate().length() > 0) {
834 sb.append("TO_DATE('");
835 sb.append(getStartDate());
836 sb.append("', 'MM/DD/YYYY')");
839 sb.append(", end_date = ");
840 if (getEndDate().length() > 0) {
841 sb.append("TO_DATE('");
842 sb.append(getEndDate());
844 sb.append(getEndHour());
846 sb.append(getEndMin());
848 sb.append(getEndAMPM());
849 sb.append("', 'MM/DD/YYYY HH:MI AM')");
852 sb.append(", run_date = ");
853 if (getRunDate().length() > 0) {
854 sb.append("TO_DATE('");
855 sb.append(getRunDate());
857 sb.append(getRunHour());
859 sb.append(getRunMin());
861 sb.append(getRunAMPM());
862 sb.append("', 'MM/DD/YYYY HH:MI AM')");
865 sb.append(", recurrence = ");
866 if (getRecurrence().length() > 0) {
868 sb.append(getRecurrence());
872 sb.append(", conditional_yn = '");
873 sb.append(getConditional());
876 sb.append(", notify_type = ");
877 sb.append(getNotify_type());
878 sb.append(", encrypt_yn = '");
879 sb.append(getEncryptMode()+"'");
880 sb.append(", attachment_yn = '");
881 sb.append(getAttachmentMode()+"'");
882 sb.append(", max_row = ");
883 sb.append(getDownloadLimit());
884 sb.append(", initial_formFields = '");
885 sb.append(getFormFields()+"'");
886 sb.append(", processed_formfields = ''");
887 sb.append(" WHERE rep_id = ");
888 sb.append(reportID + " and sched_user_id = ");
889 sb.append(getScheduleUserID());
890 sb.append(" and schedule_id = ");
891 sb.append(getScheduleID());
893 DbUtils.executeUpdate(conn, sb.toString());
895 String w_sql = Globals.getNewScheduleData();
896 DataSet dsSeq = DbUtils.executeQuery(w_sql);
897 String schedule_id = dsSeq.getString(0,0);
898 setScheduleID(schedule_id);
899 StringBuffer sb = new StringBuffer();
900 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(");
901 sb.append(getScheduleID() + ", ");
902 sb.append(getScheduleUserID() + ", ");
905 sb.append(getSchedEnabled());
907 if (getStartDate().length() > 0) {
908 sb.append("TO_DATE('");
909 sb.append(getStartDate());
910 sb.append("', 'MM/DD/YYYY')");
914 if (getEndDate().length() > 0) {
915 sb.append("TO_DATE('");
916 sb.append(getEndDate());
918 sb.append(getEndHour());
920 sb.append(getEndMin());
922 sb.append(getEndAMPM());
923 sb.append("', 'MM/DD/YYYY HH:MI AM')");
927 if (getRunDate().length() > 0) {
928 sb.append("TO_DATE('");
929 sb.append(getRunDate());
931 sb.append(getRunHour());
933 sb.append(getRunMin());
935 sb.append(getRunAMPM());
936 sb.append("', 'MM/DD/YYYY HH:MI AM')");
940 if (getRecurrence().length() > 0) {
942 sb.append(getRecurrence());
947 sb.append(getConditional());
949 sb.append(getNotify_type());
951 sb.append(getDownloadLimit());
953 sb.append(getFormFields()+"'");
955 sb.append(getEncryptMode()+"'");
957 sb.append(getAttachmentMode()+"'");
959 DbUtils.executeUpdate(conn, sb.toString());
964 String d_sql = Globals.getExecuteUpdate();
965 d_sql = d_sql.replace("[reportID]", reportID);
966 d_sql = d_sql.replace("[getScheduleID()]", getScheduleID());
968 DbUtils.executeUpdate(conn, d_sql);
970 for (int i = 0; i < emailToUsers.size(); i++){
972 String sql = Globals.getExecuteUpdateUsers();
973 sql = sql.replace("[getScheduleID()]", getScheduleID());
974 sql = sql.replace("[reportID]", reportID);
975 sql = sql.replace("[emailToUsers.get(i)).getId()]", ((IdNameValue) emailToUsers.get(i)).getId());
976 sql = sql.replace("[(i + 1)]", String.valueOf(i + 1));
977 DbUtils.executeUpdate(conn, sql);
980 for (int i = 0; i < emailToRoles.size(); i++){
982 String sql = Globals.getExecuteUpdateRoles();
983 sql = sql.replace("[getScheduleID()]", getScheduleID());
984 sql = sql.replace("[reportID]", reportID);
985 sql = sql.replace("[emailToRoles.get(i)).getId()]", ((IdNameValue) emailToRoles.get(i)).getId());
986 sql = sql.replace("[((emailToUsers.size() + i + 1)]", String.valueOf(emailToUsers.size() + i + 1));
988 DbUtils.executeUpdate(conn, sql);
991 DbUtils.commitTransaction(conn);
993 persistConditionSql(conn, getScheduleID(), parseScheduleSQL(request, getConditionSQL()));
996 logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] DB update report " + reportID + " - schedule data updated"));
997 String e_sql = Globals.getExecuteUpdateActivity();
998 e_sql = e_sql.replace("[getScheduleID()]", getScheduleID());
999 e_sql = e_sql.replace("[getRunDate()]", getRunDate());
1000 e_sql = e_sql.replace("[getRunHour()]", getRunHour());
1001 e_sql = e_sql.replace("[getRunMin()]", getRunMin());
1002 e_sql = e_sql.replace("[getRunAMPM()]", getRunAMPM());
1004 DbUtils.executeUpdate(conn, e_sql);
1006 infoUpdated = false;
1008 } catch (RaptorException e) {
1010 DbUtils.rollbackTransaction(conn);
1014 } // persistScheduleData
1016 //deleting the schedule - Start
1017 public void deleteScheduleData(Connection conn) throws RaptorException {
1018 if (reportID.equals("-1"))
1021 Connection connection = (conn != null) ? conn : DbUtils.startTransaction();
1022 String sched_id = "";
1024 //DataSet ds = DbUtils.executeQuery(connection,
1025 // "SELECT 1 FROM cr_report_schedule WHERE rep_id = " + reportID +" and sched_user_id = " + getScheduleUserID() + " and schedule_id = " + getScheduleID());
1026 String a_sql = Globals.getDeleteScheduleData();
1027 a_sql = a_sql.replace("[reportID]", reportID);
1028 a_sql = a_sql.replace("[getScheduleUserID()]", getScheduleUserID());
1029 a_sql = a_sql.replace("[getScheduleID()]", getScheduleID());
1030 DataSet ds = DbUtils.executeQuery(connection, a_sql);
1032 if (ds.getRowCount() > 0) {
1033 //DbUtils.executeUpdate(connection,
1034 // "DELETE cr_report_schedule_users WHERE rep_id = " + reportID+ " and schedule_id = " + getScheduleID());
1035 String b_sql = Globals.getDeleteScheduleDataUsers();
1036 b_sql = b_sql.replace("[reportID]", reportID);
1037 b_sql = b_sql.replace("[getScheduleID()]", getScheduleID());
1039 DbUtils.executeUpdate(connection, b_sql);
1041 StringBuffer sb = new StringBuffer();
1042 String c_sql = Globals.getDeleteScheduleDataId();
1043 c_sql = c_sql.replace("[reportID]", reportID);
1044 c_sql = c_sql.replace("[getScheduleUserID()]", getScheduleUserID());
1045 c_sql = c_sql.replace("[getScheduleID()]", getScheduleID());
1048 //sb.append("DELETE FROM cr_report_schedule where rep_id = " + reportID +" and sched_user_id = " + getScheduleUserID() + " and schedule_id = " + getScheduleID());
1050 DbUtils.executeUpdate(connection, sb.toString());
1053 DbUtils.commitTransaction(connection);
1055 logger.debug(EELFLoggerDelegate.debugLogger, ("[DEBUG MESSAGE FROM RAPTOR] DB update report " + reportID + " - schedule data deleted"));
1056 } catch (RaptorException e) {
1058 DbUtils.rollbackTransaction(connection);
1063 DbUtils.clearConnection(connection);
1065 } //deleteScheduleData
1067 public String getScheduleUserID() {
1068 return scheduleUserID;
1071 public void setScheduleUserID(String scheduleUserID) {
1072 this.scheduleUserID = scheduleUserID;
1075 public String getScheduleID() {
1076 return nvl(scheduleID);
1079 public void setScheduleID(String scheduleID) {
1080 this.scheduleID = scheduleID;
1083 public String getEndAMPM() {
1087 public void setEndAMPM(String endAMPM) {
1088 if (nvl(endAMPM).equals(this.endAMPM))
1091 this.endAMPM = nvl(endAMPM, "PM");
1094 public String getEndHour() {
1098 public void setEndHour(String endHour) {
1099 if (nvl(endHour).equals(this.endHour))
1102 this.endHour = nvl(endHour, "11");
1105 public String getEndMin() {
1109 public void setEndMin(String endMin) {
1110 if (nvl(endMin).equals(this.endMin))
1113 this.endMin = nvl(endMin, "45");
1116 public static boolean isNull(String a) {
1117 if ((a == null) || (a.length() == 0) || a.equalsIgnoreCase("null"))
1123 public String addZero(String num) {
1126 numInt = Integer.parseInt(num);
1127 }catch(NumberFormatException ex){
1132 else return ""+numInt;
1135 public static String loadConditionalSQL(String scheduleId)
1136 throws RaptorException {
1137 StringBuffer sb = new StringBuffer();
1139 PreparedStatement stmt = null;
1141 ResultSet rs = null;
1142 String condition_sql = "";
1143 Connection connection = null;
1146 connection = DbUtils.getConnection();
1148 //String sql = "SELECT condition_large_sql FROM cr_report_schedule WHERE schedule_id=?";
1149 String sql = Globals.getLoadCondSql();
1150 stmt = connection.prepareStatement(sql);
1151 stmt.setString(1,scheduleId);
1152 rs = stmt.executeQuery();
1153 if(Globals.isWeblogicServer()) {
1154 java.sql.Clob clob= null;
1157 clob = rs.getClob(1);
1160 throw new RuntimeException("Schedule ID " + scheduleId + " not found in the database");
1163 char[] buffer = new char[512];
1164 try(Reader in = new InputStreamReader(clob.getAsciiStream())) {
1165 // if(obj instanceof oracle.sql.CLOB) {
1166 // in = ((oracle.sql.CLOB) obj).getCharacterStream();
1167 // } else if (obj instanceof weblogic.jdbc.wrapper.Clob) {
1168 // in = ((weblogic.jdbc.base.BaseClob) obj).getCharacterStream();
1170 while ((len = in.read(buffer)) != -1)
1171 sb.append(buffer, 0, len);
1172 } catch(Exception e) {
1173 //if any error while operating the input stream, just throw the error out
1174 //so that outer try/catch block could handle it
1177 } else if (Globals.isPostgreSQL() || Globals.isMySQL()) {
1181 sb.append(rs.getString(1));
1184 throw new RaptorException("Schedule ID " + scheduleId + " not found in the database");
1186 /*oracle.sql.CLOB clob = null;
1188 clob = (oracle.sql.CLOB) rs.getObject(1);
1190 throw new RuntimeException("Schedule ID " + scheduleId + " not found in the database");
1192 char[] buffer = new char[512];
1195 in = clob.getCharacterStream();
1196 while ((len = in.read(buffer)) != -1)
1197 sb.append(buffer, 0, len);
1200 throw new RaptorException("only maria db support for this ");
1203 } catch (SQLException ex) {
1205 StringBuffer query = new StringBuffer("");
1207 query.append(" SELECT condition_sql FROM cr_report_schedule WHERE schedule_id = " + scheduleId);
1208 DataSet ds = DbUtils.executeQuery(query.toString());
1209 if(ds.getRowCount()>0) {
1210 condition_sql = ds.getString(0,0);
1212 return condition_sql;
1213 //throw new ReportSQLException (ex.getMessage(), ex.getCause());
1214 } catch (RaptorException e) {
1215 DbUtils.rollbackTransaction(connection);
1220 DbUtils.clearConnection(connection);
1223 } catch (IOException ex) {
1224 throw new RaptorRuntimeException (ex.getMessage(), ex.getCause());
1227 if (connection != null)
1228 DbUtils.clearConnection(connection);
1233 } catch (SQLException ex) {
1234 throw new ReportSQLException (ex.getMessage(), ex.getCause());
1237 return sb.toString();
1238 } // loadConditionalSQL
1240 private static void persistConditionSql(Connection connection, String scheduleId, String conditional_sql) throws RaptorException {
1241 PreparedStatement stmt = null;
1242 ResultSet rs = null;
1245 //String sql = "update cr_report_schedule set condition_large_sql = EMPTY_CLOB() where schedule_id = " + scheduleId;
1246 String sql = Globals.getPersistCondSqlUpdate();
1247 sql = sql.replace("[scheduleId]", scheduleId);
1249 DbUtils.executeUpdate(sql);
1250 //sql = "SELECT condition_large_sql FROM cr_report_schedule cr WHERE schedule_id=? FOR UPDATE";
1251 sql = Globals.getPersistCondSqlLarge();
1252 stmt = connection.prepareStatement(sql);
1253 stmt.setString(1,scheduleId);
1254 rs = stmt.executeQuery();
1256 /*if(Globals.isWeblogicServer()) {
1257 java.sql.Clob clob = null;
1259 clob = rs.getClob(1);
1261 throw new RuntimeException("Schedule ID " + scheduleId + " not found in the database");
1263 if (clob.length() > conditional_sql.length())
1265 //clob.trim(reportXML.length());
1266 out = ((weblogic.jdbc.vendor.oracle.OracleThinClob)clob).getCharacterOutputStream();
1268 if (Globals.isPostgreSQL() || Globals.isMySQL()) {
1270 rs.updateString(1,conditional_sql);
1272 //sb.append(rs.getString(1));
1275 throw new RaptorException("Schedule ID " + scheduleId + " not found in the database");
1277 oracle.sql.CLOB clob = null;
1279 clob = (oracle.sql.CLOB) rs.getObject(1);
1281 throw new RuntimeException("Schedule ID " + scheduleId + " not found in the database");
1283 if (clob.length() > conditional_sql.length())
1284 clob.trim(conditional_sql.length());
1285 out = clob.getCharacterOutputStream();*/
1286 throw new RaptorException("only maria db support for this ");
1289 //out.write(conditional_sql);
1292 } catch (RaptorException ex) {
1293 if(ex.getMessage().indexOf("invalid identifier")!= -1) {
1295 //String sql = "update cr_report_schedule set condition_sql = ? where schedule_id = " + scheduleId;
1296 String sql = Globals.getPersistCondSqlSet();
1297 sql = sql.replace("[scheduleId]", scheduleId);
1298 stmt = connection.prepareStatement(sql);
1299 stmt.setString(1,conditional_sql);
1300 stmt.executeUpdate();
1301 connection.commit();
1302 } catch (SQLException ex1) {
1304 connection.rollback();
1305 } catch (SQLException ex2) {}
1310 connection.rollback();
1311 } catch (SQLException ex2) {
1312 throw new ReportSQLException (ex2.getMessage(), ex2.getCause());
1315 } catch (SQLException ex) {
1317 connection.rollback();
1318 } catch (SQLException ex2) {
1319 throw new ReportSQLException (ex2.getMessage(), ex2.getCause());
1321 } catch (Exception ex) {
1322 throw new RaptorRuntimeException (ex.getMessage(), ex.getCause());
1329 } catch (SQLException ex) {
1330 throw new ReportSQLException (ex.getMessage(), ex.getCause());
1333 } // persistConditionSql
1336 * Used to get encryption mode
1337 * @return the encryptMode
1339 public String getEncryptMode() {
1344 * Used to set encryption mode
1345 * @param encryptMode the encryptMode to set
1347 public void setEncryptMode(String encryptMode) {
1348 this.encryptMode = encryptMode;
1354 * Used to get Attachment mode
1355 * @return the attachment
1357 public String getAttachmentMode() {
1361 public boolean isAttachmentMode() {
1362 return nvl(attachment).toUpperCase().startsWith("Y");
1366 * Used to set Attachment mode
1367 * @param attachment to set
1369 public void setAttachmentMode(String attachment) {
1370 this.attachment = attachment;