[AAF-21] Updated Copyright Headers for AAF
[aaf/authz.git] / authz-cass / src / main / java / com / att / dao / aaf / cass / CredDAO.java
1 /*******************************************************************************\r
2  * ============LICENSE_START====================================================\r
3  * * org.onap.aaf\r
4  * * ===========================================================================\r
5  * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.\r
6  * * ===========================================================================\r
7  * * Licensed under the Apache License, Version 2.0 (the "License");\r
8  * * you may not use this file except in compliance with the License.\r
9  * * You may obtain a copy of the License at\r
10  * * \r
11  *  *      http://www.apache.org/licenses/LICENSE-2.0\r
12  * * \r
13  *  * Unless required by applicable law or agreed to in writing, software\r
14  * * distributed under the License is distributed on an "AS IS" BASIS,\r
15  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
16  * * See the License for the specific language governing permissions and\r
17  * * limitations under the License.\r
18  * * ============LICENSE_END====================================================\r
19  * *\r
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
21  * *\r
22  ******************************************************************************/\r
23 package com.att.dao.aaf.cass;\r
24 \r
25 import java.io.ByteArrayOutputStream;\r
26 import java.io.DataInputStream;\r
27 import java.io.DataOutputStream;\r
28 import java.io.IOException;\r
29 import java.nio.ByteBuffer;\r
30 import java.util.Date;\r
31 import java.util.List;\r
32 \r
33 import com.att.authz.env.AuthzTrans;\r
34 import com.att.authz.layer.Result;\r
35 import com.att.dao.Bytification;\r
36 import com.att.dao.CIDAO;\r
37 import com.att.dao.Cached;\r
38 import com.att.dao.CassDAOImpl;\r
39 import com.att.dao.Loader;\r
40 import com.att.dao.Streamer;\r
41 import com.att.inno.env.APIException;\r
42 import com.att.inno.env.util.Chrono;\r
43 import com.datastax.driver.core.Cluster;\r
44 import com.datastax.driver.core.Row;\r
45 \r
46 /**\r
47  * CredDAO manages credentials. \r
48  * Date: 7/19/13\r
49  */\r
50 public class CredDAO extends CassDAOImpl<AuthzTrans,CredDAO.Data> {\r
51     public static final String TABLE = "cred";\r
52     public static final int CACHE_SEG = 0x40; // yields segment 0x0-0x3F\r
53         public static final int RAW = -1;\r
54     public static final int BASIC_AUTH = 1;\r
55     public static final int BASIC_AUTH_SHA256 = 2;\r
56     public static final int CERT_SHA256_RSA =200;\r
57     \r
58     private HistoryDAO historyDAO;\r
59         private CIDAO<AuthzTrans> infoDAO;\r
60         private PSInfo psNS;\r
61         private PSInfo psID;\r
62         \r
63     public CredDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException {\r
64         super(trans, CredDAO.class.getSimpleName(),cluster, keyspace, Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE));\r
65         init(trans);\r
66     }\r
67 \r
68     public CredDAO(AuthzTrans trans, HistoryDAO hDao, CacheInfoDAO ciDao) throws APIException, IOException {\r
69         super(trans, CredDAO.class.getSimpleName(),hDao, Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE));\r
70         historyDAO = hDao;\r
71         infoDAO = ciDao;\r
72         init(trans);\r
73     }\r
74 \r
75     public static final int KEYLIMIT = 3;\r
76         public static class Data extends CacheableData implements Bytification {\r
77         \r
78                 public String                           id;\r
79         public Integer                          type;\r
80         public Date                                     expires;\r
81         public Integer                                  other;\r
82                 public String                                   ns;\r
83                 public String                                   notes;\r
84         public ByteBuffer                               cred;  //   this is a blob in cassandra\r
85 \r
86 \r
87         @Override\r
88                 public int[] invalidate(Cached<?,?> cache) {\r
89                 return new int[] {\r
90                         seg(cache,id) // cache is for all entities\r
91                 };\r
92                 }\r
93         \r
94                 @Override\r
95                 public ByteBuffer bytify() throws IOException {\r
96                         ByteArrayOutputStream baos = new ByteArrayOutputStream();\r
97                         CredLoader.deflt.marshal(this,new DataOutputStream(baos));\r
98                         return ByteBuffer.wrap(baos.toByteArray());\r
99                 }\r
100                 \r
101                 @Override\r
102                 public void reconstitute(ByteBuffer bb) throws IOException {\r
103                         CredLoader.deflt.unmarshal(this, toDIS(bb));\r
104                 }\r
105 \r
106                 public String toString() {\r
107                         return id + ' ' + type + ' ' + Chrono.dateTime(expires);\r
108                 }\r
109     }\r
110 \r
111     private static class CredLoader extends Loader<Data> implements Streamer<Data>{\r
112                 public static final int MAGIC=153323443;\r
113         public static final int VERSION=1;\r
114         public static final int BUFF_SIZE=48; // Note: \r
115 \r
116         public static final CredLoader deflt = new CredLoader(KEYLIMIT);\r
117         public CredLoader(int keylimit) {\r
118             super(keylimit);\r
119         }\r
120 \r
121         @Override\r
122         public Data load(Data data, Row row) {\r
123             data.id = row.getString(0);\r
124             data.type = row.getInt(1);    // NOTE: in datastax driver,  If the int value is NULL, 0 is returned!\r
125             data.expires = row.getDate(2);\r
126             data.other = row.getInt(3);\r
127             data.ns = row.getString(4);     \r
128             data.notes = row.getString(5);\r
129             data.cred = row.getBytesUnsafe(6);            \r
130             return data;\r
131         }\r
132 \r
133         @Override\r
134         protected void key(Data data, int _idx, Object[] obj) {\r
135             int idx = _idx;\r
136 \r
137             obj[idx] = data.id;\r
138             obj[++idx] = data.type;\r
139             obj[++idx] = data.expires;\r
140         }\r
141 \r
142         @Override\r
143         protected void body(Data data, int idx, Object[] obj) {\r
144             int i;\r
145             obj[i=idx] = data.other;\r
146             obj[++i] = data.ns;\r
147             obj[++i] = data.notes;\r
148             obj[++i] = data.cred;\r
149         }\r
150 \r
151                 @Override\r
152                 public void marshal(Data data, DataOutputStream os) throws IOException {\r
153                         writeHeader(os,MAGIC,VERSION);\r
154                         writeString(os, data.id);\r
155                         os.writeInt(data.type); \r
156                         os.writeLong(data.expires==null?-1:data.expires.getTime());\r
157                         os.writeInt(data.other==null?0:data.other);\r
158                         writeString(os, data.ns);\r
159                         writeString(os, data.notes);\r
160                         if(data.cred==null) {\r
161                                 os.writeInt(-1);\r
162                         } else {\r
163                                 int l = data.cred.limit()-data.cred.position();\r
164                                 os.writeInt(l);\r
165                                 os.write(data.cred.array(),data.cred.position(),l);\r
166                         }\r
167                 }\r
168 \r
169                 @Override\r
170                 public void unmarshal(Data data, DataInputStream is) throws IOException {\r
171                         /*int version = */readHeader(is,MAGIC,VERSION);\r
172                         // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields\r
173                         byte[] buff = new byte[BUFF_SIZE];\r
174                         data.id = readString(is,buff);\r
175                         data.type = is.readInt();\r
176                         \r
177                         long l = is.readLong();\r
178                         data.expires = l<0?null:new Date(l);\r
179                         data.other = is.readInt();\r
180                         data.ns = readString(is,buff);\r
181                         data.notes = readString(is,buff);\r
182                         \r
183                         int i = is.readInt();\r
184                         if(i<0) {\r
185                                 data.cred=null;\r
186                         } else {\r
187                                 byte[] bytes = new byte[i]; // a bit dangerous, but lessened because of all the previous sized data reads\r
188                                 is.read(bytes);\r
189                                 data.cred = ByteBuffer.wrap(bytes);\r
190                         }\r
191                 }\r
192     }\r
193 \r
194     private void init(AuthzTrans trans) throws APIException, IOException {\r
195         // Set up sub-DAOs\r
196         if(historyDAO==null) {\r
197                 historyDAO = new HistoryDAO(trans,this);\r
198         }\r
199                 if(infoDAO==null) {\r
200                         infoDAO = new CacheInfoDAO(trans,this);\r
201                 }\r
202                 \r
203 \r
204                 String[] helpers = setCRUD(trans, TABLE, Data.class, CredLoader.deflt);\r
205                 \r
206                 psNS = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE +\r
207                                 " WHERE ns = ?", CredLoader.deflt,readConsistency);\r
208                 \r
209                 psID = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE +\r
210                                 " WHERE id = ?", CredLoader.deflt,readConsistency);\r
211     }\r
212     \r
213         public Result<List<Data>> readNS(AuthzTrans trans, String ns) {\r
214                 return psNS.read(trans, R_TEXT, new Object[]{ns});\r
215         }\r
216         \r
217         public Result<List<Data>> readID(AuthzTrans trans, String id) {\r
218                 return psID.read(trans, R_TEXT, new Object[]{id});\r
219         }\r
220         \r
221     /**\r
222      * Log Modification statements to History\r
223      *\r
224      * @param modified        which CRUD action was done\r
225      * @param data            entity data that needs a log entry\r
226      * @param overrideMessage if this is specified, we use it rather than crafting a history message based on data\r
227      */\r
228     @Override\r
229     protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) {\r
230         boolean memo = override.length>0 && override[0]!=null;\r
231         boolean subject = override.length>1 && override[1]!=null;\r
232 \r
233         HistoryDAO.Data hd = HistoryDAO.newInitedData();\r
234         hd.user = trans.user();\r
235         hd.action = modified.name();\r
236         hd.target = TABLE;\r
237         hd.subject = subject?override[1]: data.id;\r
238         hd.memo = memo\r
239                 ? String.format("%s by %s", override[0], hd.user)\r
240                 : (modified.name() + "d credential for " + data.id);\r
241         // Detail?\r
242                 if(modified==CRUD.delete) {\r
243                                 try {\r
244                                         hd.reconstruct = data.bytify();\r
245                                 } catch (IOException e) {\r
246                                         trans.error().log(e,"Could not serialize CredDAO.Data");\r
247                                 }\r
248                         }\r
249 \r
250         if(historyDAO.create(trans, hd).status!=Status.OK) {\r
251                 trans.error().log("Cannot log to History");\r
252         }\r
253         if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).status!=Status.OK) {\r
254                 trans.error().log("Cannot touch Cred");\r
255         }\r
256     }\r
257 }\r