AT&T 2.0.19 Code drop, stage 3
[aaf/authz.git] / auth / auth-cass / src / main / java / org / onap / aaf / auth / dao / cass / FutureDAO.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.util.Date;
26 import java.util.List;
27 import java.util.UUID;
28
29 import org.onap.aaf.auth.dao.CassDAOImpl;
30 import org.onap.aaf.auth.dao.DAOException;
31 import org.onap.aaf.auth.dao.Loader;
32 import org.onap.aaf.auth.env.AuthzTrans;
33 import org.onap.aaf.auth.layer.Result;
34
35 import com.datastax.driver.core.Cluster;
36 import com.datastax.driver.core.ResultSet;
37 import com.datastax.driver.core.Row;
38
39 /**
40  * FutureDAO stores Construction information to create 
41  * elements at another time.
42  * 
43  * @author Jonathan
44  * 8/20/2013
45  */
46 public class FutureDAO extends CassDAOImpl<AuthzTrans,FutureDAO.Data> {
47     private static final String TABLE = "future";
48         private final HistoryDAO historyDAO;
49 //      private static String createString;
50         private PSInfo psByStartAndTarget;
51         
52     public FutureDAO(AuthzTrans trans, Cluster cluster, String keyspace) {
53         super(trans, FutureDAO.class.getSimpleName(),cluster, keyspace, Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE));
54                 historyDAO = new HistoryDAO(trans, this);
55         init(trans);
56     }
57
58     public FutureDAO(AuthzTrans trans, HistoryDAO hDAO) {
59         super(trans, FutureDAO.class.getSimpleName(),hDAO, Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE));
60         historyDAO=hDAO;
61         init(trans);
62     }
63
64     public static final int KEYLIMIT = 1;
65     public static class Data {
66         public UUID         id;
67         public String           target;
68         public String           memo;
69         public Date             start;
70         public Date             expires;
71         public ByteBuffer       construct;  //   this is a blob in cassandra
72     }
73
74     private static class FLoader extends Loader<Data> {
75         public FLoader() {
76             super(KEYLIMIT);
77         }
78
79         public FLoader(int keylimit) {
80             super(keylimit);
81         }
82
83         @Override
84         public Data load(Data data, Row row) {
85             data.id             = row.getUUID(0);
86             data.target         = row.getString(1);
87             data.memo       = row.getString(2);
88             data.start          = row.getTimestamp(3);
89             data.expires        = row.getTimestamp(4);
90             data.construct      = row.getBytes(5);
91             return data;
92         }
93
94         @Override
95         protected void key(Data data, int idx, Object[] obj) {
96             obj[idx] = data.id;
97         }
98
99         @Override
100         protected void body(Data data, int _idx, Object[] obj) {
101             int idx = _idx;
102
103             obj[idx] = data.target;
104             obj[++idx] = data.memo;
105             obj[++idx] = data.start;
106             obj[++idx] = data.expires;
107             obj[++idx] = data.construct;
108         }
109     }
110
111     private void init(AuthzTrans trans) {
112         // Set up sub-DAOs
113         String[] helpers = setCRUD(trans, TABLE, Data.class, new FLoader(KEYLIMIT));
114
115         // Uh, oh.  Can't use "now()" in Prepared Statements (at least at this level)
116 //              createString = "INSERT INTO " + TABLE + " ("+helpers[FIELD_COMMAS] +") VALUES (now(),";
117 //
118 //              // Need a specialty Creator to handle the "now()"
119 //              replace(CRUD.Create, new PSInfo(trans, "INSERT INTO future (" +  helpers[FIELD_COMMAS] +
120 //                                      ") VALUES(now(),?,?,?,?,?)",new FLoader(0)));
121                 
122                 // Other SELECT style statements... match with a local Method
123                 psByStartAndTarget = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] +
124                                 " FROM future WHERE start <= ? and target = ? ALLOW FILTERING", new FLoader(2) {
125                         @Override
126                         protected void key(Data data, int _idx, Object[] obj) {
127                                 int idx = _idx;
128
129                                 obj[idx]=data.start;
130                                 obj[++idx]=data.target;
131                         }
132                 },readConsistency);
133                 
134
135     }
136
137     public Result<List<Data>> readByStartAndTarget(AuthzTrans trans, Date start, String target) throws DAOException {
138                 return psByStartAndTarget.read(trans, R_TEXT, new Object[]{start, target});
139         }
140
141     /**
142          * Override create to add secondary ID to Subject in History, and create Data.ID, if it is null
143      */
144         public Result<FutureDAO.Data> create(AuthzTrans trans,  FutureDAO.Data data, String id) {
145                 // If ID is not set (typical), create one.
146                 if(data.id==null) {
147                         StringBuilder sb = new StringBuilder(trans.user());
148                         sb.append(data.target);
149                         sb.append(System.currentTimeMillis());
150                         data.id = UUID.nameUUIDFromBytes(sb.toString().getBytes());
151                 }
152                 Result<ResultSet> rs = createPS.exec(trans, C_TEXT, data);
153                 if(rs.notOK()) {
154                         return Result.err(rs);
155                 }
156                 wasModified(trans, CRUD.create, data, null, id);
157                 return Result.ok(data); 
158         }
159
160         /**
161          * Log Modification statements to History
162          *
163          * @param modified        which CRUD action was done
164          * @param data            entity data that needs a log entry
165          * @param overrideMessage if this is specified, we use it rather than crafting a history message based on data
166          */
167         @Override
168         protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) {
169                 boolean memo = override.length>0 && override[0]!=null;
170                 boolean subject = override.length>1 && override[1]!=null;
171                 HistoryDAO.Data hd = HistoryDAO.newInitedData();
172             hd.user = trans.user();
173                 hd.action = modified.name();
174                 hd.target = TABLE;
175                 hd.subject = subject?override[1]:"";
176             hd.memo = memo?String.format("%s by %s", override[0], hd.user):data.memo;
177         
178                 if(historyDAO.create(trans, hd).status!=Status.OK) {
179                 trans.error().log("Cannot log to History");
180                 }
181         }
182     
183 }