0cfc1dc5192f85cc492aaab39534ba2a95c5f0bf
[aaf/authz.git] / auth / auth-cass / src / main / java / org / onap / aaf / auth / dao / cass / HistoryDAO.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.dao.cass;
23
24 import java.nio.ByteBuffer;
25 import java.text.SimpleDateFormat;
26 import java.util.Date;
27 import java.util.List;
28 import java.util.UUID;
29
30 import org.onap.aaf.auth.dao.AbsCassDAO;
31 import org.onap.aaf.auth.dao.CassDAOImpl;
32 import org.onap.aaf.auth.dao.Loader;
33 import org.onap.aaf.auth.env.AuthzTrans;
34 import org.onap.aaf.auth.layer.Result;
35
36 import com.datastax.driver.core.Cluster;
37 import com.datastax.driver.core.ConsistencyLevel;
38 import com.datastax.driver.core.ResultSet;
39 import com.datastax.driver.core.Row;
40
41 /**
42  * History
43  * 
44  * Originally written PE3617
45  * @author Jonathan
46  * 
47  * History is a special case, because we don't want Updates or Deletes...  Too likely to mess up history.
48  * 
49  * Jonathan 9-9-2013 - Found a problem with using "Prepare".  You cannot prepare anything with a "now()" in it, as
50  * it is evaluated once during the prepare, and kept.  That renders any use of "now()" pointless.  Therefore
51  * the Create function needs to be run fresh everytime.
52  * 
53  * Fixed in Cassandra 1.2.6 https://issues.apache.org/jira/browse/CASSANDRA-5616
54  *
55  */
56 public class HistoryDAO extends CassDAOImpl<AuthzTrans, HistoryDAO.Data> {
57         private static final String TABLE = "history";
58
59         private String[] helpers;
60
61         private HistLoader defLoader;
62
63         private AbsCassDAO<AuthzTrans, Data>.PSInfo readByUser, readBySubject, readByYRMN;
64
65         public HistoryDAO(AuthzTrans trans, Cluster cluster, String keyspace) {
66                 super(trans, HistoryDAO.class.getSimpleName(),cluster,keyspace,Data.class,TABLE,ConsistencyLevel.LOCAL_ONE,ConsistencyLevel.ANY);
67                 init(trans);
68         }
69
70         public HistoryDAO(AuthzTrans trans, AbsCassDAO<AuthzTrans,?> aDao) {
71                 super(trans, HistoryDAO.class.getSimpleName(),aDao,Data.class,TABLE,ConsistencyLevel.LOCAL_ONE,ConsistencyLevel.ANY);
72                 init(trans);
73         }
74
75
76         private static final int KEYLIMIT = 1;
77         public static class Data {
78                 public UUID id;
79                 public int      yr_mon;
80                 public String user;
81                 public String action;
82                 public String target;
83                 public String subject;
84                 public String  memo;
85 //              Map<String, String>  detail = null;
86 //              public Map<String, String>  detail() {
87 //                      if(detail == null) {
88 //                              detail = new HashMap<String, String>();
89 //                      }
90 //                      return detail;
91 //              }
92                 public ByteBuffer reconstruct;
93         }
94         
95         private static class HistLoader extends Loader<Data> {
96                 public HistLoader(int keylimit) {
97                         super(keylimit);
98                 }
99
100                 @Override
101                 public Data load(Data data, Row row) {
102                         data.id = row.getUUID(0);
103                         data.yr_mon = row.getInt(1);
104                         data.user = row.getString(2);
105                         data.action = row.getString(3);
106                         data.target = row.getString(4);
107                         data.subject = row.getString(5);
108                         data.memo = row.getString(6);
109 //                      data.detail = row.getMap(6, String.class, String.class);
110                         data.reconstruct = row.getBytes(7);
111                         return data;
112                 }
113
114                 @Override
115                 protected void key(Data data, int idx, Object[] obj) {
116                         obj[idx]=data.id;
117                 }
118
119                 @Override
120                 protected void body(Data data, int _idx, Object[] obj) {
121                         int idx = _idx;
122                         obj[idx]=data.yr_mon;
123                         obj[++idx]=data.user;
124                         obj[++idx]=data.action;
125                         obj[++idx]=data.target;
126                         obj[++idx]=data.subject;
127                         obj[++idx]=data.memo;
128 //                      obj[++idx]=data.detail;
129                         obj[++idx]=data.reconstruct;            
130                 }
131         };
132         
133         private void init(AuthzTrans trans) {
134                 // Loader must match fields order
135                 defLoader = new HistLoader(KEYLIMIT);
136                 helpers = setCRUD(trans, TABLE, Data.class, defLoader);
137
138                 // Need a specialty Creator to handle the "now()"
139                 // 9/9/2013 - Jonathan - Just great... now() is evaluated once on Client side, invalidating usage (what point is a now() from a long time in the past?
140                 // Unless this is fixed, we're putting in non-prepared statement
141                 // Solved in Cassandra.  Make sure you are running 1.2.6 Cassandra or later. https://issues.apache.org/jira/browse/CASSANDRA-5616       
142                 replace(CRUD.create, new PSInfo(trans, "INSERT INTO history (" +  helpers[FIELD_COMMAS] +
143                                         ") VALUES(now(),?,?,?,?,?,?,?)", 
144                                         new HistLoader(0) {
145                                                 @Override
146                                                 protected void key(Data data, int idx, Object[] obj) {
147                                                 }
148                                         },writeConsistency)
149                                 );
150 //              disable(CRUD.Create);
151                 
152                 replace(CRUD.read, new PSInfo(trans, SELECT_SP +  helpers[FIELD_COMMAS] +
153                                 " FROM history WHERE id = ?", defLoader,readConsistency) 
154 //                              new HistLoader(2) {
155 //                                      @Override
156 //                                      protected void key(Data data, int idx, Object[] obj) {
157 //                                              obj[idx]=data.yr_mon;
158 //                                              obj[++idx]=data.id;
159 //                                      }
160 //                              })
161                         );
162                 disable(CRUD.update);
163                 disable(CRUD.delete);
164                 
165                 readByUser = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + 
166                                 " FROM history WHERE user = ?", defLoader,readConsistency);
167                 readBySubject = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + 
168                                 " FROM history WHERE subject = ? and target = ? ALLOW FILTERING", defLoader,readConsistency);
169                 readByYRMN = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + 
170                                 " FROM history WHERE yr_mon = ?", defLoader,readConsistency);
171                 async(true); //TODO dropping messages with Async
172         }
173
174         public static Data newInitedData() {
175                 Data data = new Data();
176                 Date now = new Date();
177                 // Sonar claims that SimpleDateFormat is not thread safe, so we can't be static
178                 data.yr_mon = Integer.parseInt(new SimpleDateFormat("yyyyMM").format(now));
179                 // data.day_time = Integer.parseInt(dayTimeFormat.format(now));
180                 return data;            
181         }
182
183         public Result<List<Data>> readByYYYYMM(AuthzTrans trans, int yyyymm) {
184                 Result<ResultSet> rs = readByYRMN.exec(trans, "yr_mon", yyyymm);
185                 if(rs.notOK()) {
186                         return Result.err(rs);
187                 }
188                 return extract(defLoader,rs.value,null,dflt);
189         }
190
191         /**
192          * Gets the history for a user in the specified year and month
193          * year - the year in yyyy format
194          * month -  the month in a year ...values 1 - 12
195          **/
196         public Result<List<Data>> readByUser(AuthzTrans trans, String user, int ... yyyymm) {
197                 if(yyyymm.length==0) {
198                         return Result.err(Status.ERR_BadData, "No or invalid yyyymm specified");
199                 }
200                 Result<ResultSet> rs = readByUser.exec(trans, "user", user);
201                 if(rs.notOK()) {
202                         return Result.err(rs);
203                 }
204                 return extract(defLoader,rs.value,null,yyyymm.length>0?new YYYYMM(yyyymm):dflt);
205         }
206         
207         public Result<List<Data>> readBySubject(AuthzTrans trans, String subject, String target, int ... yyyymm) {
208                 if(yyyymm.length==0) {
209                         return Result.err(Status.ERR_BadData, "No or invalid yyyymm specified");
210                 }
211                 Result<ResultSet> rs = readBySubject.exec(trans, "subject", subject, target);
212                 if(rs.notOK()) {
213                         return Result.err(rs);
214                 }
215                 return extract(defLoader,rs.value,null,yyyymm.length>0?new YYYYMM(yyyymm):dflt);
216         }
217         
218         private class YYYYMM implements Accept<Data> {
219                 private int[] yyyymm;
220                 public YYYYMM(int yyyymm[]) {
221                         this.yyyymm = yyyymm;
222                 }
223                 @Override
224                 public boolean ok(Data data) {
225                         int dym = data.yr_mon;
226                         for(int ym:yyyymm) {
227                                 if(dym==ym) {
228                                         return true;
229                                 }
230                         }
231                         return false;
232                 }
233                 
234         };
235         
236 }