Tidied up load() method to remove several static
[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  * Modifications Copyright (C) 2019 IBM.
7  * ===========================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END====================================================
20  *
21  */
22 package org.onap.aaf.auth.batch.reports.bodies;
23
24 import java.io.File;
25 import java.io.IOException;
26 import java.lang.reflect.Constructor;
27 import java.lang.reflect.InvocationTargetException;
28 import java.lang.reflect.Modifier;
29 import java.net.URISyntaxException;
30 import java.net.URL;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.Enumeration;
34 import java.util.HashMap;
35 import java.util.HashSet;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Set;
39 import java.util.TreeMap;
40 import java.util.jar.JarEntry;
41 import java.util.jar.JarFile;
42
43 import org.onap.aaf.auth.batch.helpers.LastNotified;
44 import org.onap.aaf.auth.batch.reports.Notify;
45 import org.onap.aaf.auth.env.AuthzTrans;
46 import org.onap.aaf.cadi.Access;
47 import org.onap.aaf.misc.env.APIException;
48
49 public abstract class NotifyBody {
50     private static final String DUPL = "<td style=\"text-indent: 4em;\">''</td>";
51     private static final Map<String,NotifyBody> bodyMap = new HashMap<>();
52
53     protected Map<String,List<List<String>>> rows;
54     protected final String env;
55     protected final String gui_url;
56
57     private final String name;
58     private final String type;
59     private String date;
60     private int escalation;
61     private int count;
62
63     public NotifyBody(Access access, final String type, final String name) {
64         rows = new TreeMap<>();
65         this.name = name;
66         this.type = type;
67         date="";
68         escalation = 1;
69         count = 0;
70         env = access.getProperty("CASS_ENV","DEVL");
71         gui_url = access.getProperty("GUI_URL", "");
72     }
73
74     public void store(List<String> row) {
75         if(!row.isEmpty()) {
76             if("info".equals(row.get(0))) {
77                 if(row.size()>2) {
78                     date = row.get(2);
79                 }
80                 if(row.size()>3) {
81                     escalation = Integer.parseInt(row.get(3));
82                 }
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;
183         if (url != null) {
184             urlString = url.toString();
185             if (urlString.startsWith("jar:file:")) {
186                 int exclam = urlString.lastIndexOf('!');
187                 JarFile jf = new JarFile(urlString.substring(9, exclam));
188                 try {
189                     Enumeration<JarEntry> jfe = jf.entries();
190                     while (jfe.hasMoreElements()) {
191                         String name = jfe.nextElement().getName();
192                         if (name.startsWith(path) && name.endsWith(".class")) {
193                             classNames.add(name.substring(0, name.length() - 6).replace('/', '.'));
194                         }
195                     }
196                 } finally {
197                     jf.close();
198                 }
199             } else {
200                 File dir = new File(url.getFile());
201                 String[] dirs = dir.list();
202                 if (dirs != null) {
203                     for (String f : dirs) {
204                         if (f.endsWith(".class")) {
205                             classNames.add(pkg.getName() + '.' + f.substring(0, f.length() - 6));
206                         }
207                     }
208                 }
209             }
210             for (String cls : classNames) {
211                 try {
212                     Class<?> c = cl.loadClass(cls);
213                     if ((c != null) && (!Modifier.isAbstract(c.getModifiers()))) {
214                         Constructor<?> cst = c.getConstructor(Access.class);
215                         NotifyBody nb = (NotifyBody) cst.newInstance(access);
216                         bodyMap.put("info|" + nb.name, nb);
217                         bodyMap.put(nb.type + '|' + nb.name, nb);
218                     }
219                 } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
220                     e.printStackTrace();
221                 }
222             }
223         }
224     }
225
226     protected void print(StringBuilder sb, int indent, Object ... objs) {
227         for(int i = 0; i < indent; ++i) {
228             sb.append(' ');
229         }
230         for(Object o : objs) {
231             sb.append(o.toString());
232         }
233     }
234
235     protected void println(StringBuilder sb, int indent, Object ... objs) {
236         print(sb,indent,objs);
237         sb.append('\n');
238     }
239
240     protected void printf(StringBuilder sb, int indent, String fmt, Object ... objs) {
241         print(sb,indent,String.format(fmt, objs));
242     }
243
244     protected String printCell(StringBuilder sb, int indent, String current, String prev) {
245         if(current.equals(prev)) {
246             println(sb,indent,DUPL);
247         } else {
248             printCell(sb,indent,current);
249         }
250         return current; // use to set prev...
251     }
252
253     protected void printCell(StringBuilder sb, int indent, String current) {
254         println(sb,indent,"<td>",current,"</td>");
255     }
256
257     public synchronized void inc() {
258         ++count;
259     }
260
261     public int count() {
262         return count;
263     }
264 }