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