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