3a761d84c372335b86ab3ac6a26d1e7be300b07b
[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  *
37  */
38 package org.onap.portalsdk.analytics.scheduler;
39
40 import java.math.BigDecimal;
41 import java.sql.ResultSet;
42 import java.sql.SQLException;
43 import java.text.SimpleDateFormat;
44 import java.util.Date;
45 import java.util.UUID;
46 import org.onap.portalsdk.analytics.error.RaptorException;
47 import org.onap.portalsdk.analytics.error.ReportSQLException;
48 import org.onap.portalsdk.analytics.scheduler.SchedulerUtil.Executor;
49 import org.onap.portalsdk.analytics.system.Globals;
50 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
51
52 public class SendNotifications {
53
54     private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SendNotifications.class);
55     SchedulerUtil schedulerUtil;
56     public SendEmail sendEmail;
57
58     public SendNotifications() throws Exception {
59         schedulerUtil = new SchedulerUtil();
60         sendEmail = new SendEmail();
61         sendEmail.setSchedulerUtil(schedulerUtil);
62         init();
63     }
64
65     public void deInit() throws SQLException {
66         schedulerUtil.closeConnection();
67     }
68
69     public void init() throws SQLException, ReportSQLException {
70         schedulerUtil.init();
71     }
72
73     public void send_notification(final String p_mail_server, final String p_sender, final String p_system_name,
74             final String p_system_url, final int connectionTimeout) throws RaptorException, Exception {
75
76         logger.info(p_mail_server + " " + p_sender + " " + p_system_name + " " + p_system_url);
77         final int p_time_interval = Globals.getSchedulerInterval();
78         int v_num_recs = 0;
79         BigDecimal v_id = null;
80         String v_r_action = "report.download.pdf";
81
82         final String CNotificationsql = Globals.getAvailableSchedules()
83                 .replace("[currentDate]", Globals.getCurrentDateString());
84
85         try (final ResultSet rs = schedulerUtil.getConnection().createStatement().executeQuery(CNotificationsql);) {
86             while (rs.next()) {
87                 final int v_schedule_id = rs.getInt("schedule_id");
88                 final int offset = get_report_sched_offset(rs.getInt("rep_id"), v_schedule_id);
89
90                 if (offset >= p_time_interval) {
91                     continue;
92                 }
93
94                 final Date v_touch_date = (Date) schedulerUtil.getSingleResult(
95                         "select touch_date from cr_report_email_sent_log where schedule_id = " + v_schedule_id
96                                 + " and log_id = (select max(log_id) from cr_report_email_sent_log where schedule_id = "
97                                 + v_schedule_id + ")",
98                         "touch_date");
99                 if (v_touch_date != null) {
100                     if (Math.abs(System.currentTimeMillis() - v_touch_date.getTime()) / 1000 < (p_time_interval - 1)) {
101                         return;
102                     }
103                 }
104
105                 if ("Y".equals(rs.getString("conditional_yn"))) {
106                     v_num_recs = (Integer) schedulerUtil
107                             .getSingleResult(
108                                     "select count(*) count from (" + rs.getString("condition_large_sql") + " )",
109                                     "count");
110                 }
111
112                 if (v_num_recs > 0 || "N".equals(rs.getString("conditional_yn"))) {
113                     final String v_gen_key = ("Z" + UUID.randomUUID()).toString()
114                             .substring(0, 24); // 25 character string
115                     final Object sequenceId =
116                             schedulerUtil.getSingleResult(
117                                     Globals.getSequenceNextVal().replace("[sequenceName]", "seq_email_sent_log_id"),
118                                     "id");
119
120                     if (sequenceId instanceof Long) {
121                         v_id = new BigDecimal((Long) sequenceId);
122                     } else if (sequenceId instanceof BigDecimal) {
123                         v_id = (BigDecimal) sequenceId;
124                     }
125
126                     schedulerUtil.insertOrUpdate(
127                             "insert into cr_report_email_sent_log (log_id, gen_key, schedule_id, rep_id, user_id, touch_date) values ("
128                                     + v_id + ",'" + v_gen_key + "'," + rs.getInt("schedule_id") + ","
129                                     + rs.getInt("rep_id")
130                                     + ","
131                                     + rs.getInt("user_id") + ", " + Globals.getCurrentDateString() + " )");
132
133                     final int notify_type = rs.getInt("notify_type");
134                     if (notify_type == 4) {
135                         v_r_action = "report.download";
136                     } else if (notify_type == 2) {
137                         v_r_action = "report.download.pdf";
138                     } else if (notify_type == 3) {
139                         v_r_action = "report.csv.download";
140                     } else if (notify_type == 5) {
141                         v_r_action = "report.download.excel2007";
142                     } else if (notify_type == 6) {
143                         v_r_action = "download.all";
144                     }
145
146                     final String v_formfields;
147                     if (rs.getObject("processed_formfields") != null) {
148                         v_formfields = modify_formfields(v_schedule_id, rs.getString("processed_formFields"));
149                     } else {
150                         v_formfields = strip_formfields(v_schedule_id, rs.getString("initial_formfields"));
151                     }
152
153                     final String v_url =
154                             p_system_url + "&r_action=" + v_r_action + "&log_id=" + v_id + "&user_id=" + rs
155                                     .getString("user_id")
156                                     + "&pdfAttachmentKey=" + v_gen_key + "&download_limit=" + rs.getInt("max_row")
157                                     + v_formfields;
158
159                     final boolean v_attach_email_yn = shouldSendAttachmentInEmail(v_schedule_id);
160
161                     final String v_email_msg =
162                             "<html><body><p><b><u><i>" + p_system_name + " System Notification</i></u></b></p>"
163                                     + "<p>Report <b>" + rs.getString("title")
164                                     + "</b> is available for viewing.</p><p>You can view the report if it is attached. </br>"
165                                     + "If it is not attached, or you have problem to open it, you can log into Business Direct and run the report.</p>"
166                                     + "</body></html>";
167
168                     if (rs.getInt("notify_type") != 6) {
169                         sendEmail.sendEmail(p_mail_server, p_sender,
170                                 p_system_name + " System Notification: Report " + rs.getString("title") + " generated",
171                                 v_email_msg, v_url, rs.getInt("notify_type"), v_schedule_id, p_time_interval,
172                                 v_attach_email_yn,
173                                 connectionTimeout);
174
175                     } else {
176                         // may not necessary
177                         schedulerUtil.insertOrUpdate(
178                                 "insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values  ("
179                                         + v_schedule_id + ",'" + v_url + "'," + "'Success: http request began.', "
180                                         + Globals
181                                                 .getCurrentDateString()
182                                         + " )");
183                         schedulerUtil.insertOrUpdate(
184                                 "insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values  ("
185                                         + v_schedule_id + ",'" + v_url + "',"
186                                         + "'Success: http response recieved. Code  resp.status_code '' desc '' resp.reason_phrase', "
187                                         + Globals.getCurrentDateString() + " )");
188                     }
189
190                     schedulerUtil.insertOrUpdate(
191                             "update cr_report_schedule set run_date = " + Globals.getCurrentDateString()
192                                     + " where schedule_id="
193                                     + v_schedule_id);
194
195                     schedulerUtil.insertOrUpdate(
196                             "update cr_report_email_sent_log set sent_date= " + Globals.getCurrentDateString()
197                                     + " , access_flag='N' where log_id=" + v_id);
198                     schedulerUtil.insertOrUpdate(
199                             "insert into cr_schedule_activity_log (SCHEDULE_ID, url, notes, run_time) values ("
200                                     + v_schedule_id
201                                     + ",'" + v_url + "','Success: Email Sent', " + Globals.getCurrentDateString()
202                                     + " )");
203                 }
204             }
205         } catch (final SQLException e) {
206             logger.warn("Failed to open connection", e);
207         }
208     }
209
210     private boolean shouldSendAttachmentInEmail(int v_schedule_id) throws SQLException, ReportSQLException {
211
212         String l_boolean = (String) schedulerUtil.getSingleResult(
213                 "SELECT ATTACHMENT_YN from cr_report_schedule where schedule_id  = " + v_schedule_id, "ATTACHMENT_YN");
214         if ("Y".equals(l_boolean))
215             return true;
216         return false;
217     }
218
219     private String strip_formfields(int v_schedule_id, String p_formfields) throws SQLException, ReportSQLException {
220
221         String v_formfields_insert = "";
222         String v_formfields_generate = "";
223         String v_name = "";
224         String v_value = "";
225
226         String[] column_values = schedulerUtil.cr_dissecturl(p_formfields, "&");
227
228         for (String column_value : column_values) {
229             if (column_value == null || column_value.isEmpty())
230                 continue;
231
232             v_name = column_value.substring(0, column_value.indexOf('='));
233             v_formfields_insert += column_value + "&";
234             v_value = column_value.substring(column_value.indexOf('=') + 1);
235             if (column_value.indexOf("_auto") > 0) {
236                 v_formfields_generate =
237                         v_formfields_generate + v_name.substring(0, v_name.indexOf("_auto")) + "=" + v_value + "&";
238             } else {
239                 v_formfields_generate = v_formfields_generate + column_value + "&";
240             }
241         }
242
243         schedulerUtil.insertOrUpdate("update CR_REPORT_SCHEDULE set processed_formfields ='" + v_formfields_insert
244                 + "' where schedule_id = " + v_schedule_id);
245
246         return v_formfields_generate.substring(0, v_formfields_generate.length());
247
248     }
249
250     private String modify_formfields(int v_schedule_id, String p_formfields) throws SQLException, ReportSQLException {
251
252         class Result {
253
254             String v_formfields_insert = "";
255             String v_formfields_generate = "";
256             String v_name = "";
257             String v_value = "";
258             Date v_date;
259             String v_hour = "";
260             String v_hour_value = "";
261         }
262
263         final Result result = new Result();
264
265         final String v_recurrence = (String) schedulerUtil.getSingleResult(
266                 "select recurrence from cr_report_schedule where schedule_id = " + v_schedule_id, "recurrence");
267
268         String[] column_values = schedulerUtil.cr_dissecturl(p_formfields, "&");
269
270         for (String column_value : column_values) {
271             if (column_value == null)
272                 column_value = "";
273
274             if ("MONTHLY".equals(v_recurrence)) {
275                 if (column_value.indexOf("_auto") > 0) {
276                     result.v_name = column_value.substring(0, column_value.indexOf('='));
277                     result.v_date =
278                             schedulerUtil.to_date(column_value.substring(column_value.indexOf('=') + 1), "mm/dd/yyyy");
279                     result.v_value = schedulerUtil.add_months(result.v_date, 1).toString();
280
281                     if (result.v_name.length() > 0) {
282                         result.v_formfields_insert =
283                                 result.v_formfields_insert + result.v_name + "=" + result.v_value + "&";
284                         result.v_formfields_generate = result.v_formfields_generate
285                                 + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "=" + result.v_value
286                                 + "&";
287                     }
288                 } else {
289                     result.v_formfields_insert = result.v_formfields_insert + column_value + "&";
290                     result.v_formfields_generate = result.v_formfields_generate + column_value + "&";
291                 }
292
293             } else if ("DAILY".equals(v_recurrence)) {
294                 if (column_value.indexOf("_auto") > 0) {
295                     result.v_name = column_value.substring(0, column_value.indexOf('='));
296                     result.v_date =
297                             schedulerUtil.to_date(column_value.substring(column_value.indexOf('=') + 1), "mm/dd/yyyy");
298                     result.v_value = schedulerUtil.add_months(result.v_date, 1).toString();
299
300                     if (result.v_name.length() > 0) {
301                         result.v_formfields_insert =
302                                 result.v_formfields_insert + result.v_name + "=" + result.v_value + "&";
303                         result.v_formfields_generate = result.v_formfields_generate
304                                 + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "=" + result.v_value
305                                 + "&";
306                     }
307                 } else {
308                     result.v_formfields_insert = result.v_formfields_insert + column_value + "&";
309                     result.v_formfields_generate = result.v_formfields_generate + column_value + "&";
310                 }
311
312             } else if ("DAILY_MO_FR".equals(v_recurrence)) {
313                 if (column_value.indexOf("_auto") > 0) {
314                     result.v_name = column_value.substring(0, column_value.indexOf('='));
315                     result.v_date =
316                             schedulerUtil.to_date(column_value.substring(column_value.indexOf('=') + 1), "mm/dd/yyyy");
317                     SimpleDateFormat sdf = new SimpleDateFormat("EEE");
318                     sdf.format(result.v_date);
319                     if ("FRI".equals(result.v_date.toString())) {
320                         result.v_date = schedulerUtil.add_days(result.v_date, 3);
321                     } else if ("SAT".equals(result.v_date.toString())) {
322                         result.v_date = schedulerUtil.add_days(result.v_date, 2);
323                     } else {
324                         result.v_date = schedulerUtil.add_days(result.v_date, 1);
325                     }
326                     result.v_value = result.v_date.toString();
327                     if (result.v_name.length() > 0) {
328                         result.v_formfields_insert =
329                                 result.v_formfields_insert + result.v_name + "=" + result.v_value + "&";
330                         result.v_formfields_generate = result.v_formfields_generate
331                                 + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "=" + result.v_value
332                                 + "&";
333                     }
334
335                 } else {
336                     result.v_formfields_insert = result.v_formfields_insert + column_value + "&";
337                     result.v_formfields_generate = result.v_formfields_generate + column_value + "&";
338                 }
339
340             } else if ("HOURLY".equals(v_recurrence)) {
341
342                 result.v_name =
343                         column_value.indexOf('=') > 0 ? column_value.substring(0, column_value.indexOf('=')) : "";
344                 if (column_value.indexOf("_auto") > 0) {
345
346                     String[] column_values2 = schedulerUtil.cr_dissecturl(p_formfields, "&");
347
348                     for (String column_value2 : column_values2) {
349
350                         String key = column_value2.substring(0, column_value2.indexOf("="));
351                         if (key.equals(result.v_name.substring(0, result.v_name.indexOf("_auto")))
352                                 || key.equals(result.v_name.substring(0, result.v_name.indexOf("_Hr")))) {
353                             result.v_hour = column_value2;
354                         }
355                     }
356
357                     // schedulerUtil.getAndExecute("select c.column_value from table(CR_DISSECTURL(p_formfields)) c
358                     // where substr(c.column_value, 1, instr(c.column_value, '=')-1) = substr(" + result.v_name +
359                     // ",1,instr(" + result.v_name + ",'_auto')-1)||'_Hr'", new Executor() {
360                     //
361                     // @Override
362                     // public void execute(ResultSet rs) throws SQLException {
363                     //
364                     // result.v_hour = rs.getString("column_value");
365                     // }
366                     //
367                     // });
368
369                     if (result.v_hour.length() > 0) {
370                         result.v_hour_value = result.v_hour.substring(result.v_hour.indexOf('=') + 1);
371                     }
372
373                     result.v_date = schedulerUtil.to_date(
374                             column_value.substring(column_value.indexOf('=') + 1) + " " + result.v_hour_value,
375                             "mm/dd/yyyy HH24:MI:SS");
376
377                     result.v_value =
378                             schedulerUtil.to_date_str(schedulerUtil.add_hours(result.v_date, 1), "mm/dd/yyyy HH24");
379
380                     if (result.v_name.length() > 0) {
381                         if (result.v_hour.length() > 0) {
382
383                             result.v_formfields_insert =
384                                     result.v_formfields_insert + result.v_name + "=" + result.v_value.substring(0, 10)
385                                             + "&" + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "_Hr="
386                                             + result.v_value.substring(11, 13);
387                             result.v_formfields_generate = result.v_formfields_generate
388                                     + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "="
389                                     + result.v_value.substring(0, 10) + "&"
390                                     + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "_Hr="
391                                     + result.v_value.substring(11, 13) + "&";
392
393                         } else {
394                             result.v_formfields_insert =
395                                     result.v_formfields_insert + result.v_name + "=" + result.v_value + "&";
396                             result.v_formfields_generate = result.v_formfields_generate
397                                     + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "=" + result.v_value
398                                     + "&";
399                         }
400                     }
401                 }
402                 if (column_value.indexOf("_Hr") <= 0) {
403                     result.v_formfields_insert = result.v_formfields_insert + column_value + "&";
404                     result.v_formfields_generate = result.v_formfields_generate + column_value + "&";
405                 }
406             } else if ("WEEKLY".equals(v_recurrence)) {
407
408                 if (column_value.indexOf("_auto") > 0) {
409                     result.v_name = column_value.substring(0, column_value.indexOf('='));
410                     result.v_date =
411                             schedulerUtil.to_date(column_value.substring(column_value.indexOf('=') + 1), "mm/dd/yyyy");
412                     result.v_value = schedulerUtil.add_days(result.v_date, 7).toString();
413
414                     if (result.v_name.length() > 0) {
415                         result.v_formfields_insert =
416                                 result.v_formfields_insert + result.v_name + "=" + result.v_value + "&";
417                         result.v_formfields_generate = result.v_formfields_generate
418                                 + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "=" + result.v_value
419                                 + "&";
420                     }
421
422                 } else {
423                     result.v_formfields_insert = result.v_formfields_insert + column_value + "&";
424                     result.v_formfields_generate = result.v_formfields_generate + column_value + "&";
425                 }
426
427             } else {
428                 if (column_value.indexOf("_auto") > 0) {
429                     result.v_name = column_value.substring(0, column_value.indexOf('='));
430                     result.v_date =
431                             schedulerUtil.to_date(column_value.substring(column_value.indexOf('=') + 1), "mm/dd/yyyy");
432                     result.v_value = schedulerUtil.add_days(result.v_date, 7).toString();
433                     if (result.v_name.length() > 0) {
434                         result.v_formfields_insert =
435                                 result.v_formfields_insert + result.v_name + "=" + result.v_value + "&";
436                         result.v_formfields_generate = result.v_formfields_generate
437                                 + result.v_name.substring(0, result.v_name.indexOf("_auto")) + "=" + result.v_value
438                                 + "&";
439                     }
440
441                 } else {
442                     result.v_formfields_insert = result.v_formfields_insert + column_value + "&";
443                     result.v_formfields_generate = result.v_formfields_generate + column_value + "&";
444                 }
445             }
446         }
447
448         schedulerUtil.insertOrUpdate("update CR_REPORT_SCHEDULE set processed_formfields ='"
449                 + result.v_formfields_insert + "' where schedule_id =" + v_schedule_id);
450         return "&" + result.v_formfields_generate.substring(0, result.v_formfields_generate.length());
451     }
452
453     private int get_report_sched_offset(int p_rep_id, int p_schedule_id) throws SQLException, ReportSQLException {
454
455         class CrReportSchedule {
456
457             Date run_date;
458             String recurrence;
459         }
460         Date v_last_date = null;
461         Date v_sysdate = new Date();
462
463         final CrReportSchedule v_report_schedule_rec = new CrReportSchedule();
464
465         schedulerUtil.getAndExecute(
466                 "SELECT * FROM cr_report_schedule WHERE rep_id = " + p_rep_id + " and schedule_id = " + p_schedule_id,
467                 new Executor() {
468
469                     @Override
470                     public void execute(ResultSet rs) throws SQLException {
471
472                         v_report_schedule_rec.recurrence = rs.getString("recurrence");
473                         java.sql.Timestamp runDate = rs.getTimestamp("run_date");
474                         v_report_schedule_rec.run_date = new Date(runDate.getTime());
475                     }
476
477                 });
478
479         if (v_report_schedule_rec.run_date == null || v_report_schedule_rec.run_date.compareTo(v_sysdate) > 0) {
480             return Integer.MAX_VALUE;
481         }
482
483         Date v_next_date = v_report_schedule_rec.run_date;
484
485         while (v_next_date.compareTo(v_sysdate) < 0) {
486
487             if ("HOURLY".equals(v_report_schedule_rec.recurrence)) {
488                 v_next_date = SchedulerUtil.add_hours(v_next_date, 1);
489             } else if ("DAILY".equals(v_report_schedule_rec.recurrence)) {
490                 v_next_date = SchedulerUtil.add_days(v_next_date, 1);
491             } else if ("DAILY_MO_FR".equals(v_report_schedule_rec.recurrence)) {
492                 SimpleDateFormat sdf = new SimpleDateFormat("EEE");
493                 sdf.format(v_next_date);
494                 if ("FRI".equals(v_next_date.toString())) {
495                     v_next_date = SchedulerUtil.add_days(v_next_date, 3);
496                 } else if ("SAT".equals(v_next_date.toString())) {
497                     v_next_date = SchedulerUtil.add_days(v_next_date, 2);
498                 } else {
499                     v_next_date = SchedulerUtil.add_days(v_next_date, 1);
500                 }
501             } else if ("WEEKLY".equals(v_report_schedule_rec.recurrence)) {
502                 v_next_date = SchedulerUtil.add_days(v_next_date, 7);
503             } else if ("MONTHLY".equals(v_report_schedule_rec.recurrence)) {
504                 v_next_date = SchedulerUtil.add_months(v_next_date, 1);
505             } else {
506                 break;
507             }
508             v_last_date = v_next_date;
509         }
510
511         if (v_last_date != null
512                 && SchedulerUtil.trunc_hour(v_last_date).compareTo(SchedulerUtil.trunc_hour(v_sysdate)) == 0) {
513             return (int) (Math.abs(v_sysdate.getTime() - v_last_date.getTime()) / 1000);
514         } else {
515             // More than an hour
516             return 3601;
517         }
518     }
519
520     public SchedulerUtil getSchedulerUtil() {
521         return schedulerUtil;
522     }
523
524     public void setSchedulerUtil(SchedulerUtil schedulerUtil) {
525         this.schedulerUtil = schedulerUtil;
526     }
527
528 }