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