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