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