6c95f02e92e36d1fd3ad1b0531b1e16b630f39dc
[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                 return;
84             } else if(type.equals(row.get(0))) {
85                 String user = user(row);
86                 if(user!=null) {
87                     List<List<String>> lss = rows.get(user); 
88                     if(lss == null) {
89                         lss = new ArrayList<>();
90                         rows.put(user,lss);
91                     }
92                     lss.add(row);
93                 }
94             }
95         }
96     }
97
98     public String name() {
99         return name;
100     }
101     
102     public String type() {
103         return type;
104     }
105     
106     public String date() {
107         return date;
108     }
109     public int escalation() {
110         return escalation;
111     }
112     
113     public Set<String> users() {
114         return rows.keySet();
115     }
116     
117     /**
118      * ID must be set from Row for Email lookup
119      * 
120      * @param trans
121      * @param n
122      * @param id
123      * @param row
124      * @return
125      */
126     public abstract boolean body(AuthzTrans trans, StringBuilder sb, int indent, Notify n, String id);
127     
128     /**
129      * Return "null" if user not found in row... Code will handle.
130      * @param row
131      * @return
132      */
133     protected abstract String user(List<String> row);
134     
135     /**
136      * Provide a context-sensitive Subject, which includes ENV as well as details
137      * 
138      * @return
139      */
140     public abstract String subject();
141
142     /**
143      * Record the fact that a particular Notification was marked as "sent" by Emailer.
144      * 
145      * @param trans
146      * @param approver
147      * @param ln
148      */
149     public abstract void record(AuthzTrans trans, StringBuilder query, String id, List<String> notified, LastNotified ln);
150     
151     /**
152      * Get Notify Body based on key of
153      * type|name
154      */
155     public static NotifyBody get(String key) {
156         return bodyMap.get(key);
157     }
158     
159     /**
160      * Return set of loaded NotifyBodies
161      * 
162      */
163     public static Collection<NotifyBody> getAll() {
164         // Note: The same Notify Body is entered several times with different keys.
165         // Therefore, need a Set of Values, not all the Values.
166         Set<NotifyBody> set = new HashSet<>();
167         set.addAll(bodyMap.values());
168         return set;
169     }
170     
171     /**
172      * @param propAccess 
173      * @throws URISyntaxException 
174      * 
175      */
176     public static void load(Access access) throws APIException, IOException {
177         // class load available NotifyBodies
178         ClassLoader cl = Thread.currentThread().getContextClassLoader();
179         Package pkg = NotifyBody.class.getPackage();
180         String path = pkg.getName().replace('.', '/');
181         URL url = cl.getResource(path);
182         List<String> classNames = new ArrayList<>();
183         String urlString = url.toString();
184         if(urlString.startsWith("jar:file:")) {
185             int exclam = urlString.lastIndexOf('!');
186             JarFile jf = new JarFile(urlString.substring(9,exclam));
187             try {
188                 Enumeration<JarEntry> jfe = jf.entries();
189                 while(jfe.hasMoreElements()) {
190                     String name = jfe.nextElement().getName();
191                     if(name.startsWith(path) && name.endsWith(".class")) {
192                         classNames.add(name.substring(0,name.length()-6).replace('/', '.'));
193                     }
194                 }
195             } finally {
196                 jf.close();
197             }
198         } else {
199             File dir = new File(url.getFile());
200             for( String f : dir.list()) {
201                 if(f.endsWith(".class")) {
202                     classNames.add(pkg.getName()+'.'+f.substring(0,f.length()-6));
203                 }
204             }
205         }
206         for(String cls : classNames) {
207             try {
208                 Class<?> c = cl.loadClass(cls);
209                 if((c!=null)&&(!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             } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
218                 e.printStackTrace();
219             }
220         }
221     }
222
223     protected void print(StringBuilder sb, int indent, Object ... objs) {
224         for(int i=0;i<indent;++i) {
225             sb.append(' ');
226         }
227         for(Object o : objs) {
228             sb.append(o.toString());
229         }
230     }
231             
232     protected void println(StringBuilder sb, int indent, Object ... objs) {
233         print(sb,indent,objs);
234         sb.append('\n');
235     }
236
237     protected void printf(StringBuilder sb, int indent, String fmt, Object ... objs) {
238         print(sb,indent,String.format(fmt, objs));
239     }
240
241     protected String printCell(StringBuilder sb, int indent, String current, String prev) {
242         if(current.equals(prev)) {
243             println(sb,indent,DUPL);
244         } else {
245             printCell(sb,indent,current);
246         }
247         return current; // use to set prev...
248     }
249     
250     protected void printCell(StringBuilder sb, int indent, String current) {
251         println(sb,indent,"<td>",current,"</td>");
252     }
253     
254     public synchronized void inc() {
255         ++count;
256     }
257     
258     public int count() {
259         return count;
260     }
261 }