2 * ============LICENSE_START====================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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====================================================
22 package org.onap.aaf.auth.batch.update;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.io.PrintStream;
28 import java.text.ParseException;
29 import java.util.ArrayList;
30 import java.util.Collections;
31 import java.util.Comparator;
32 import java.util.Date;
33 import java.util.HashMap;
34 import java.util.HashSet;
35 import java.util.List;
37 import java.util.Map.Entry;
39 import java.util.TreeMap;
41 import org.onap.aaf.auth.batch.Batch;
42 import org.onap.aaf.auth.batch.BatchPrincipal;
43 import org.onap.aaf.auth.batch.actions.Email;
44 import org.onap.aaf.auth.batch.actions.EmailPrint;
45 import org.onap.aaf.auth.batch.actions.Message;
46 import org.onap.aaf.auth.batch.helpers.Cred;
47 import org.onap.aaf.auth.batch.helpers.NS;
48 import org.onap.aaf.auth.batch.helpers.Notification;
49 import org.onap.aaf.auth.batch.helpers.UserRole;
50 import org.onap.aaf.auth.batch.helpers.Notification.TYPE;
51 import org.onap.aaf.auth.dao.cass.CredDAO;
52 import org.onap.aaf.auth.dao.hl.Question;
53 import org.onap.aaf.auth.env.AuthzTrans;
54 import org.onap.aaf.auth.layer.Result;
55 import org.onap.aaf.auth.org.EmailWarnings;
56 import org.onap.aaf.auth.org.Organization;
57 import org.onap.aaf.auth.org.Organization.Identity;
58 import org.onap.aaf.auth.org.OrganizationException;
59 import org.onap.aaf.auth.org.OrganizationFactory;
60 import org.onap.aaf.cadi.CadiException;
61 import org.onap.aaf.cadi.util.CSV;
62 import org.onap.aaf.misc.env.APIException;
63 import org.onap.aaf.misc.env.Env;
64 import org.onap.aaf.misc.env.TimeTaken;
65 import org.onap.aaf.misc.env.util.Chrono;
68 public class NotifyCredExpiring extends Batch {
70 private static final String UNKNOWN_ID = "unknown@deprecated.id";
71 private static final String AAF_INSTANTIATED_MECHID = "AAF INSTANTIATED MECHID";
72 private static final String EXPIRATION_DATE = "EXPIRATION DATE";
73 private static final String QUICK_LINK = "QUICK LINK TO UPDATE PAGE";
74 private static final String DASH_1 = "-----------------------";
75 private static final String DASH_2 = "---------------";
76 private static final String DASH_3 = "----------------------------------------------------";
77 private static final String LINE = "\n----------------------------------------------------------------";
79 private int maxEmails;
80 private final PrintStream ps;
81 private final AuthzTrans noAvg;
82 private String supportEmailAddr;
84 private CSVInfo csvInfo;
86 public NotifyCredExpiring(AuthzTrans trans) throws APIException, IOException, OrganizationException {
88 TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE);
90 session = cluster.connect();
95 noAvg = env.newTransNoAvg();
96 noAvg.setUser(new BatchPrincipal("batch:NotifyCredExpiring"));
99 email = new EmailPrint();
101 maxEmails = Integer.parseInt(trans.getProperty("MAX_EMAILS","3"));
104 maxEmails = Integer.parseInt(trans.getProperty("MAX_EMAILS","3"));
107 email.subject("AAF Password Expiration Notification (ENV: %s)",batchEnv);
108 email.preamble("AAF (MOTS 22830) is the AT&T Authorization System used by many AT&T Tools and Applications.\n\n" +
109 " The following Credentials are expiring on the dates shown. Failure to act before the expiration date "
110 + "will cause your App's Authentications to fail.\n");
111 email.signature("Sincerely,\nAAF Team (Our MOTS# 22830)\n"
112 + "https://wiki.web.att.com/display/aaf/Contact+Us\n"
113 + "(Use 'Other Misc Requests (TOPS)')");
115 boolean quit = false;
116 if(args().length<1) {
117 System.err.println("Need CSV formatted Expiring Report");
120 File f = new File(logDir(),args()[0]);
121 System.out.println("Reading " + f.getCanonicalPath());
125 if(args().length<2) {
126 System.err.println("Need Email Template");
133 csvInfo = new CSVInfo(System.err);
136 } catch (CadiException e) {
137 throw new APIException(e);
140 Notification.load(trans, session, Notification.v2_0_18);
142 ps = new PrintStream(new FileOutputStream(logDir() + "/email"+Chrono.dateOnlyStamp()+".log",true));
143 ps.printf("### Approval Notify %s for %s%s\n",Chrono.dateTime(),batchEnv,dryRun?", DryRun":"");
147 protected void run(AuthzTrans trans) {
150 Map<String,List<LastCred>> ownerCreds = new TreeMap<>();
153 List<LastCred> noOwner = new ArrayList<>();
154 ownerCreds.put(UNKNOWN_ID,noOwner);
157 // // Get a list of ONLY the ones needing email by Owner
158 // for (Entry<String, List<Cred>> es : Cred.byNS.entrySet()) {
159 // for (Cred c : es.getValue()) {
160 // List<UserRole> ownerURList = UserRole.getByRole().get(es.getKey()+".owner");
161 // if (ownerURList!=null) {
162 // for (UserRole ur:ownerURList) {
163 // String owner = ur.user();
164 // List<LastCred> llc = ownerCreds.get(owner);
166 // ownerCreds.put(owner, (llc=new ArrayList<>()));
168 // llc.add(new LastCred(c,last));
171 // noOwner.add(new LastCred(c,last));
176 // boolean bCritical,bNormal,bEarly;
177 // Message msg = new Message();
178 // Notification ownNotf;
179 // StringBuilder logMessage = new StringBuilder();
180 // for (Entry<String,List<LastCred>> es : ownerCreds.entrySet()) {
181 // String owner = es.getKey();
182 // boolean header = true;
184 // Organization org = OrganizationFactory.obtain(env, owner);
185 // Identity user = org.getIdentity(noAvg, owner);
186 // if (!UNKNOWN_ID.equals(owner) && user==null) {
187 // ps.printf("Invalid Identity: %s\n", owner);
189 // logMessage.setLength(0);
190 // if (maxEmails>emailCount) {
191 // bCritical=bNormal=bEarly = false;
194 // email.addTo(user==null?supportEmailAddr:user.email());
196 // ownNotf = Notification.get(es.getKey(),TYPE.CN);
197 // if (ownNotf==null) {
198 // ownNotf = Notification.create(user==null?UNKNOWN_ID:user.fullID(), TYPE.CN);
200 // last = ownNotf.last;
201 // // Get Max ID size for formatting purposes
202 // int length = AAF_INSTANTIATED_MECHID.length();
203 // for (LastCred lc : es.getValue()) {
204 // length = Math.max(length, lc.cred.id.length());
206 // String id_exp_fmt = "\t%-"+length+"s %15s %s";
208 // Collections.sort(es.getValue(),LastCred.COMPARE);
209 // for (LastCred lc : es.getValue()) {
210 // if (lc.last.after(must) && lc.last.before(early) &&
211 // (ownNotf.last==null || ownNotf.last.before(withinLastWeek))) {
212 // if (!bEarly && header) {
213 // msg.line("\tThe following are friendly 2 month reminders, just in case you need to schedule your updates early. "
214 // + "You will be reminded next month\n");
215 // msg.line(id_exp_fmt, AAF_INSTANTIATED_MECHID,EXPIRATION_DATE, QUICK_LINK);
216 // msg.line(id_exp_fmt, DASH_1, DASH_2, DASH_3);
220 // } else if (lc.last.after(critical) && lc.last.before(must) &&
221 // (ownNotf.last==null || ownNotf.last.before(withinLastWeek))) {
223 // boolean last2wks = lc.last.before(within2Weeks);
226 // Identity supvsr = user.responsibleTo();
227 // email.addCC(supvsr.email());
228 // } catch (OrganizationException e) {
229 // trans.error().log(e, "Supervisor cannot be looked up");
233 // msg.line("\tIt is now important for you to update Passwords all all configurations using them for the following.\n" +
234 // (last2wks?"\tNote: Your Supervisor is CCd\n":"\tNote: Your Supervisor will be notified if this is not being done before the last 2 weeks\n"));
235 // msg.line(id_exp_fmt, AAF_INSTANTIATED_MECHID,EXPIRATION_DATE, QUICK_LINK);
236 // msg.line(id_exp_fmt, DASH_1, DASH_2, DASH_3);
241 // } else if (lc.last.after(tooLate) && lc.last.before(critical)) { // Email Every Day, with Supervisor
242 // if (!bCritical && header) {
243 // msg.line("\t!!! WARNING: These Credentials will expire in LESS THAN ONE WEEK !!!!\n" +
244 // "\tYour supervisor is added to this Email\n");
245 // msg.line(id_exp_fmt, AAF_INSTANTIATED_MECHID,EXPIRATION_DATE, QUICK_LINK);
246 // msg.line(id_exp_fmt, DASH_1, DASH_2, DASH_3);
252 // Identity supvsr = user.responsibleTo();
253 // if (supvsr!=null) {
254 // email.addCC(supvsr.email());
255 // supvsr = supvsr.responsibleTo();
256 // if (supvsr!=null) {
257 // email.addCC(supvsr.email());
261 // } catch (OrganizationException e) {
262 // trans.error().log(e, "Supervisor cannot be looked up");
265 // if (bEarly || bNormal || bCritical) {
266 // if (logMessage.length()==0) {
267 // logMessage.append("NotifyCredExpiring");
269 // logMessage.append("\n\t");
270 // logMessage.append(lc.cred.id);
271 // logMessage.append('\t');
272 // logMessage.append(Chrono.dateOnlyStamp(lc.last));
273 // msg.line(id_exp_fmt, lc.cred.id, Chrono.dateOnlyStamp(lc.last)+" ",env.getProperty(GUI_URL)+"/creddetail?ns="+Question.domain2ns(lc.cred.id));
277 // if (bEarly || bNormal || bCritical) {
279 // msg.line("Why are you receiving this Notification?\n");
280 // msg.line("You are the listed owner of one or more AAF Namespaces. ASPR requires that those responsible for "
281 // + "applications and their access review them regularly for accuracy. The AAF WIKI page for AT&T is https://wiki.web.att.com/display/aaf. "
282 // + "You might like https://wiki.web.att.com/display/aaf/AAF+in+a+Nutshell. More detailed info regarding questions of being a Namespace Owner is available at https://wiki.web.att.com/pages/viewpage.action?pageId=594741363\n");
283 // msg.line("You may view the Namespaces you listed as Owner for in this AAF Env by viewing the following webpage:\n");
284 // msg.line(" %s/ns\n\n",env.getProperty(GUI_URL));
286 // Result<Void> rv = email.exec(trans, org,"");
289 // if (!isDryRun()) {
290 // ownNotf.update(noAvg, session, false);
291 // // SET LastNotification
293 // email.log(ps,logMessage.toString());
295 // trans.error().log(rv.errorString());
300 // } catch (OrganizationException e) {
301 // trans.info().log(e);
304 trans.info().printf("%d emails sent for %s", emailCount,batchEnv);
308 private static class CSVInfo implements CSV.Visitor {
309 private PrintStream out;
310 private Set<String> unsupported;
311 private NotifyCredVisitor credv;
312 private List<LastCred> llc;
314 public CSVInfo(PrintStream out) {
316 credv = new NotifyCredVisitor(llc = new ArrayList<>());
320 public void visit(List<String> row) throws IOException, CadiException {
323 case NotifyCredVisitor.SUPPORTS:
327 if(unsupported==null) {
328 unsupported = new HashSet<String>();
330 if(!unsupported.contains(row.get(0))) {
331 unsupported.add(row.get(0));
332 out.println("Unsupported Type: " + row.get(0));
338 private static class Contact {
339 public List<String> contacts;
340 private List<UserRole> owners;
342 public Contact(final String ns) {
343 contacts = new ArrayList<>();
347 public void loadFromNS(final String ns) {
348 owners = UserRole.getByRole().get(ns+".owner");
352 private static class LastCred extends Contact {
353 public final String id;
354 public final int type;
355 public final Date expires;
357 public LastCred(final String id, final String ns, final int type, final Date expires) {
361 this.expires = expires;
365 private static class NotifyCredVisitor implements CSV.Visitor {
366 public static final String SUPPORTS = "cred";
367 private final List<LastCred> lastCred;
369 public NotifyCredVisitor(final List<LastCred> lastCred) {
370 this.lastCred = lastCred;
374 public void visit(List<String> row) throws IOException, CadiException {
376 lastCred.add(new LastCred(
379 Integer.parseInt(row.get(3)),
380 Chrono.dateOnlyFmt.parse(row.get(4))
383 } catch (NumberFormatException | ParseException e) {
384 throw new CadiException(e);
390 protected void _close(AuthzTrans trans) {