Approval Batch, prep better JUnit
[aaf/authz.git] / auth / auth-batch / src / main / java / org / onap / aaf / auth / batch / helpers / Approval.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.helpers;
23
24 import java.util.ArrayList;
25 import java.util.Date;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.TreeMap;
29 import java.util.UUID;
30
31 import org.onap.aaf.auth.dao.cass.ApprovalDAO;
32 import org.onap.aaf.auth.env.AuthzTrans;
33 import org.onap.aaf.auth.layer.Result;
34 import org.onap.aaf.cadi.util.CSV;
35 import org.onap.aaf.misc.env.Env;
36 import org.onap.aaf.misc.env.TimeTaken;
37 import org.onap.aaf.misc.env.Trans;
38
39 import com.datastax.driver.core.ResultSet;
40 import com.datastax.driver.core.Row;
41 import com.datastax.driver.core.Session;
42 import com.datastax.driver.core.SimpleStatement;
43 import com.datastax.driver.core.Statement;
44
45 public class Approval implements CacheChange.Data  {
46     public static final String RE_APPROVAL_IN_ROLE = "Re-Approval in Role '";
47     public static final String RE_VALIDATE_ADMIN = "Re-Validate as Administrator for AAF Namespace '";
48     public static final String RE_VALIDATE_OWNER = "Re-Validate Ownership for AAF Namespace '";
49
50     public static TreeMap<String,List<Approval>> byApprover = new TreeMap<>();
51     public static TreeMap<String,List<Approval>> byUser = new TreeMap<>();
52     public static TreeMap<UUID,List<Approval>> byTicket = new TreeMap<>();
53     private final static CacheChange<Approval> cache = new CacheChange<>(); 
54     
55     public final ApprovalDAO.Data add;
56     private String role;
57     
58     public Approval(UUID id, UUID ticket, String approver, Date last_notified, 
59             String user, String memo, String operation, String status, String type, long updated) {
60         add = new ApprovalDAO.Data();
61         add.id = id;
62         add.ticket = ticket;
63         add.approver = approver;
64         add.last_notified = last_notified;
65         add.user = user;
66         add.memo = memo;
67         add.operation = operation;
68         add.status = status;
69         add.type = type;
70         add.updated = new Date(updated);
71         role = roleFromMemo(memo);
72     }
73     
74     public static String roleFromMemo(String memo) {
75         if (memo==null) {
76             return null;
77         }
78         int first = memo.indexOf('\'');
79         if (first>=0) {
80             int second = memo.indexOf('\'', ++first);
81             if (second>=0) {
82                 String role = memo.substring(first, second);
83                 if (memo.startsWith(RE_VALIDATE_ADMIN)) {
84                     return role + ".admin";
85                 } else if (memo.startsWith(RE_VALIDATE_OWNER)) {
86                     return role + ".owner";
87                 } else if (memo.startsWith(RE_APPROVAL_IN_ROLE)) {
88                     return role;
89                 }
90             }
91         }
92         return null;
93     }
94
95     public static void load(Trans trans, Session session, Creator<Approval> creator, Visitor<Approval> visitor) {
96         trans.info().log( "query: " + creator.select() );
97         TimeTaken tt = trans.start("Read Approval", Env.REMOTE);
98        
99         ResultSet results;
100         try {
101             Statement stmt = new SimpleStatement( creator.select() );
102             results = session.execute(stmt);
103         } finally {
104             tt.done();
105         }
106
107         int count = 0;
108         try {
109             Iterator<Row> iter = results.iterator();
110             Row row;
111             tt = trans.start("Load X509s", Env.SUB);
112             try {
113                 while (iter.hasNext()) {
114                         ++count;
115                     row = iter.next();
116                     visitor.visit(creator.create(row));
117                 }
118             } finally {
119                 tt.done();
120             }
121         } finally {
122             trans.info().log("Found",count,"X509 Certificates");
123         }
124     }
125     
126         public static void row(CSV.Writer cw, Approval app) {
127                 cw.row("approval",app.add.id,app.add.ticket,app.add.user,app.role,app.add.memo);
128         }
129
130     public static void load(Trans trans, Session session, Creator<Approval> creator ) {
131         trans.info().log( "query: " + creator.select() );
132         TimeTaken tt = trans.start("Load Notify", Env.REMOTE);
133        
134         ResultSet results;
135         try {
136             Statement stmt = new SimpleStatement(creator.select());
137             results = session.execute(stmt);
138         } finally {
139             tt.done();
140         }
141         int count = 0;
142         tt = trans.start("Process Notify", Env.SUB);
143
144         try {
145                 List<Approval> ln;
146                 for (Row row : results.all()) {
147                     ++count;
148                     try {
149                             Approval app = creator.create(row);
150                             String person = app.getApprover();
151                             if (person!=null) {
152                             ln = byApprover.get(person);
153                                 if (ln==null) {
154                                     ln = new ArrayList<>();
155                                     byApprover.put(app.getApprover(), ln);
156                                 }
157                                 ln.add(app);
158                             }
159                             
160                             
161                         person = app.getUser();
162                             if (person!=null) {
163                                 ln = byUser.get(person);
164                                 if (ln==null) {
165                                     ln = new ArrayList<>();
166                                     byUser.put(app.getUser(), ln);
167                                 }
168                                 ln.add(app);
169                             }
170                             UUID ticket = app.getTicket();
171                             if (ticket!=null) {
172                                 ln = byTicket.get(ticket);
173                                 if (ln==null) {
174                                     ln = new ArrayList<>();
175                                     byTicket.put(app.getTicket(), ln);
176                                 }
177                             ln.add(app);
178                             }
179                     } finally {
180                         tt.done();
181                     }
182                 }
183         } finally {
184             tt.done();
185             trans.info().log("Found",count,"Approval Records");
186         }
187     }
188     
189     @Override
190     public void expunge() {
191         List<Approval> la = byApprover.get(getApprover());
192         if (la!=null) {
193             la.remove(this);
194         }
195         
196         la = byUser.get(getUser());
197         if (la!=null) {
198             la.remove(this);
199         }
200         UUID ticket = this.add==null?null:this.add.ticket;
201         if (ticket!=null) {
202             la = byTicket.get(this.add.ticket);
203             if (la!=null) {
204                 la.remove(this);
205             }
206         }
207     }
208
209     public void update(AuthzTrans trans, ApprovalDAO apprDAO, boolean dryRun) {
210         if (dryRun) {
211             trans.info().printf("Would update Approval %s, %s, last_notified %s",add.id,add.status,add.last_notified);
212         } else {
213             trans.info().printf("Update Approval %s, %s, last_notified %s",add.id,add.status,add.last_notified);
214             apprDAO.update(trans, add);
215         }
216     }
217
218     public static Creator<Approval> v2_0_17 = new Creator<Approval>() {
219         @Override
220         public Approval create(Row row) {
221             return new Approval(row.getUUID(0), row.getUUID(1), row.getString(2), row.getTimestamp(3),
222                     row.getString(4),row.getString(5),row.getString(6),row.getString(7),row.getString(8)
223                     ,row.getLong(9)/1000);
224         }
225
226         @Override
227         public String select() {
228             return "select id,ticket,approver,last_notified,user,memo,operation,status,type,WRITETIME(status) from authz.approval";
229         }
230     };
231
232     /**
233      * @return the lastNotified
234      */
235     public Date getLast_notified() {
236         return add.last_notified;
237     }
238     /**
239      * @param lastNotified the lastNotified to set
240      */
241     public void setLastNotified(Date last_notified) {
242         add.last_notified = last_notified;
243     }
244     /**
245      * @return the status
246      */
247     public String getStatus() {
248         return add.status;
249     }
250     /**
251      * @param status the status to set
252      */
253     public void setStatus(String status) {
254         add.status = status;
255     }
256     /**
257      * @return the id
258      */
259     public UUID getId() {
260         return add.id;
261     }
262     /**
263      * @return the ticket
264      */
265     public UUID getTicket() {
266         return add.ticket;
267     }
268     /**
269      * @return the approver
270      */
271     public String getApprover() {
272         return add.approver;
273     }
274     /**
275      * @return the user
276      */
277     public String getUser() {
278         return add.user;
279     }
280     /**
281      * @return the memo
282      */
283     public String getMemo() {
284         return add.memo;
285     }
286     /**
287      * @return the operation
288      */
289     public String getOperation() {
290         return add.operation;
291     }
292     /**
293      * @return the type
294      */
295     public String getType() {
296         return add.type;
297     }
298     public void lapsed() {
299         add.ticket=null;
300         add.status="lapsed";
301     }
302     
303     public String getRole() {
304         return role;
305     }
306     
307     public String toString() {
308         return getUser() + ' ' + getMemo();
309     }
310
311     public void delayDelete(AuthzTrans trans, ApprovalDAO ad, boolean dryRun, String text) {
312         if (dryRun) {
313             trans.info().log(text,"- Would Delete: Approval",getId(),"on ticket",getTicket(),"for",getApprover());
314         } else {
315             Result<Void> rv = ad.delete(trans, add, false);
316             if (rv.isOK()) {
317                 trans.info().log(text,"- Deleted: Approval",getId(),"on ticket",getTicket(),"for",getApprover());
318                 cache.delayedDelete(this);
319             } else {
320                 trans.info().log(text,"- Failed to Delete Approval",getId());
321             }
322         }
323     }
324     
325
326     public static void resetLocalData() {
327         cache.resetLocalData();
328     }
329     
330     public static int sizeForDeletion() {
331         return cache.cacheSize();
332     }
333
334     public static void delayDelete(AuthzTrans noAvg, ApprovalDAO apprDAO, boolean dryRun, List<Approval> list, String text) {
335         if (list!=null) {
336             for (Approval a : list) {
337                 a.delayDelete(noAvg, apprDAO, dryRun,text);
338             }
339         }
340     }
341
342     public static boolean pendingDelete(Approval a) {
343         return cache.contains(a);
344     }
345
346         public static void deleteByIDBatch(StringBuilder sb, String id) {
347                 sb.append("DELETE from authz.approval where id=");
348                 sb.append(id);
349                 sb.append(";\n");
350         }
351
352 }