Collection syntax change because of Sonar
[aaf/authz.git] / auth / auth-batch / src / main / java / org / onap / aaf / auth / helpers / Cred.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.util.ArrayList;
25 import java.util.Date;
26 import java.util.GregorianCalendar;
27 import java.util.HashSet;
28 import java.util.Iterator;
29 import java.util.List;
30 import java.util.Set;
31 import java.util.TreeMap;
32
33 import org.onap.aaf.auth.dao.cass.CredDAO;
34 import org.onap.aaf.auth.dao.hl.Question;
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 Cred  {
46     public static final TreeMap<String,Cred> data = new TreeMap<>();
47     public static final TreeMap<String,List<Cred>> byNS = new TreeMap<>();
48
49         public final String id;
50         public final List<Instance> instances;
51         public final String ns;
52         
53         public Cred(String id) {
54                 this.id = id;
55                 instances = new ArrayList<>();
56                 ns=Question.domain2ns(id);
57         }
58         
59         public static class Instance {
60                 public final int type;
61                 public final Date expires,written;
62                 public final Integer other;
63                 
64                 public Instance(int type, Date expires, Integer other, long written) {
65                         this.type = type;
66                         this.expires = expires;
67                         this.other = other;
68                         this.written = new Date(written);
69                 }
70         }
71         
72         public Date last(final int ... types) {
73                 Date last = null;
74                 for(Instance i : instances) {
75                 if(types.length>0) { // filter by types, if requested
76                         boolean quit = true;
77                         for(int t : types) {
78                                 if(t==i.type) {
79                                         quit=false;
80                                         break;
81                                 }
82                         }
83                         if(quit) {
84                                 continue;
85                         }
86                 }
87                         if(last==null || i.expires.after(last)) {
88                                 last = i.expires;
89                         }
90                 }
91                 return last;
92         }
93
94         
95         public Set<Integer> types() {
96                 Set<Integer> types = new HashSet<>();
97                 for(Instance i : instances) {
98                         types.add(i.type);
99                 }
100                 return types;
101         }
102
103         public static void load(Trans trans, Session session, int ... types ) {
104                 load(trans, session,"select id, type, expires, other, writetime(cred) from authz.cred;",types);
105                 
106         }
107
108         public static void loadOneNS(Trans trans, Session session, String ns,int ... types ) {
109                 load(trans, session,"select id, type, expires, other, writetime(cred) from authz.cred WHERE ns='" + ns + "';");
110         }
111
112         private static void load(Trans trans, Session session, String query, int ...types) {
113
114         trans.info().log( "query: " + query );
115         TimeTaken tt = trans.start("Read Creds", Env.REMOTE);
116        
117         ResultSet results;
118                 try {
119                 Statement stmt = new SimpleStatement( query );
120                 results = session.execute(stmt);
121         } finally {
122                 tt.done();
123         }
124                 int count = 0;
125         try {
126                 Iterator<Row> iter = results.iterator();
127                 Row row;
128                 int type; // for filtering
129                 String id;
130                 tt = trans.start("Load Credentials", Env.SUB);
131                 try {
132                         while(iter.hasNext()) {
133                                 ++count;
134                                 row = iter.next();
135                                 id = row.getString(0);
136                                 type = row.getInt(1);
137                                 if(types.length>0) { // filter by types, if requested
138                                         boolean quit = true;
139                                         for(int t : types) {
140                                                 if(t==type) {
141                                                         quit=false;
142                                                         break;
143                                                 }
144                                         }
145                                         if(quit) {
146                                                 continue;
147                                         }
148                                 }
149                                 Cred cred = data.get(id);
150                                 if(cred==null) {
151                                         cred = new Cred(id);
152                                         data.put(id, cred);
153                                 }
154                                 cred.instances.add(new Instance(type, row.getTimestamp(2), row.getInt(3), row.getLong(4)/1000));
155                                 
156                                 List<Cred> lscd = byNS.get(cred.ns);
157                                 if(lscd==null) {
158                                         byNS.put(cred.ns, (lscd=new ArrayList<>()));
159                                 }
160                                 boolean found = false;
161                                 for(Cred c : lscd) {
162                                         if(c.id.equals(cred.id)) {
163                                                 found=true;
164                                                 break;
165                                         }
166                                 }
167                                 if(!found) {
168                                         lscd.add(cred);
169                                 }
170                         }
171                 } finally {
172                         tt.done();
173                 }
174         } finally {
175                 trans.info().log("Found",count,"creds");
176         }
177         }
178         
179         /** 
180          * Count entries in Cred data.
181          * Note, as opposed to other methods, need to load the whole cred table for the Types.
182          * @param numbuckets 
183          * @return
184          */
185         public static CredCount count(int numbuckets) {
186                 CredCount cc = new CredCount(numbuckets);
187                 for(Cred c : data.values()) {
188                         for (Instance ci : c.instances) {
189                                 cc.inc(ci.type,ci.written, ci.expires);
190                         }
191                 }
192                 return cc;
193 //              String query = "select count(*) from authz.cred LIMIT 1000000;";
194 //        trans.info().log( "query: " + query );
195 //        TimeTaken tt = trans.start("Count Credentials", Env.REMOTE);
196 //        ResultSet results;
197 //        try {
198 //              Statement stmt = new SimpleStatement(query).setReadTimeoutMillis(12000);
199 //              results = session.execute(stmt);
200 //              return results.one().getLong(0);
201 //        } finally {
202 //              tt.done();
203 //        }
204         }
205
206         public static class CredCount {
207                 public int raw[];
208                 public int basic_auth[];
209                 public int basic_auth_256[];
210                 public int cert[];
211                 public int x509Added[];
212                 public int x509Expired[];
213                 public Date dates[];
214                 
215                 public CredCount(int numbuckets) {
216                         raw = new int[numbuckets];
217                         basic_auth = new int[numbuckets];
218                         basic_auth_256 = new int[numbuckets];
219                         cert = new int[numbuckets];
220                         x509Added = new int[numbuckets];
221                         x509Expired = new int[numbuckets];
222                         dates = new Date[numbuckets];
223                         GregorianCalendar gc = new GregorianCalendar();
224                         dates[0]=gc.getTime(); // now
225                         gc.set(GregorianCalendar.DAY_OF_MONTH, 1);
226                         gc.set(GregorianCalendar.HOUR, 0);
227                         gc.set(GregorianCalendar.MINUTE, 0);
228                         gc.set(GregorianCalendar.SECOND,0);
229                         gc.set(GregorianCalendar.MILLISECOND,0);
230                         gc.add(GregorianCalendar.MILLISECOND, -1); // last milli of month
231                         for(int i=1;i<numbuckets;++i) {
232                                 dates[i] = gc.getTime();
233                                 gc.add(GregorianCalendar.MONTH, -1);
234                         }
235                         
236                 }
237                 
238                 public void inc(int type, Date start, Date expires) {
239                         for(int i=0;i<dates.length-1;++i) {
240                                 if(start.before(dates[i])) {
241                                         if(type==CredDAO.CERT_SHA256_RSA) {
242                                                 if(start.after(dates[i+1])) {
243                                                         ++x509Added[i];
244                                                 }
245                                         }
246                                         if(expires.after(dates[i])) {
247                                                 switch(type) {
248                                                         case CredDAO.RAW:
249                                                                 ++raw[i];
250                                                                 break;
251                                                         case CredDAO.BASIC_AUTH:
252                                                                 ++basic_auth[i];
253                                                                 break;
254                                                         case CredDAO.BASIC_AUTH_SHA256:
255                                                                 ++basic_auth_256[i];
256                                                                 break;
257                                                         case CredDAO.CERT_SHA256_RSA:
258                                                                 ++cert[i];
259                                                                 break;
260                                                 }
261                                         }
262                                 }
263                         }
264                 }
265
266                 public long authCount(int idx) {
267                         return (long)basic_auth[idx]+basic_auth_256[idx];
268                 }
269                 
270                 public long x509Count(int idx) {
271                         return cert[idx];
272                 }
273
274         }
275         
276         public String toString() {
277                 StringBuilder sb = new StringBuilder(id);
278                 sb.append('[');
279                 for(Instance i : instances) {
280                         sb.append('{');
281                         sb.append(i.type);
282                         sb.append(",\"");
283                         sb.append(i.expires);
284                         sb.append("\"}");
285                 }
286                 sb.append(']');
287                 return sb.toString();
288         }
289
290         /* (non-Javadoc)
291          * @see java.lang.Object#hashCode()
292          */
293         @Override
294         public int hashCode() {
295                 return id.hashCode();
296         }
297
298         /* (non-Javadoc)
299          * @see java.lang.Object#equals(java.lang.Object)
300          */
301         @Override
302         public boolean equals(Object obj) {
303                 return id.equals(obj);
304         }
305
306 }