2 * ============LICENSE_START==========================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 * ============LICENSE_END=============================================
21 * ====================================================================
24 package org.onap.music.datastore.jsonobjects;
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;
35 import javax.ws.rs.core.MultivaluedMap;
36 import javax.ws.rs.core.Response.Status;
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;
48 import com.datastax.driver.core.DataType;
49 import com.datastax.driver.core.TableMetadata;
50 import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
52 import io.swagger.annotations.ApiModel;
53 import io.swagger.annotations.ApiModelProperty;
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;
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);
70 @ApiModelProperty(value = "objectMap",hidden = true)
71 public Map<String, byte[]> getObjectMap() {
75 public void setObjectMap(Map<String, byte[]> objectMap) {
76 this.objectMap = objectMap;
79 @ApiModelProperty(value = "keyspace")
80 public String getKeyspaceName() {
84 public void setKeyspaceName(String keyspaceName) {
85 this.keyspaceName = keyspaceName;
88 @ApiModelProperty(value = "Table name")
89 public String getTableName() {
93 public void setTableName(String tableName) {
94 this.tableName = tableName;
97 @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic")
98 public Map<String, String> getConsistencyInfo() {
99 return consistencyInfo;
102 public void setConsistencyInfo(Map<String, String> consistencyInfo) {
103 this.consistencyInfo = consistencyInfo;
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() {
114 public void setTtl(String ttl) {
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() {
126 public void setTimestamp(String timestamp) {
127 this.timestamp = timestamp;
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() {
137 public void setValues(Map<String, Object> values) {
138 this.values = values;
141 @ApiModelProperty(value = "Information for selecting specific rows for insert",hidden = true)
142 public Map<String, Object> getRowSpecification() {
143 return rowSpecification;
146 public void setRowSpecification(Map<String, Object> rowSpecification) {
147 this.rowSpecification = rowSpecification;
150 public String getPrimaryKeyVal() {
151 return primaryKeyVal;
154 public void setPrimaryKeyVal(String primaryKeyVal) {
155 this.primaryKeyVal = primaryKeyVal;
158 public byte[] serialize() {
159 ByteArrayOutputStream bos = new ByteArrayOutputStream();
160 ObjectOutput out = null;
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);
167 return bos.toByteArray();
171 * Generate TableInsertQuery
173 * @throws MusicQueryException
175 public PreparedQueryObject genInsertPreparedQueryObj() throws MusicQueryException {
176 PreparedQueryObject queryObject = new PreparedQueryObject();
177 TableMetadata tableInfo = null;
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());
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());
189 String primaryKeyName = tableInfo.getPrimaryKey().get(0).getName();
190 StringBuilder fieldsString = new StringBuilder("(vector_ts,");
192 String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
193 StringBuilder valueString = new StringBuilder("(" + "?" + ",");
194 queryObject.addValue(vectorTs);
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());
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("'", "''");
210 DataType colType = null;
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());
220 Object formattedValue = null;
222 formattedValue = MusicUtil.convertToActualDataType(colType, valueObj);
223 } catch (Exception e) {
224 logger.error(EELFLoggerDelegate.errorLogger,e);
226 valueString.append("?");
228 queryObject.addValue(formattedValue);
230 if (counter == valuesMap.size() - 1) {
231 fieldsString.append(")");
232 valueString.append(")");
234 fieldsString.append(",");
235 valueString.append(",");
237 counter = counter + 1;
241 Map<String, byte[]> objectMap = this.getObjectMap();
242 if(objectMap != null) {
243 for (Map.Entry<String, byte[]> entry : objectMap.entrySet()) {
245 fieldsString.replace(fieldsString.length()-1, fieldsString.length(), ",");
246 valueString.replace(valueString.length()-1, valueString.length(), ",");
248 fieldsString.append("" + entry.getKey());
249 byte[] valueObj = entry.getValue();
250 if (primaryKeyName.equals(entry.getKey())) {
251 primaryKey = entry.getValue() + "";
252 primaryKey = primaryKey.replace("'", "''");
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);
259 valueString.append("?");
260 queryObject.addValue(formattedValue);
261 counter = counter + 1;
262 fieldsString.append(",");
263 valueString.append(",");
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());
273 fieldsString.replace(fieldsString.length()-1, fieldsString.length(), ")");
274 valueString.replace(valueString.length()-1, valueString.length(), ")");
276 queryObject.appendQueryString("INSERT INTO " + this.getKeyspaceName() + "." + this.getTableName() + " "
277 + fieldsString + " VALUES " + valueString);
279 String ttl = this.getTtl();
280 String timestamp = this.getTimestamp();
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));
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));
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));
301 queryObject.appendQueryString(";");
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"));
308 throw new MusicQueryException("Invalid Consistency type", Status.BAD_REQUEST.getStatusCode());
311 queryObject.setOperation("insert");
313 logger.info("Data insert Query ::::: " + queryObject.getQuery());
322 * @throws MusicQueryException
324 public PreparedQueryObject genSelectCriticalPreparedQueryObj(MultivaluedMap<String, String> rowParams) throws MusicQueryException {
326 PreparedQueryObject queryObject = new PreparedQueryObject();
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());
333 EELFLoggerDelegate.mdcPut("keyspace", "( "+this.getKeyspaceName()+" ) ");
334 RowIdentifier rowId = null;
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());
344 queryObject.appendQueryString(
345 "SELECT * FROM " + this.getKeyspaceName() + "." + this.getTableName() + " WHERE " + rowId.rowIdString + ";");
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
357 public RowIdentifier(String primaryKeyValue, StringBuilder rowIdString,
358 PreparedQueryObject queryObject) {
359 this.primarKeyValue = primaryKeyValue;
360 this.rowIdString = rowIdString;
361 this.queryObject = queryObject;
372 * @throws MusicServiceException
374 private RowIdentifier getRowIdentifier(String keyspace, String tablename,
375 MultivaluedMap<String, String> rowParams, PreparedQueryObject queryObject)
376 throws MusicServiceException {
377 StringBuilder rowSpec = new StringBuilder();
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);
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;
396 colType = tableInfo.getColumn(entry.getKey()).getType();
397 formattedValue = MusicUtil.convertToActualDataType(colType, indValue);
398 } catch (Exception e) {
399 logger.error(EELFLoggerDelegate.errorLogger,e);
401 if(tableInfo.getPrimaryKey().get(0).getName().equals(entry.getKey())) {
402 primaryKey.append(indValue);
404 rowSpec.append(keyName + "= ?");
405 queryObject.addValue(formattedValue);
406 if (counter != rowParams.size() - 1) {
407 rowSpec.append(" AND ");
409 counter = counter + 1;
411 return new RowIdentifier(primaryKey.toString(), rowSpec, queryObject);