Add a MassMail Batch Program
[aaf/authz.git] / auth / auth-batch / src / main / java / org / onap / aaf / auth / batch / reports / MassMail.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
4  * ===========================================================================
5  * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6  * ===========================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END====================================================
19  *
20  */
21
22 package org.onap.aaf.auth.batch.reports;
23
24 import java.io.BufferedReader;
25 import java.io.File;
26 import java.io.FileInputStream;
27 import java.io.FileOutputStream;
28 import java.io.FileReader;
29 import java.io.IOException;
30 import java.io.PrintStream;
31 import java.util.HashMap;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Properties;
35
36 import org.onap.aaf.auth.batch.Batch;
37 import org.onap.aaf.auth.batch.helpers.NS;
38 import org.onap.aaf.auth.batch.helpers.UserRole;
39 import org.onap.aaf.auth.env.AuthzTrans;
40 import org.onap.aaf.auth.org.Organization;
41 import org.onap.aaf.auth.org.Organization.Identity;
42 import org.onap.aaf.auth.org.OrganizationException;
43 import org.onap.aaf.cadi.util.CSV;
44 import org.onap.aaf.misc.env.APIException;
45 import org.onap.aaf.misc.env.Env;
46 import org.onap.aaf.misc.env.TimeTaken;
47
48 import com.datastax.driver.core.ResultSet;
49 import com.datastax.driver.core.SimpleStatement;
50 import com.datastax.driver.core.Statement;
51
52 public class MassMail extends Batch {
53
54         private Map<String, CSV.Writer> writerList;
55         private final String from;
56         private String subject = "AAF Information";
57         private boolean bOwners = true;
58         private boolean bAdmins = false;
59         private boolean bAppIDOnly = false;
60         private int escalate = 0;
61         private final File subdir;
62         private final String head;
63         private final String content;
64         private final String tail;
65
66         public MassMail(AuthzTrans trans) throws APIException, IOException, OrganizationException {
67                 super(trans.env());
68                 from = trans.getProperty("MAIL_FROM");
69                 if (from == null) {
70                         throw new APIException("No MAIL_FROM property set");
71                 }
72                 String subdirName = null;
73                 // Flags
74                 for (String arg : args()) {
75                         switch (arg) {
76                         case "-owners":
77                                 bOwners = true;
78                                 break;
79                         case "-admins":
80                                 bAdmins = true;
81                                 break;
82                         case "-appid_only":
83                                 bAppIDOnly = true;
84                                 break;
85                         default:
86                                 if (arg.length() > 10 && arg.startsWith("-escalate=")) {
87                                         escalate = Integer.parseInt(arg.substring(10));
88                                 } else if (subdirName == null) {
89                                         subdirName = arg;
90                                 }
91                         }
92                 }
93
94                 subdir = new File(logDir(), subdirName == null ? "mailing" : subdirName);
95                 if (subdir.exists()) {
96                         if (!subdir.isDirectory()) {
97                                 throw new APIException(subdirName + " is not a directory");
98                         }
99                 } else {
100                         subdir.mkdirs();
101                 }
102
103                 subject = readIn(subdir, "subject");
104                 head = readIn(subdir, "html.head");
105                 content = readIn(subdir,"html.content");
106                 tail = readIn(subdir,"html.tail");
107                 
108                 trans.info().log("Starting Connection Process");
109                 TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB);
110                 try {
111                         TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE);
112                         try {
113                                 session = cluster.connect();
114                         } finally {
115                                 tt.done();
116                         }
117
118                         // Create Intermediate Output
119                         writerList = new HashMap<>();
120
121                         NS.load(trans, session, NS.v2_0_11);
122                         UserRole.load(trans, session, UserRole.v2_0_11);
123 //            now = new Date();
124 //            String sdate = Chrono.dateOnlyStamp(now);
125                 } finally {
126                         tt0.done();
127                 }
128         }
129
130         private String readIn(File subdir, String name) throws IOException {
131                 File file = new File(subdir, name);
132                 byte[] bytes = new byte[(int) file.length()];
133                 FileInputStream fis = new FileInputStream(file);
134                 try {
135                         fis.read(bytes);
136                         return new String(bytes);
137                 } finally {
138                         fis.close();
139                 }
140         }
141
142         @Override
143         protected void run(AuthzTrans trans) {
144 //        try {
145                 trans.info().log("Create a Mass Mailing");
146
147                 final AuthzTrans transNoAvg = trans.env().newTransNoAvg();
148                 final Organization org = trans.org();
149                 if (org != null) {
150                         StringBuilder to = new StringBuilder();
151                         StringBuilder cc = new StringBuilder();
152                         StringBuilder greet = new StringBuilder();
153                         for (NS ns : NS.data.values()) {
154                                 if (bAppIDOnly) {
155                                         ResultSet results;
156                                         Statement stmt = new SimpleStatement(
157                                                         String.format("SELECT count(*) FROM authz.cred WHERE ns='%s';", ns.ndd.name));
158                                         results = session.execute(stmt);
159                                         long count = results.one().getLong(0);
160                                         if (count <= 0) {
161                                                 continue;
162                                         }
163                                 }
164
165                                 to.setLength(0);
166                                 cc.setLength(0);
167                                 greet.setLength(0);
168                                 if (bOwners) {
169                                         StringBuilder o = to;
170                                         List<UserRole> owners = UserRole.getByRole().get(ns.ndd.name + ".owner");
171                                         if (owners.isEmpty()) {
172                                                 trans.error().log(ns.ndd.name, "has no owners!");
173                                         } else {
174                                                 for (UserRole owner : owners) {
175                                                         try {
176                                                                 Identity identity = org.getIdentity(transNoAvg, owner.user());
177                                                                 if (identity.isPerson()) {
178                                                                         if (o.length() > 0) {
179                                                                                 o.append(',');
180                                                                                 greet.append(',');
181                                                                         }
182                                                                         o.append(identity.email());
183                                                                         greet.append(identity.firstName());
184                                                                         for (int i = 0; i < escalate; ++i) {
185                                                                                 identity = identity.responsibleTo();
186                                                                                 if (identity == null) {
187                                                                                         break;
188                                                                                 }
189                                                                                 if (cc.length() > 0) {
190                                                                                         cc.append(',');
191                                                                                 }
192                                                                                 cc.append(identity.email());
193                                                                         }
194                                                                 }
195                                                         } catch (OrganizationException e) {
196                                                                 trans.error().log(e, "Error Reading Organization");
197                                                         }
198                                                 }
199                                         }
200                                 }
201
202                                 if (bAdmins) {
203                                         StringBuilder a;
204                                         if (bOwners) {
205                                                 a = cc;
206                                         } else {
207                                                 a = to;
208                                         }
209                                         List<UserRole> admins = UserRole.getByRole().get(ns.ndd.name + ".admin");
210                                         if (admins.isEmpty()) {
211                                                 trans.warn().log(ns.ndd.name, "has no admins!");
212                                         } else {
213                                                 for (UserRole admin : admins) {
214                                                         try {
215                                                                 Identity identity = org.getIdentity(transNoAvg, admin.user());
216                                                                 if (identity.isPerson()) {
217                                                                         if (a.length() > 0) {
218                                                                                 a.append(',');
219                                                                         }
220                                                                         a.append(identity.email());
221                                                                         if (!bOwners) {
222                                                                                 if (greet.length() > 0) {
223                                                                                         greet.append(',');
224                                                                                 }
225                                                                                 greet.append(identity.firstName());
226                                                                         }
227                                                                 }
228                                                         } catch (OrganizationException e) {
229                                                                 trans.error().log(e, "Error Reading Organization");
230                                                         }
231                                                 }
232                                         }
233                                 }
234
235                                 try {
236                                         PrintStream ps = new PrintStream(new FileOutputStream(
237                                                         subdir.getPath() + File.separatorChar + "email_" + ns.ndd.name + ".hdr"));
238                                         try {
239                                                 ps.print("TO: ");
240                                                 ps.println(to);
241                                                 ps.print("CC: ");
242                                                 ps.println(cc);
243                                                 ps.print("FROM: ");
244                                                 ps.println(from);
245                                                 ps.print("SUBJECT: ");
246                                                 ps.println(subject);
247                                         } finally {
248                                                 ps.close();
249                                         }
250                                         
251                                         ps = new PrintStream(new FileOutputStream(
252                                                         subdir.getPath() + File.separatorChar + "email_" + ns.ndd.name + ".html"));
253                                         try {
254                                                 ps.println(head.replaceAll("%FIRST_NAMES%", greet.toString()));
255                                                 ps.println(content.replaceAll("%NS%", ns.ndd.name));
256                                                 ps.println(tail);
257                                         } finally {
258                                                 ps.close();
259                                         }
260                                 } catch (IOException e) {
261                                         trans.error().log(e);
262                                 }
263
264                         }
265 //              UserRole.load(transNoAvg, session, UserRole.v2_0_11, ur -> {
266 //                      if("owner".equals(ur.rname())) {
267 //                              try {
268 //                                                      Identity identity = org.getIdentity(transNoAvg, ur.user());
269 //                                                      if(identity.isPerson()) {
270 //                                                              System.out.println("Emailing " + identity.email());
271 //                                                      }
272 //                                              } catch (OrganizationException e) {
273 //                                  trans.error().log(e, "Error Reading Organization");
274 //                                              }
275 //                      }
276 //                    Organization org = trans.org();
277 //                        Identity identity = org.getIdentity(trans, ur.row);
278 //
279 //                    if(!check(transNoAvg, checked, ur.user())) {
280 //                        ur.row(whichWriter(transNoAvg,ur.user()),UserRole.UR);
281 //                    }
282 //                } catch (OrganizationException e) {
283 //                    trans.error().log(e, "Error Decrypting X509");
284 //                }
285 //              });
286                 }
287
288 //        } catch (OrganizationException e) {
289 //            trans.info().log(e);
290
291         }
292
293         @Override
294         protected void _close(AuthzTrans trans) {
295                 session.close();
296                 for (CSV.Writer cw : writerList.values()) {
297                         cw.close();
298                 }
299         }
300
301 }