e84df37bc6b1c39dd5523388d69ab9dfa6d92801
[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.File;
25 import java.io.FileInputStream;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.PrintStream;
29 import java.util.HashMap;
30 import java.util.List;
31 import java.util.Map;
32
33 import org.onap.aaf.auth.batch.Batch;
34 import org.onap.aaf.auth.batch.helpers.NS;
35 import org.onap.aaf.auth.batch.helpers.UserRole;
36 import org.onap.aaf.auth.env.AuthzTrans;
37 import org.onap.aaf.auth.org.Organization;
38 import org.onap.aaf.auth.org.Organization.Identity;
39 import org.onap.aaf.auth.org.OrganizationException;
40 import org.onap.aaf.cadi.util.CSV;
41 import org.onap.aaf.misc.env.APIException;
42 import org.onap.aaf.misc.env.Env;
43 import org.onap.aaf.misc.env.TimeTaken;
44
45 import com.datastax.driver.core.ResultSet;
46 import com.datastax.driver.core.SimpleStatement;
47 import com.datastax.driver.core.Statement;
48
49 public class MassMail extends Batch {
50
51         private Map<String, CSV.Writer> writerList;
52         private final String from;
53         private String subject = "AAF Information";
54         private boolean bOwners = true;
55         private boolean bAdmins = false;
56         private boolean bAppIDOnly = false;
57         private int escalate = 0;
58         private final File subdir;
59         private final String head;
60         private final String content;
61         private final String tail;
62
63         public MassMail(AuthzTrans trans) throws APIException, IOException, OrganizationException {
64                 super(trans.env());
65                 from = trans.getProperty("MAIL_FROM");
66                 if (from == null) {
67                         throw new APIException("No MAIL_FROM property set");
68                 }
69                 String subdirName = null;
70                 // Flags
71                 for (String arg : args()) {
72                         switch (arg) {
73                         case "-owners":
74                                 bOwners = true;
75                                 break;
76                         case "-admins":
77                                 bAdmins = true;
78                                 break;
79                         case "-appid_only":
80                                 bAppIDOnly = true;
81                                 break;
82                         default:
83                                 if (arg.length() > 10 && arg.startsWith("-escalate=")) {
84                                         escalate = Integer.parseInt(arg.substring(10));
85                                 } else if (subdirName == null) {
86                                         subdirName = arg;
87                                 }
88                         }
89                 }
90
91                 subdir = new File(logDir(), subdirName == null ? "mailing" : subdirName);
92                 if (subdir.exists()) {
93                         if (!subdir.isDirectory()) {
94                                 throw new APIException(subdirName + " is not a directory");
95                         }
96                 } else {
97                         subdir.mkdirs();
98                 }
99
100                 subject = readIn(subdir, "subject");
101                 if(subject==null) {
102                         throw new IOException("MassMail needs a 'subject' file in your mailing directory");
103                 } else {
104                         subject = subject.replace("%ENV%", batchEnv);
105                 }
106                 String temp = readIn(subdir, "html.head");
107                 if(temp==null) {
108                         File f = new File(trans.getProperty("HEADER_HTML"));
109                         if(!f.exists()) {
110                                 throw new IOException("No 'html.head' found in mailing dir, or default HEADER_HTML property");
111                         }
112                         temp = readIn(f.getParentFile(),f.getName());
113                 }
114                 head = temp;
115                 
116                 content = readIn(subdir,"html.content");
117                 temp = readIn(subdir,"html.tail");
118                 if(temp==null) {
119                         File f = new File(trans.getProperty("FOOTER_HTML"));
120                         if(!f.exists()) {
121                                 throw new IOException("No 'html.tail' found in mailing dir, or default FOOTER_HTML property");
122                         }
123                         temp = readIn(f.getParentFile(),f.getName());
124                 }
125                 tail = temp;
126                 
127                 trans.info().log("Starting Connection Process");
128                 TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB);
129                 try {
130                         TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE);
131                         try {
132                                 session = cluster.connect();
133                         } finally {
134                                 tt.done();
135                         }
136
137                         // Create Intermediate Output
138                         writerList = new HashMap<>();
139
140                         NS.load(trans, session, NS.v2_0_11);
141                         UserRole.load(trans, session, UserRole.v2_0_11);
142                 } finally {
143                         tt0.done();
144                 }
145         }
146
147         private String readIn(File subdir, String name) throws IOException {
148                 File file = new File(subdir, name);
149                 if(file.exists()) {
150                         byte[] bytes = new byte[(int) file.length()];
151                         FileInputStream fis = new FileInputStream(file);
152                         try {
153                                 fis.read(bytes);
154                                 return new String(bytes);
155                         } finally {
156                                 fis.close();
157                         }
158                 } else {
159                         return null;
160                 }
161         }
162
163         @Override
164         protected void run(AuthzTrans trans) {
165                 trans.info().log("Create a Mass Mailing");
166
167                 final AuthzTrans transNoAvg = trans.env().newTransNoAvg();
168                 final Organization org = trans.org();
169                 if (org != null) {
170                         StringBuilder to = new StringBuilder();
171                         StringBuilder cc = new StringBuilder();
172                         StringBuilder greet = new StringBuilder();
173                         for (NS ns : NS.data.values()) {
174                                 if (bAppIDOnly) {
175                                         ResultSet results;
176                                         Statement stmt = new SimpleStatement(
177                                                         String.format("SELECT count(*) FROM authz.cred WHERE ns='%s';", ns.ndd.name));
178                                         results = session.execute(stmt);
179                                         long count = results.one().getLong(0);
180                                         if (count <= 0) {
181                                                 continue;
182                                         }
183                                 }
184
185                                 to.setLength(0);
186                                 cc.setLength(0);
187                                 greet.setLength(0);
188                                 if (bOwners) {
189                                         StringBuilder o = to;
190                                         List<UserRole> owners = UserRole.getByRole().get(ns.ndd.name + ".owner");
191                                         if (owners==null || owners.isEmpty()) {
192                                                 trans.error().log(ns.ndd.name, "has no owners!");
193                                         } else {
194                                                 for (UserRole owner : owners) {
195                                                         try {
196                                                                 Identity identity = org.getIdentity(transNoAvg, owner.user());
197                                                                 if(identity==null) {
198                                                                         trans.error().log(owner.user() + " is not a valid Identity in " + org.getName());
199                                                                 } else if (identity.isPerson()) {
200                                                                         if (o.length() > 0) {
201                                                                                 o.append(',');
202                                                                                 greet.append(',');
203                                                                         }
204                                                                         o.append(identity.email());
205                                                                         greet.append(identity.firstName());
206                                                                         for (int i = 0; i < escalate; ++i) {
207                                                                                 identity = identity.responsibleTo();
208                                                                                 if (identity == null) {
209                                                                                         break;
210                                                                                 }
211                                                                                 if (cc.length() > 0) {
212                                                                                         cc.append(',');
213                                                                                 }
214                                                                                 cc.append(identity.email());
215                                                                         }
216                                                                 }
217                                                         } catch (OrganizationException e) {
218                                                                 trans.error().log(e, "Error Reading Organization");
219                                                         }
220                                                 }
221                                         }
222                                 }
223
224                                 if (bAdmins) {
225                                         StringBuilder a;
226                                         if ( bOwners && to.length()>0 ) {
227                                                 a = cc;
228                                         } else {
229                                                 a = to;
230                                         }
231                                         List<UserRole> admins = UserRole.getByRole().get(ns.ndd.name + ".admin");
232                                         if (admins==null || admins.isEmpty()) {
233                                                 trans.warn().log(ns.ndd.name, "has no admins!");
234                                         } else {
235                                                 for (UserRole admin : admins) {
236                                                         if(to.indexOf(admin.user())>0) {
237                                                                 continue;
238                                                         }
239                                                         try {
240                                                                 Identity identity = org.getIdentity(transNoAvg, admin.user());
241                                                                 if(identity==null) {
242                                                                         trans.error().log(admin.user() + " is not a valid Identity in " + org.getName());
243                                                                 } else if (identity.isPerson()) {
244                                                                         if (a.length() > 0) {
245                                                                                 a.append(',');
246                                                                         }
247                                                                         a.append(identity.email());
248                                                                         if (!bOwners) {
249                                                                                 if (greet.length() > 0) {
250                                                                                         greet.append(',');
251                                                                                 }
252                                                                                 greet.append(identity.firstName());
253                                                                         }
254                                                                 }
255                                                         } catch (OrganizationException e) {
256                                                                 trans.error().log(e, "Error Reading Organization");
257                                                         }
258                                                 }
259                                         }
260                                 }
261
262                                 try {
263                                         PrintStream ps = new PrintStream(new FileOutputStream(
264                                                         subdir.getPath() + File.separatorChar + "email_" + ns.ndd.name + ".hdr"));
265                                         try {
266                                                 ps.print("TO: ");
267                                                 ps.println(to);
268                                                 ps.print("CC: ");
269                                                 ps.println(cc);
270                                                 ps.print("FROM: ");
271                                                 ps.println(from);
272                                                 ps.print("SUBJECT: ");
273                                                 ps.println(subject);
274                                         } finally {
275                                                 ps.close();
276                                         }
277                                         
278                                         ps = new PrintStream(new FileOutputStream(
279                                                         subdir.getPath() + File.separatorChar + "email_" + ns.ndd.name + ".html"));
280                                         try {
281                                                 ps.println(head.replaceAll("%FIRST_NAMES%", greet.toString()));
282                                                 ps.println(content.replaceAll("%NS%", ns.ndd.name));
283                                                 ps.println(tail);
284                                         } finally {
285                                                 ps.close();
286                                         }
287
288                                 } catch (IOException e) {
289                                         trans.error().log(e);
290                                 }
291
292                         }
293                 }
294         }
295
296         @Override
297         protected void _close(AuthzTrans trans) {
298                 session.close();
299                 for (CSV.Writer cw : writerList.values()) {
300                         cw.close();
301                 }
302         }
303
304 }