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