Batch, Remove unneeded Classes, refine, etc
[aaf/authz.git] / auth / auth-batch / src / main / java / org / onap / aaf / auth / batch / helpers / UserRole.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.io.PrintStream;
25 import java.util.ArrayList;
26 import java.util.Date;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.SortedMap;
30 import java.util.TreeMap;
31
32 import org.onap.aaf.auth.dao.cass.UserRoleDAO;
33 import org.onap.aaf.auth.dao.cass.UserRoleDAO.Data;
34 import org.onap.aaf.auth.env.AuthzTrans;
35 import org.onap.aaf.cadi.util.CSV;
36 import org.onap.aaf.misc.env.Env;
37 import org.onap.aaf.misc.env.TimeTaken;
38 import org.onap.aaf.misc.env.Trans;
39 import org.onap.aaf.misc.env.util.Chrono;
40
41 import com.datastax.driver.core.ResultSet;
42 import com.datastax.driver.core.Row;
43 import com.datastax.driver.core.Session;
44 import com.datastax.driver.core.SimpleStatement;
45 import com.datastax.driver.core.Statement;
46
47 public class UserRole implements Cloneable, CacheChange.Data  {
48
49     public static final String UR = "ur";
50     public static final String APPROVE_UR = "ur";
51
52         private static final String SEPARATOR = "\",\"";
53
54     // CACHE Calling
55     private static final String LOG_FMT = "%s UserRole - %s: %s-%s (%s, %s) expiring %s";
56     private static final String REPLAY_FMT = "%s|%s|%s|%s|%s\n";
57     private static final String DELETE_FMT = "# %s\n"+ REPLAY_FMT;
58
59     private static final List<UserRole> data = new ArrayList<>();
60     private static final SortedMap<String,List<UserRole>> byUser = new TreeMap<>();
61     private static final SortedMap<String,List<UserRole>> byRole = new TreeMap<>();
62     private static final CacheChange<UserRole> cache = new CacheChange<>();
63     private static PrintStream urDelete = System.out;
64     private static PrintStream urRecover = System.err;
65     private static int totalLoaded;
66     private int deleted;
67     private Data urdd;
68
69     public static final Creator<UserRole> v2_0_11 = new Creator<UserRole>() {
70         @Override
71         public UserRole create(Row row) {
72             return new UserRole(row.getString(0), row.getString(1), row.getString(2),row.getString(3),row.getTimestamp(4));
73         }
74
75         @Override
76         public String select() {
77             return "select user,role,ns,rname,expires from authz.user_role";
78         }
79     };
80
81     public UserRole(String user, String ns, String rname, Date expires) {    
82         urdd = new UserRoleDAO.Data();
83         urdd.user = user;
84         urdd.role = ns + '.' + rname;
85         urdd.ns = ns;
86         urdd.rname = rname;
87         urdd.expires = expires;
88     }
89
90     public UserRole(String user, String role, String ns, String rname, Date expires) {
91         urdd = new UserRoleDAO.Data();
92         urdd.user = user;
93         urdd.role = role;
94         urdd.ns = ns;
95         urdd.rname = rname;
96         urdd.expires = expires;
97     }
98
99     public static List<UserRole> getData() {
100         return data;
101     }
102
103     public static SortedMap<String, List<UserRole>> getByUser() {
104         return byUser;
105     }
106
107     public static SortedMap<String, List<UserRole>> getByRole() {
108         return byRole;
109     }
110
111     public static void load(Trans trans, Session session, Creator<UserRole> creator) {
112         load(trans,session,creator,null,new DataLoadVisitor());
113     }
114     
115     public static void load(Trans trans, Session session, Creator<UserRole> creator, Visitor<UserRole> visitor ) {
116         load(trans,session,creator,null,visitor);
117     }
118
119     public static void loadOneRole(Trans trans, Session session, Creator<UserRole> creator, String role, Visitor<UserRole> visitor) {
120         load(trans,session,creator,"role='" + role +"' ALLOW FILTERING;",visitor);
121     }
122     
123     public static void loadOneUser(Trans trans, Session session, Creator<UserRole> creator, String user, Visitor<UserRole> visitor ) {
124         load(trans,session,creator,"user='"+ user +'\'',visitor);
125     }
126
127     private static void load(Trans trans, Session session, Creator<UserRole> creator, String where, Visitor<UserRole> visitor) {
128         String query = creator.query(where);
129         trans.debug().log( "query: " + query );
130         TimeTaken tt = trans.start("Read UserRoles", Env.REMOTE);
131
132         ResultSet results;
133         try {
134             Statement stmt = new SimpleStatement( query );
135             results = session.execute(stmt);
136         } finally {
137             tt.done();
138         }
139         try {
140             tt = trans.start("Load UserRole", Env.SUB);
141             try {
142                 iterateResults(creator, results.iterator(), visitor);
143             } finally {
144                 tt.done();
145             }
146         } finally {
147             trans.debug().log("Loaded",totalLoaded,"UserRoles");
148         }
149     }
150
151     private static void iterateResults(Creator<UserRole> creator, Iterator<Row> iter, Visitor<UserRole> visit ) {
152         Row row;
153         while (iter.hasNext()) {
154             ++totalLoaded;
155             row = iter.next();
156             UserRole ur = creator.create(row);
157             visit.visit(ur);
158         }
159     }
160
161     public static class DataLoadVisitor implements Visitor<UserRole> {
162                 @Override
163                 public void visit(UserRole ur) {
164             data.add(ur);
165
166             List<UserRole> lur = byUser.get(ur.urdd.user);
167             if (lur==null) {
168                 lur = new ArrayList<>();
169                 byUser.put(ur.urdd.user, lur);
170             }
171             lur.add(ur);
172
173             lur = byRole.get(ur.urdd.role);
174             if (lur==null) {
175                 lur = new ArrayList<>();
176                 byRole.put(ur.urdd.role, lur);
177             }
178             lur.add(ur);
179                 }
180     }
181     
182     public int totalLoaded() {
183         return totalLoaded;
184     }
185     
186     public int deleted() {
187         return deleted;
188     }
189     
190     @Override
191     public void expunge() {
192         data.remove(this);
193         
194         List<UserRole> lur = byUser.get(urdd.user);
195         if (lur!=null) {
196             lur.remove(this);
197         }
198     
199         lur = byRole.get(urdd.role);
200         if (lur!=null) {
201             lur.remove(this);
202         }
203     }
204     
205     public static void setDeleteStream(PrintStream ds) {
206         urDelete = ds;
207     }
208
209     public static void setRecoverStream(PrintStream ds) {
210         urRecover = ds;
211     }
212
213     public static long count(Trans trans, Session session) {
214         String query = "select count(*) from authz.user_role LIMIT 1000000;";
215         trans.info().log( "query: " + query );
216         TimeTaken tt = trans.start("Count Namespaces", Env.REMOTE);
217         ResultSet results;
218         try {
219             Statement stmt = new SimpleStatement(query).setReadTimeoutMillis(12000);
220             results = session.execute(stmt);
221             return results.one().getLong(0);
222         } finally {
223             tt.done();
224         }
225     }
226
227     public UserRoleDAO.Data urdd() {
228         return urdd;
229     }
230     
231     public String user() {
232         return urdd.user;
233     }
234     
235     public String role() {
236         return urdd.role;
237     }
238     
239     public String ns() {
240         return urdd.ns;
241     }
242     
243     public String rname() {
244         return urdd.rname;
245     }
246     
247     public Date expires() {
248         return urdd.expires;
249     }
250     
251     public void expires(Date time) {
252         urdd.expires = time;
253     }
254
255     public String toString() {
256         return "\"" + urdd.user + SEPARATOR + urdd.role + SEPARATOR + urdd.ns + SEPARATOR + urdd.rname + SEPARATOR
257             + Chrono.dateOnlyStamp(urdd.expires);
258     }
259
260     public static UserRole get(String u, String r) {
261         List<UserRole> lur = byUser.get(u);
262         if (lur!=null) {
263             for (UserRole ur : lur) {
264
265                 if (ur.urdd.role.equals(r)) {
266                     return ur;
267                 }
268             }
269         }
270         return null;
271     }
272
273     // SAFETY - DO NOT DELETE USER ROLES DIRECTLY FROM BATCH FILES!!!
274     // We write to a file, and validate.  If the size is iffy, we email Support
275     public void delayDelete(AuthzTrans trans, String text, boolean dryRun) {
276         String dt = Chrono.dateTime(urdd.expires);
277         if (dryRun) {
278             trans.info().printf(LOG_FMT,text,"Would Delete",urdd.user,urdd.role,urdd.ns,urdd.rname,dt);
279         } else {
280             trans.info().printf(LOG_FMT,text,"Staged Deletion",urdd.user,urdd.role,urdd.ns,urdd.rname,dt);
281         }
282         urDelete.printf(DELETE_FMT,text,urdd.user,urdd.role,dt,urdd.ns,urdd.rname);
283         urRecover.printf(REPLAY_FMT,urdd.user,urdd.role,dt,urdd.ns,urdd.rname);
284
285         cache.delayedDelete(this);
286         ++deleted;
287     }
288     
289
290     /**
291      * Calls expunge() for all deleteCached entries
292      */
293     public static void resetLocalData() {
294         cache.resetLocalData();
295     }
296     
297     public void row(final CSV.Writer csvw, String tag) {
298         csvw.row(tag,user(),role(),ns(),rname(),Chrono.dateOnlyStamp(expires()),expires().getTime());
299     }
300
301     public void row(final CSV.Writer csvw, String tag, String reason) {
302         csvw.row(tag,user(),role(),ns(),rname(),Chrono.dateOnlyStamp(expires()),expires().getTime(),reason);
303     }
304     
305     public static Data row(List<String> row) {
306                 Data data = new Data();
307                 data.user = row.get(1);
308                 data.role = row.get(2);
309                 data.ns = row.get(3);
310                 data.rname = row.get(4);
311                 data.expires = new Date(Long.parseLong(row.get(6)));
312                 return data;
313         }
314
315         public static void batchDelete(StringBuilder sb, List<String> row) {
316         sb.append("DELETE from authz.user_role WHERE user='");
317         sb.append(row.get(1));
318         sb.append("' AND role='");
319         sb.append(row.get(2));
320         sb.append("';\n");
321     }
322
323     public static void batchExtend(StringBuilder sb, List<String> row, Date newDate ) {
324         sb.append("UPDATE authz.user_role SET expires='");
325         sb.append(Chrono.dateTime(newDate));
326         sb.append("' WHERE user='");
327         sb.append(row.get(1));
328         sb.append("' AND role='");
329         sb.append(row.get(2));
330         sb.append("';\n");
331     }
332
333     public void batchUpdateExpires(StringBuilder sb) {
334         sb.append("UPDATE authz.user_role SET expires='");
335         sb.append(Chrono.dateTime(expires()));
336         sb.append("' WHERE user='");
337         sb.append(user());
338         sb.append("' AND role='");
339         sb.append(role());
340         sb.append("';\n");
341     }
342
343         public static String histMemo(String fmt, List<String> row) {
344                 String reason;
345                 if(row.size()>7) { // Reason included
346                         reason = String.format("%s removed from %s because %s", 
347                                         row.get(1),row.get(2),row.get(7));
348                 } else {
349                         reason = String.format(fmt, row.get(1),row.get(2), row.get(5));
350                 }
351                 return reason;
352         }
353
354         public static String histSubject(List<String> row) {
355                 return row.get(1) + '|' + row.get(2);   
356         }
357 }