[AAF-21] Updated Copyright Headers for AAF
[aaf/authz.git] / authz-cass / src / main / java / com / att / dao / aaf / cass / CertDAO.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.math.BigInteger;\r
30 import java.nio.ByteBuffer;\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.datastax.driver.core.Cluster;\r
43 import com.datastax.driver.core.Row;\r
44 \r
45 /**\r
46  * CredDAO manages credentials. \r
47  * Date: 7/19/13\r
48  */\r
49 public class CertDAO extends CassDAOImpl<AuthzTrans,CertDAO.Data> {\r
50     public static final String TABLE = "x509";\r
51     public static final int CACHE_SEG = 0x40; // yields segment 0x0-0x3F\r
52     \r
53     private HistoryDAO historyDAO;\r
54         private CIDAO<AuthzTrans> infoDAO;\r
55         private PSInfo psX500,psID;\r
56         \r
57     public CertDAO(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException {\r
58         super(trans, CertDAO.class.getSimpleName(),cluster, keyspace, Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE));\r
59         init(trans);\r
60     }\r
61 \r
62     public CertDAO(AuthzTrans trans, HistoryDAO hDao, CacheInfoDAO ciDao) throws APIException, IOException {\r
63         super(trans, CertDAO.class.getSimpleName(),hDao, Data.class,TABLE, readConsistency(trans,TABLE), writeConsistency(trans,TABLE));\r
64         historyDAO = hDao;\r
65         infoDAO = ciDao;\r
66         init(trans);\r
67     }\r
68     \r
69     public static final int KEYLIMIT = 2;\r
70         public static class Data extends CacheableData implements Bytification {\r
71         \r
72         public String                                   ca;\r
73                 public BigInteger                               serial;\r
74         public String                           id;\r
75         public String                                   x500;\r
76         public String                                   x509;\r
77 \r
78         @Override\r
79                 public int[] invalidate(Cached<?,?> cache) {\r
80                 return new int[] {\r
81                         seg(cache,ca,serial)\r
82                 };\r
83                 }\r
84         \r
85                 @Override\r
86                 public ByteBuffer bytify() throws IOException {\r
87                         ByteArrayOutputStream baos = new ByteArrayOutputStream();\r
88                         CertLoader.deflt.marshal(this,new DataOutputStream(baos));\r
89                         return ByteBuffer.wrap(baos.toByteArray());\r
90                 }\r
91                 \r
92                 @Override\r
93                 public void reconstitute(ByteBuffer bb) throws IOException {\r
94                         CertLoader.deflt.unmarshal(this, toDIS(bb));\r
95                 }\r
96     }\r
97 \r
98     private static class CertLoader extends Loader<Data> implements Streamer<Data>{\r
99                 public static final int MAGIC=85102934;\r
100         public static final int VERSION=1;\r
101         public static final int BUFF_SIZE=48; // Note: \r
102 \r
103         public static final CertLoader deflt = new CertLoader(KEYLIMIT);\r
104         public CertLoader(int keylimit) {\r
105             super(keylimit);\r
106         }\r
107 \r
108         @Override\r
109         public Data load(Data data, Row row) {\r
110                 data.ca = row.getString(0);\r
111             ByteBuffer bb = row.getBytesUnsafe(1);\r
112             byte[] bytes = new byte[bb.remaining()];\r
113             bb.get(bytes);\r
114             data.serial = new BigInteger(bytes);\r
115             data.id = row.getString(2);\r
116             data.x500 = row.getString(3);\r
117             data.x509 = row.getString(4);\r
118             return data;\r
119         }\r
120 \r
121         @Override\r
122         protected void key(Data data, int idx, Object[] obj) {\r
123             obj[idx] = data.ca;\r
124             obj[++idx] = ByteBuffer.wrap(data.serial.toByteArray());\r
125         }\r
126 \r
127         @Override\r
128         protected void body(Data data, int _idx, Object[] obj) {\r
129                 int idx = _idx;\r
130 \r
131             obj[idx] = data.id;\r
132             obj[++idx] = data.x500;\r
133             obj[++idx] = data.x509;\r
134 \r
135             \r
136         }\r
137 \r
138                 @Override\r
139                 public void marshal(Data data, DataOutputStream os) throws IOException {\r
140                         writeHeader(os,MAGIC,VERSION);\r
141                         writeString(os, data.id);\r
142                         writeString(os, data.x500);\r
143                         writeString(os, data.x509);\r
144                         writeString(os, data.ca);\r
145                         if(data.serial==null) {\r
146                                 os.writeInt(-1);\r
147                         } else {\r
148                                 byte[] dsba = data.serial.toByteArray();\r
149                                 int l = dsba.length;\r
150                                 os.writeInt(l);\r
151                                 os.write(dsba,0,l);\r
152                         }\r
153                 }\r
154 \r
155                 @Override\r
156                 public void unmarshal(Data data, DataInputStream is) throws IOException {\r
157                         /*int version = */readHeader(is,MAGIC,VERSION);\r
158                         // If Version Changes between Production runs, you'll need to do a switch Statement, and adequately read in fields\r
159                         byte[] buff = new byte[BUFF_SIZE];\r
160                         data.id = readString(is,buff);\r
161                         data.x500 = readString(is,buff);\r
162                         data.x509 = readString(is,buff);\r
163                         data.ca = readString(is,buff);\r
164                         int i = is.readInt();\r
165                         if(i<0) {\r
166                                 data.serial=null;\r
167                         } else {\r
168                                 byte[] bytes = new byte[i]; // a bit dangerous, but lessened because of all the previous sized data reads\r
169                                 is.read(bytes);\r
170                                 data.serial = new BigInteger(bytes);\r
171                         }\r
172                 }\r
173     }\r
174     \r
175     public Result<List<CertDAO.Data>> read(AuthzTrans trans, Object ... key) {\r
176         // Translate BigInteger to Byte array for lookup\r
177         return super.read(trans, key[0],ByteBuffer.wrap(((BigInteger)key[1]).toByteArray()));\r
178     }\r
179 \r
180     private void init(AuthzTrans trans) throws APIException, IOException {\r
181         // Set up sub-DAOs\r
182         if(historyDAO==null) {\r
183                 historyDAO = new HistoryDAO(trans,this);\r
184         }\r
185                 if(infoDAO==null) {\r
186                         infoDAO = new CacheInfoDAO(trans,this);\r
187                 }\r
188 \r
189                 String[] helpers = setCRUD(trans, TABLE, Data.class, CertLoader.deflt);\r
190 \r
191                 psID = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE +\r
192                                 " WHERE id = ?", CertLoader.deflt,readConsistency);\r
193 \r
194                 psX500 = new PSInfo(trans, SELECT_SP + helpers[FIELD_COMMAS] + " FROM " + TABLE +\r
195                                 " WHERE x500 = ?", CertLoader.deflt,readConsistency);\r
196                 \r
197     }\r
198     \r
199         public Result<List<Data>> readX500(AuthzTrans trans, String x500) {\r
200                 return psX500.read(trans, R_TEXT, new Object[]{x500});\r
201         }\r
202 \r
203         public Result<List<Data>> readID(AuthzTrans trans, String id) {\r
204                 return psID.read(trans, R_TEXT, new Object[]{id});\r
205         }\r
206 \r
207     /**\r
208      * Log Modification statements to History\r
209      *\r
210      * @param modified        which CRUD action was done\r
211      * @param data            entity data that needs a log entry\r
212      * @param overrideMessage if this is specified, we use it rather than crafting a history message based on data\r
213      */\r
214     @Override\r
215     protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) {\r
216         boolean memo = override.length>0 && override[0]!=null;\r
217         boolean subject = override.length>1 && override[1]!=null;\r
218 \r
219         HistoryDAO.Data hd = HistoryDAO.newInitedData();\r
220         hd.user = trans.user();\r
221         hd.action = modified.name();\r
222         hd.target = TABLE;\r
223         hd.subject = subject?override[1]: data.id;\r
224         hd.memo = memo\r
225                 ? String.format("%s by %s", override[0], hd.user)\r
226                 : (modified.name() + "d certificate info for " + data.id);\r
227         // Detail?\r
228                 if(modified==CRUD.delete) {\r
229                                 try {\r
230                                         hd.reconstruct = data.bytify();\r
231                                 } catch (IOException e) {\r
232                                         trans.error().log(e,"Could not serialize CertDAO.Data");\r
233                                 }\r
234                         }\r
235 \r
236         if(historyDAO.create(trans, hd).status!=Status.OK) {\r
237                 trans.error().log("Cannot log to History");\r
238         }\r
239         if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).status!=Status.OK) {\r
240                 trans.error().log("Cannot touch Cert");\r
241         }\r
242     }\r
243 }\r