Batch, Remove unneeded Classes, refine, etc
[aaf/authz.git] / auth / auth-batch / src / main / java / org / onap / aaf / auth / batch / reports / bodies / NotifyBody.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 package org.onap.aaf.auth.batch.reports.bodies;
22
23 import java.io.File;
24 import java.io.IOException;
25 import java.lang.reflect.Constructor;
26 import java.lang.reflect.InvocationTargetException;
27 import java.lang.reflect.Modifier;
28 import java.net.URISyntaxException;
29 import java.net.URL;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Enumeration;
33 import java.util.HashMap;
34 import java.util.HashSet;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Set;
38 import java.util.TreeMap;
39 import java.util.jar.JarEntry;
40 import java.util.jar.JarFile;
41
42 import org.onap.aaf.auth.batch.helpers.LastNotified;
43 import org.onap.aaf.auth.batch.reports.Notify;
44 import org.onap.aaf.auth.env.AuthzTrans;
45 import org.onap.aaf.cadi.Access;
46 import org.onap.aaf.misc.env.APIException;
47
48 public abstract class NotifyBody {
49         private static final String DUPL = "<td style=\"text-indent: 4em;\">''</td>";
50         private static final Map<String,NotifyBody> bodyMap = new HashMap<>();
51
52         protected Map<String,List<List<String>>> rows;
53         protected final String env;
54         protected final String gui_url;
55         
56         private final String name;
57         private final String type;
58         private String date;
59         private int escalation;
60         private int count;
61         
62         public NotifyBody(Access access, final String type, final String name) {
63                 rows = new TreeMap<>();
64                 this.name = name;
65                 this.type = type;
66                 date="";
67                 escalation = 1;
68                 count = 0;
69                 env = access.getProperty("CASS_ENV","DEVL");
70                 gui_url = access.getProperty("GUI_URL", "");
71         }
72         
73         public void store(List<String> row) {
74                 if(!row.isEmpty()) {
75                         if("info".equals(row.get(0))) {
76                                 if(row.size()>2) {
77                                         date = row.get(2);
78                                 }
79                                 if(row.size()>3) {
80                                         escalation = Integer.parseInt(row.get(3));
81                                 }
82                                 return;
83                         } else if(type.equals(row.get(0))) {
84                                 String user = user(row);
85                                 if(user!=null) {
86                                         List<List<String>> lss = rows.get(user); 
87                                         if(lss == null) {
88                                                 lss = new ArrayList<>();
89                                                 rows.put(user,lss);
90                                         }
91                                         lss.add(row);
92                                 }
93                         }
94                 }
95         }
96
97         public String name() {
98                 return name;
99         }
100         
101         public String type() {
102                 return type;
103         }
104         
105         public String date() {
106                 return date;
107         }
108         public int escalation() {
109                 return escalation;
110         }
111         
112         public Set<String> users() {
113                 return rows.keySet();
114         }
115         
116         /**
117          * ID must be set from Row for Email lookup
118          * 
119          * @param trans
120          * @param n
121          * @param id
122          * @param row
123          * @return
124          */
125         public abstract boolean body(AuthzTrans trans, StringBuilder sb, int indent, Notify n, String id);
126         
127         /**
128          * Return "null" if user not found in row... Code will handle.
129          * @param row
130          * @return
131          */
132         protected abstract String user(List<String> row);
133         
134         /**
135          * Provide a context-sensitive Subject, which includes ENV as well as details
136          * 
137          * @return
138          */
139         public abstract String subject();
140
141         /**
142          * Record the fact that a particular Notification was marked as "sent" by Emailer.
143          * 
144          * @param trans
145          * @param approver
146          * @param ln
147          */
148         public abstract void record(AuthzTrans trans, StringBuilder query, String id, List<String> notified, LastNotified ln);
149         
150         /**
151          * Get Notify Body based on key of
152          * type|name
153          */
154         public static NotifyBody get(String key) {
155                 return bodyMap.get(key);
156         }
157         
158         /**
159          * Return set of loaded NotifyBodies
160          * 
161          */
162         public static Collection<NotifyBody> getAll() {
163                 // Note: The same Notify Body is entered several times with different keys.
164                 // Therefore, need a Set of Values, not all the Values.
165                 Set<NotifyBody> set = new HashSet<>();
166                 set.addAll(bodyMap.values());
167                 return set;
168         }
169         
170         /**
171          * @param propAccess 
172          * @throws URISyntaxException 
173          * 
174          */
175         public static void load(Access access) throws APIException, IOException {
176                 // class load available NotifyBodies
177                 ClassLoader cl = Thread.currentThread().getContextClassLoader();
178                 Package pkg = NotifyBody.class.getPackage();
179                 String path = pkg.getName().replace('.', '/');
180                 URL url = cl.getResource(path);
181                 List<String> classNames = new ArrayList<>();
182                 String urlString = url.toString();
183                 if(urlString.startsWith("jar:file:")) {
184                         int exclam = urlString.lastIndexOf('!');
185                         JarFile jf = new JarFile(urlString.substring(9,exclam));
186                         try {
187                                 Enumeration<JarEntry> jfe = jf.entries();
188                                 while(jfe.hasMoreElements()) {
189                                         String name = jfe.nextElement().getName();
190                                         if(name.startsWith(path) && name.endsWith(".class")) {
191                                                 classNames.add(name.substring(0,name.length()-6).replace('/', '.'));
192                                         }
193                                 }
194                         } finally {
195                                 jf.close();
196                         }
197                 } else {
198                         File dir = new File(url.getFile());
199                         for( String f : dir.list()) {
200                                 if(f.endsWith(".class")) {
201                                         classNames.add(pkg.getName()+'.'+f.substring(0,f.length()-6));
202                                 }
203                         }
204                 }
205                 for(String cls : classNames) {
206                         try {
207                                 Class<?> c = cl.loadClass(cls);
208                                 if(c!=null) {
209                                         if(!Modifier.isAbstract(c.getModifiers())) {
210                                                 Constructor<?> cst = c.getConstructor(Access.class);
211                                                 NotifyBody nb = (NotifyBody)cst.newInstance(access);
212                                                 if(nb!=null) {
213                                                         bodyMap.put("info|"+nb.name, nb);
214                                                         bodyMap.put(nb.type+'|'+nb.name, nb);
215                                                 }
216                                         }
217                                 }
218                         } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
219                                 e.printStackTrace();
220                         }
221                 }
222         }
223
224         protected void print(StringBuilder sb, int indent, Object ... objs) {
225                 for(int i=0;i<indent;++i) {
226                         sb.append(' ');
227                 }
228                 for(Object o : objs) {
229                         sb.append(o.toString());
230                 }
231         }
232                         
233         protected void println(StringBuilder sb, int indent, Object ... objs) {
234                 print(sb,indent,objs);
235                 sb.append('\n');
236         }
237
238         protected void printf(StringBuilder sb, int indent, String fmt, Object ... objs) {
239                 print(sb,indent,String.format(fmt, objs));
240         }
241
242         protected String printCell(StringBuilder sb, int indent, String current, String prev) {
243                 if(current.equals(prev)) {
244                         println(sb,indent,DUPL);
245                 } else {
246                         printCell(sb,indent,current);
247                 }
248                 return current; // use to set prev...
249         }
250         
251         protected void printCell(StringBuilder sb, int indent, String current) {
252                 println(sb,indent,"<td>",current,"</td>");
253         }
254         
255         public synchronized void inc() {
256                 ++count;
257         }
258         
259         public int count() {
260                 return count;
261         }
262 }