Update junits
[music.git] / music-core / src / main / java / org / onap / music / datastore / jsonobjects / JsonInsert.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
4  * ===================================================================
5  *  Copyright (c) 2017 AT&T Intellectual Property
6  *  Modifications Copyright (C) 2019 IBM 
7  * ===================================================================
8  *  Licensed under the Apache License, Version 2.0 (the "License");
9  *  you may not use this file except in compliance with the License.
10  *  You may obtain a copy of the License at
11  * 
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  *  Unless required by applicable law or agreed to in writing, software
15  *  distributed under the License is distributed on an "AS IS" BASIS,
16  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  *  See the License for the specific language governing permissions and
18  *  limitations under the License.
19  * 
20  * ============LICENSE_END=============================================
21  * ====================================================================
22  */
23
24 package org.onap.music.datastore.jsonobjects;
25
26 import java.io.ByteArrayOutputStream;
27 import java.io.IOException;
28 import java.io.ObjectOutput;
29 import java.io.ObjectOutputStream;
30 import java.io.Serializable;
31 import java.nio.ByteBuffer;
32 import java.util.List;
33 import java.util.Map;
34
35 import javax.ws.rs.core.MultivaluedMap;
36 import javax.ws.rs.core.Response.Status;
37
38 import org.onap.music.datastore.MusicDataStoreHandle;
39 import org.onap.music.datastore.PreparedQueryObject;
40 import org.onap.music.eelf.logging.EELFLoggerDelegate;
41 import org.onap.music.eelf.logging.format.AppMessages;
42 import org.onap.music.eelf.logging.format.ErrorSeverity;
43 import org.onap.music.eelf.logging.format.ErrorTypes;
44 import org.onap.music.exceptions.MusicQueryException;
45 import org.onap.music.exceptions.MusicServiceException;
46 import org.onap.music.main.MusicUtil;
47
48 import com.datastax.driver.core.DataType;
49 import com.datastax.driver.core.TableMetadata;
50 import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
51
52 import io.swagger.annotations.ApiModel;
53 import io.swagger.annotations.ApiModelProperty;
54
55 @ApiModel(value = "InsertTable", description = "Json model for table vlaues insert")
56 @JsonIgnoreProperties(ignoreUnknown = true)
57 public class JsonInsert implements Serializable {
58     private static final long serialVersionUID = 1L;
59     private String keyspaceName;
60     private String tableName;
61     private transient Map<String, Object> values;
62     private String ttl;
63     private String timestamp;
64     private transient Map<String, Object> rowSpecification;
65     private Map<String, String> consistencyInfo;
66     private Map<String, byte[]> objectMap;
67     private String primaryKeyVal;
68     private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonInsert.class);
69
70     @ApiModelProperty(value = "objectMap",hidden = true)
71     public Map<String, byte[]> getObjectMap() {
72         return objectMap;
73     }
74     
75     public void setObjectMap(Map<String, byte[]> objectMap) {
76         this.objectMap = objectMap;
77     }
78     
79     @ApiModelProperty(value = "keyspace")
80     public String getKeyspaceName() {
81         return keyspaceName;
82     }
83
84     public void setKeyspaceName(String keyspaceName) {
85         this.keyspaceName = keyspaceName;
86     }
87
88     @ApiModelProperty(value = "Table name")
89     public String getTableName() {
90         return tableName;
91     }
92
93     public void setTableName(String tableName) {
94         this.tableName = tableName;
95     }
96
97     @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic")
98     public Map<String, String> getConsistencyInfo() {
99         return consistencyInfo;
100     }
101
102     public void setConsistencyInfo(Map<String, String> consistencyInfo) {
103         this.consistencyInfo = consistencyInfo;
104     }
105
106     @ApiModelProperty(value = "Columns and tables support an optional "
107         + "expiration period called TTL (time-to-live) in seconds.",
108         notes="TTL precision is one second, which is calculated by the coordinator "
109         + "node. When using TTL, ensure that all nodes in the cluster have synchronized clocks.",allowEmptyValue = true)
110     public String getTtl() {
111         return ttl;
112     }
113
114     public void setTtl(String ttl) {
115         this.ttl = ttl;
116     }
117
118     @ApiModelProperty(value = "Time stamp (epoch_in_microseconds)",
119         notes = "Marks inserted data (write time) with TIMESTAMP. "
120         + "Enter the time since epoch (January 1, 1970) in microseconds."
121         + "By default, the actual time of write is used.", allowEmptyValue = true)
122     public String getTimestamp() {
123         return timestamp;
124     }
125
126     public void setTimestamp(String timestamp) {
127         this.timestamp = timestamp;
128     }
129
130     @ApiModelProperty(value = "Json Object of key/values", notes="Where key is the column name and value is the data value for that column.",
131         example = "{'emp_id': 'df98a3d40cd6','emp_name': 'john',"
132         + "'emp_salary': 50,'address':{'street' : '1 Some way','city' : 'New York'}}")
133     public Map<String, Object> getValues() {
134         return values;
135     }
136
137     public void setValues(Map<String, Object> values) {
138         this.values = values;
139     }
140
141     @ApiModelProperty(value = "Information for selecting specific rows for insert",hidden = true)
142     public Map<String, Object> getRowSpecification() {
143         return rowSpecification;
144     }
145
146     public void setRowSpecification(Map<String, Object> rowSpecification) {
147         this.rowSpecification = rowSpecification;
148     }
149     
150     public String getPrimaryKeyVal() {
151         return primaryKeyVal;
152     }
153
154     public void setPrimaryKeyVal(String primaryKeyVal) {
155         this.primaryKeyVal = primaryKeyVal;
156     }
157
158     public byte[] serialize() {
159         ByteArrayOutputStream bos = new ByteArrayOutputStream();
160         ObjectOutput out = null;
161         try {
162             out = new ObjectOutputStream(bos);
163             out.writeObject(this);
164         } catch (IOException e) {
165             logger.error(EELFLoggerDelegate.errorLogger, e, AppMessages.IOERROR, ErrorSeverity.ERROR, ErrorTypes.DATAERROR);
166         }
167         return bos.toByteArray();
168     }
169     
170     /**
171      * Generate TableInsertQuery
172      * @return
173      * @throws MusicQueryException
174      */
175     public PreparedQueryObject genInsertPreparedQueryObj() throws MusicQueryException {
176         PreparedQueryObject queryObject = new PreparedQueryObject();
177         TableMetadata tableInfo = null;
178         try {
179             tableInfo = MusicDataStoreHandle.returnColumnMetadata(this.getKeyspaceName(), this.getTableName());
180             if(tableInfo == null) {
181                 throw new MusicQueryException("Table name doesn't exists. Please check the table name.",
182                         Status.BAD_REQUEST.getStatusCode());
183             }
184         } catch (MusicServiceException e) {
185             logger.error(EELFLoggerDelegate.errorLogger, e, AppMessages.UNKNOWNERROR  ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
186             throw new MusicQueryException(e.getMessage(),Status.BAD_REQUEST.getStatusCode());
187             
188         }
189         String primaryKeyName = tableInfo.getPrimaryKey().get(0).getName();
190         StringBuilder fieldsString = new StringBuilder("(vector_ts,");
191         String vectorTs =
192                         String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
193         StringBuilder valueString = new StringBuilder("(" + "?" + ",");
194         queryObject.addValue(vectorTs);
195         
196         Map<String, Object> valuesMap = this.getValues();
197         if (valuesMap==null) {
198             throw new MusicQueryException("Nothing to insert. No values provided in request.",
199                     Status.BAD_REQUEST.getStatusCode());
200         }
201         int counter = 0;
202         String primaryKey = "";
203         for (Map.Entry<String, Object> entry : valuesMap.entrySet()) {
204             fieldsString.append("" + entry.getKey());
205             Object valueObj = entry.getValue();
206             if (primaryKeyName.equals(entry.getKey())) {
207                 primaryKey = entry.getValue() + "";
208                 primaryKey = primaryKey.replace("'", "''");
209             }
210             DataType colType = null;
211             try {
212                 colType = tableInfo.getColumn(entry.getKey()).getType();
213             } catch(NullPointerException ex) {
214                 logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() +" Invalid column name : "+entry.getKey
215                     (), AppMessages.INCORRECTDATA  ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR, ex);
216                 throw new MusicQueryException("Invalid column name : " + entry.getKey(),
217                         Status.BAD_REQUEST.getStatusCode());
218             }
219
220             Object formattedValue = null;
221             try {
222                 formattedValue = MusicUtil.convertToActualDataType(colType, valueObj);
223             } catch (Exception e) {
224                 logger.error(EELFLoggerDelegate.errorLogger,e);
225             }
226             valueString.append("?");
227
228             queryObject.addValue(formattedValue);
229
230             if (counter == valuesMap.size() - 1) {
231                 fieldsString.append(")");
232                 valueString.append(")");
233             } else {
234                 fieldsString.append(",");
235                 valueString.append(",");
236             }
237             counter = counter + 1;
238         }
239
240         //blobs..
241         Map<String, byte[]> objectMap = this.getObjectMap();
242         if(objectMap != null) {
243             for (Map.Entry<String, byte[]> entry : objectMap.entrySet()) {
244                 if(counter > 0) {
245                     fieldsString.replace(fieldsString.length()-1, fieldsString.length(), ",");
246                     valueString.replace(valueString.length()-1, valueString.length(), ",");
247                 }
248                 fieldsString.append("" + entry.getKey());
249                 byte[] valueObj = entry.getValue();
250                 if (primaryKeyName.equals(entry.getKey())) {
251                     primaryKey = entry.getValue() + "";
252                     primaryKey = primaryKey.replace("'", "''");
253                 }
254                 DataType colType = tableInfo.getColumn(entry.getKey()).getType();
255                 ByteBuffer formattedValue = null;
256                 if(colType.toString().toLowerCase().contains("blob")) {
257                     formattedValue = MusicUtil.convertToActualDataType(colType, valueObj);
258                 }
259                 valueString.append("?");
260                 queryObject.addValue(formattedValue);
261                 counter = counter + 1;
262                 fieldsString.append(",");
263                 valueString.append(",");
264             } 
265         }
266         this.setPrimaryKeyVal(primaryKey);
267         if(primaryKey == null || primaryKey.length() <= 0) {
268             logger.error(EELFLoggerDelegate.errorLogger, "Some required partition key parts are missing: "+primaryKeyName );
269             throw new MusicQueryException("Some required partition key parts are missing: " + primaryKeyName,
270                     Status.BAD_REQUEST.getStatusCode());
271         }
272
273         fieldsString.replace(fieldsString.length()-1, fieldsString.length(), ")");
274         valueString.replace(valueString.length()-1, valueString.length(), ")");
275
276         queryObject.appendQueryString("INSERT INTO " + this.getKeyspaceName() + "." + this.getTableName() + " "
277                         + fieldsString + " VALUES " + valueString);
278
279         String ttl = this.getTtl();
280         String timestamp = this.getTimestamp();
281
282         if ((ttl != null) && (timestamp != null)) {
283             logger.info(EELFLoggerDelegate.applicationLogger, "both there");
284             queryObject.appendQueryString(" USING TTL ? AND TIMESTAMP ?");
285             queryObject.addValue(Integer.parseInt(ttl));
286             queryObject.addValue(Long.parseLong(timestamp));
287         }
288
289         if ((ttl != null) && (timestamp == null)) {
290             logger.info(EELFLoggerDelegate.applicationLogger, "ONLY TTL there");
291             queryObject.appendQueryString(" USING TTL ?");
292             queryObject.addValue(Integer.parseInt(ttl));
293         }
294
295         if ((ttl == null) && (timestamp != null)) {
296             logger.info(EELFLoggerDelegate.applicationLogger, "ONLY timestamp there");
297             queryObject.appendQueryString(" USING TIMESTAMP ?");
298             queryObject.addValue(Long.parseLong(timestamp));
299         }
300
301         queryObject.appendQueryString(";");
302
303         String consistency = this.getConsistencyInfo().get("type");
304         if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL) && this.getConsistencyInfo().get("consistency") != null) {
305             if(MusicUtil.isValidConsistency(this.getConsistencyInfo().get("consistency"))) {
306                 queryObject.setConsistency(this.getConsistencyInfo().get("consistency"));
307             } else {
308                 throw new MusicQueryException("Invalid Consistency type", Status.BAD_REQUEST.getStatusCode());
309             }
310         }
311         queryObject.setOperation("insert");
312
313         logger.info("Data insert Query ::::: " + queryObject.getQuery());
314
315         return queryObject;
316     }
317     
318     /**
319      * 
320      * @param rowParams
321      * @return
322      * @throws MusicQueryException
323      */
324     public PreparedQueryObject genSelectCriticalPreparedQueryObj(MultivaluedMap<String, String> rowParams) throws MusicQueryException {
325         
326         PreparedQueryObject queryObject = new PreparedQueryObject();
327         
328         if((this.getKeyspaceName() == null || this.getKeyspaceName().isEmpty()) 
329                 || (this.getTableName() == null || this.getTableName().isEmpty())){
330             throw new MusicQueryException("one or more path parameters are not set, please check and try again",
331                      Status.BAD_REQUEST.getStatusCode());
332         }
333         EELFLoggerDelegate.mdcPut("keyspace", "( "+this.getKeyspaceName()+" ) ");
334         RowIdentifier rowId = null;
335         try {
336             rowId = getRowIdentifier(this.getKeyspaceName(), this.getTableName(), rowParams, queryObject);
337             this.setPrimaryKeyVal(rowId.primarKeyValue);
338         } catch (MusicServiceException ex) {
339             logger.error(EELFLoggerDelegate.errorLogger,ex, AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes
340                 .GENERALSERVICEERROR, ex);
341             throw new MusicQueryException(ex.getMessage(), Status.BAD_REQUEST.getStatusCode());
342         }
343         
344         queryObject.appendQueryString(
345             "SELECT *  FROM " + this.getKeyspaceName() + "." + this.getTableName() + " WHERE " + rowId.rowIdString + ";");
346         
347         return queryObject;
348     }
349     
350     private class RowIdentifier {
351         public String primarKeyValue;
352         public StringBuilder rowIdString;
353         @SuppressWarnings("unused")
354         public PreparedQueryObject queryObject; // the string with all the row
355                                                 // identifiers separated by AND
356
357         public RowIdentifier(String primaryKeyValue, StringBuilder rowIdString,
358                         PreparedQueryObject queryObject) {
359             this.primarKeyValue = primaryKeyValue;
360             this.rowIdString = rowIdString;
361             this.queryObject = queryObject;
362         }
363     }
364     
365     /**
366     *
367     * @param keyspace
368     * @param tablename
369     * @param rowParams
370     * @param queryObject
371     * @return
372     * @throws MusicServiceException
373     */
374    private RowIdentifier getRowIdentifier(String keyspace, String tablename,
375        MultivaluedMap<String, String> rowParams, PreparedQueryObject queryObject)
376        throws MusicServiceException {
377        StringBuilder rowSpec = new StringBuilder();
378        int counter = 0;
379        TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, tablename);
380        if (tableInfo == null) {
381            logger.error(EELFLoggerDelegate.errorLogger,
382                "Table information not found. Please check input for table name= "
383                + keyspace + "." + tablename);
384            throw new MusicServiceException(
385                "Table information not found. Please check input for table name= "
386                + keyspace + "." + tablename);
387        }
388        StringBuilder primaryKey = new StringBuilder();
389        for (MultivaluedMap.Entry<String, List<String>> entry : rowParams.entrySet()) {
390            String keyName = entry.getKey();
391            List<String> valueList = entry.getValue();
392            String indValue = valueList.get(0);
393            DataType colType = null;
394            Object formattedValue = null;
395            try {
396                colType = tableInfo.getColumn(entry.getKey()).getType();
397                formattedValue = MusicUtil.convertToActualDataType(colType, indValue);
398            } catch (Exception e) {
399                logger.error(EELFLoggerDelegate.errorLogger,e);
400            }
401            if(tableInfo.getPrimaryKey().get(0).getName().equals(entry.getKey())) {
402                primaryKey.append(indValue);
403            }
404            rowSpec.append(keyName + "= ?");
405            queryObject.addValue(formattedValue);
406            if (counter != rowParams.size() - 1) {
407                rowSpec.append(" AND ");
408            }
409            counter = counter + 1;
410        }
411        return new RowIdentifier(primaryKey.toString(), rowSpec, queryObject);
412     }
413
414
415 }