0c30cc74f2ecde567a918850bdd6b1ca9df4d6b6
[music.git] / src / main / java / org / onap / music / service / impl / MusicCassaCore.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
4  * ===================================================================
5  *  Copyright (c) 2017 AT&T Intellectual Property
6  *  Modifications Copyright (c) 2018 IBM. 
7  * ===================================================================
8  *  Modifications Copyright (c) 2019 Samsung
9  * ===================================================================
10  *  Licensed under the Apache License, Version 2.0 (the "License");
11  *  you may not use this file except in compliance with the License.
12  *  You may obtain a copy of the License at
13  *
14  *     http://www.apache.org/licenses/LICENSE-2.0
15  *
16  *  Unless required by applicable law or agreed to in writing, software
17  *  distributed under the License is distributed on an "AS IS" BASIS,
18  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  *  See the License for the specific language governing permissions and
20  *  limitations under the License.
21  *
22  * ============LICENSE_END=============================================
23  * ====================================================================
24  */
25
26 package org.onap.music.service.impl;
27
28 import java.io.StringWriter;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.StringTokenizer;
32
33 import javax.ws.rs.core.MultivaluedMap;
34
35 import org.onap.music.datastore.Condition;
36 import org.onap.music.datastore.MusicDataStore;
37 import org.onap.music.datastore.MusicDataStoreHandle;
38 import org.onap.music.datastore.PreparedQueryObject;
39 import org.onap.music.datastore.jsonobjects.JsonDelete;
40 import org.onap.music.datastore.jsonobjects.JsonIndex;
41 import org.onap.music.datastore.jsonobjects.JsonInsert;
42 import org.onap.music.datastore.jsonobjects.JsonKeySpace;
43 import org.onap.music.datastore.jsonobjects.JsonSelect;
44 import org.onap.music.datastore.jsonobjects.JsonTable;
45 import org.onap.music.datastore.jsonobjects.JsonUpdate;
46 import org.onap.music.eelf.logging.EELFLoggerDelegate;
47 import org.onap.music.eelf.logging.format.AppMessages;
48 import org.onap.music.eelf.logging.format.ErrorSeverity;
49 import org.onap.music.eelf.logging.format.ErrorTypes;
50 import org.onap.music.exceptions.MusicDeadlockException;
51 import org.onap.music.exceptions.MusicLockingException;
52 import org.onap.music.exceptions.MusicQueryException;
53 import org.onap.music.exceptions.MusicServiceException;
54 import org.onap.music.lockingservice.cassandra.CassaLockStore;
55 import org.onap.music.lockingservice.cassandra.CassaLockStore.LockObject;
56 import org.onap.music.lockingservice.cassandra.LockType;
57 import org.onap.music.lockingservice.cassandra.MusicLockState;
58 import org.onap.music.lockingservice.cassandra.MusicLockState.LockStatus;
59 import org.onap.music.main.MusicUtil;
60 import org.onap.music.main.ResultType;
61 import org.onap.music.main.ReturnType;
62 import org.onap.music.service.MusicCoreService;
63
64 import com.datastax.driver.core.DataType;
65 import com.datastax.driver.core.ResultSet;
66 import com.datastax.driver.core.Row;
67 import com.datastax.driver.core.TableMetadata;
68
69 public class MusicCassaCore implements MusicCoreService {
70
71     private static CassaLockStore mLockHandle = null;
72     private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicCassaCore.class);
73     private static MusicCassaCore musicCassaCoreInstance = null;
74
75     private MusicCassaCore() {
76         // not going to happen
77     }
78     
79     public static CassaLockStore getmLockHandle() {
80         return mLockHandle;
81     }
82
83     public static void setmLockHandle(CassaLockStore mLockHandle) {
84         MusicCassaCore.mLockHandle = mLockHandle;
85     }
86     
87     public static MusicCassaCore getInstance() {
88
89         if(musicCassaCoreInstance == null) {
90             musicCassaCoreInstance = new MusicCassaCore();
91         }
92         return musicCassaCoreInstance;
93     }
94
95
96
97
98     public static CassaLockStore getLockingServiceHandle() throws MusicLockingException {
99         logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring lock store handle");
100         long start = System.currentTimeMillis();
101
102         if (mLockHandle == null) {
103             try {
104                 mLockHandle = new CassaLockStore(MusicDataStoreHandle.getDSHandle());
105             } catch (Exception e) {
106                 logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKHANDLE,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
107                 throw new MusicLockingException("Failed to aquire Locl store handle " + e);
108             }
109         }
110         long end = System.currentTimeMillis();
111         logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to acquire lock store handle:" + (end - start) + " ms");
112         return mLockHandle;
113     }
114
115     public String createLockReference(String fullyQualifiedKey) throws MusicLockingException {
116         return createLockReference(fullyQualifiedKey, LockType.WRITE);
117     }
118
119     public String createLockReference(String fullyQualifiedKey, LockType locktype) throws MusicLockingException {
120         return createLockReference(fullyQualifiedKey, locktype, null);
121     }
122
123     public String createLockReference(String fullyQualifiedKey, LockType locktype, String owner) throws MusicLockingException {
124         String[] splitString = fullyQualifiedKey.split("\\.");
125         String keyspace = splitString[0];
126         String table = splitString[1];
127         String lockName = splitString[2];
128
129         logger.info(EELFLoggerDelegate.applicationLogger,"Creating lock reference for lock name:" + lockName);
130         long start = System.currentTimeMillis();
131         String lockReference = null;
132
133         try {
134             boolean deadlock = getLockingServiceHandle().checkForDeadlock(keyspace, table, lockName, locktype, owner, false);
135             if (deadlock) {
136                 MusicDeadlockException e = new MusicDeadlockException("Deadlock detected when " + owner + " tried to create lock on " + keyspace + "." + table + "." + lockName);
137                 e.setValues(owner, keyspace, table, lockName);
138                 throw e;
139             }
140         } catch (MusicDeadlockException e) {
141             //just threw this, no need to wrap it
142             throw e;
143         } catch (MusicServiceException | MusicQueryException e) {
144             logger.error(EELFLoggerDelegate.applicationLogger, e);
145             throw new MusicLockingException("Unable to check for deadlock. " + e.getMessage(), e);
146         }
147         
148         try {
149             lockReference = "" + getLockingServiceHandle().genLockRefandEnQueue(keyspace, table, lockName, locktype, owner);
150         } catch (MusicLockingException | MusicServiceException | MusicQueryException e) {
151             logger.error(EELFLoggerDelegate.applicationLogger, e);
152             throw new MusicLockingException("Unable to create lock reference. " + e.getMessage(), e);
153         } catch (Exception e) {
154             logger.error(EELFLoggerDelegate.applicationLogger, e);
155             throw new MusicLockingException("Unable to create lock reference. " + e.getMessage(), e);
156         }
157         long end = System.currentTimeMillis();
158         logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to create lock reference:" + (end - start) + " ms");
159         return lockReference;
160     }
161
162
163     public ReturnType acquireLockWithLease(String fullyQualifiedKey, String lockReference, long leasePeriod)
164             throws MusicLockingException, MusicQueryException, MusicServiceException  {
165         evictExpiredLockHolder(fullyQualifiedKey,leasePeriod);
166         return acquireLock(fullyQualifiedKey, lockReference);
167     }
168
169     private void evictExpiredLockHolder(String fullyQualifiedKey, long leasePeriod)
170             throws MusicLockingException, MusicQueryException, MusicServiceException {
171         String[] splitString = fullyQualifiedKey.split("\\.");
172         String keyspace = splitString[0];
173         String table = splitString[1];
174         String primaryKeyValue = splitString[2];
175
176         LockObject currentLockHolderObject = getLockingServiceHandle().peekLockQueue(keyspace, table, primaryKeyValue);
177
178         if (!currentLockHolderObject.getIsLockOwner()) { // no lock holder
179             return;
180         }
181         /*
182          * Release the lock of the previous holder if it has expired. if the update to the acquire time has
183          * not reached due to network delays, simply use the create time as the reference
184          */
185         long referenceTime = Math.max(Long.parseLong(currentLockHolderObject.getAcquireTime()),
186                 Long.parseLong(currentLockHolderObject.getCreateTime()));
187         if ((System.currentTimeMillis() - referenceTime) > leasePeriod) {
188             forciblyReleaseLock(fullyQualifiedKey, currentLockHolderObject.getLockRef() + "");
189             logger.info(EELFLoggerDelegate.applicationLogger, currentLockHolderObject.getLockRef() + " forcibly released");
190         }
191     }
192
193     public ReturnType acquireLock(String fullyQualifiedKey, String lockId)
194             throws MusicLockingException, MusicQueryException, MusicServiceException {
195         String[] splitString = lockId.split("\\.");
196         String keyspace = splitString[0].substring(1);//remove '$'
197         String table = splitString[1];
198         String primaryKeyValue = splitString[2].substring(0, splitString[2].lastIndexOf("$"));
199         String localFullyQualifiedKey = lockId.substring(1, lockId.lastIndexOf("$"));
200         String lockRef = lockId.substring(lockId.lastIndexOf("$")+1); //lockRef is "$" to end
201
202         LockObject lockInfo = getLockingServiceHandle().getLockInfo(keyspace, table, primaryKeyValue, lockRef);
203
204         if (!lockInfo.getIsLockOwner()) {
205             return new ReturnType(ResultType.FAILURE, lockId + " is not a lock holder");//not top of the lock store q
206         }
207         
208         if (getLockingServiceHandle().checkForDeadlock(keyspace, table, primaryKeyValue, lockInfo.getLocktype(), lockInfo.getOwner(), true)) {
209             MusicDeadlockException e = new MusicDeadlockException("Deadlock detected when " + lockInfo.getOwner()  + " tried to create lock on " + keyspace + "." + table + "." + primaryKeyValue);
210             e.setValues(lockInfo.getOwner(), keyspace, table, primaryKeyValue);
211             throw e;
212         }
213
214         //check to see if the value of the key has to be synced in case there was a forceful release
215         String syncTable = keyspace+".unsyncedKeys_"+table;
216         String query = "select * from "+syncTable+" where key='"+localFullyQualifiedKey+"';";
217         PreparedQueryObject readQueryObject = new PreparedQueryObject();
218         readQueryObject.appendQueryString(query);
219         ResultSet results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(readQueryObject);
220         if (!results.all().isEmpty()) {
221             logger.info("In acquire lock: Since there was a forcible release, need to sync quorum!");
222             try {
223                 syncQuorum(keyspace, table, primaryKeyValue);
224             } catch (Exception e) {
225                 StringWriter sw = new StringWriter();
226                     logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR506E] Failed to aquire lock ",
227                         ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR, e);
228                 String exceptionAsString = sw.toString();
229                 return new ReturnType(ResultType.FAILURE, "Exception thrown while syncing key:\n" + exceptionAsString);
230             }
231             String cleanQuery = "delete from " + syncTable + " where key='"+localFullyQualifiedKey+"';";
232             PreparedQueryObject deleteQueryObject = new PreparedQueryObject();
233             deleteQueryObject.appendQueryString(cleanQuery);
234             MusicDataStoreHandle.getDSHandle().executePut(deleteQueryObject, "critical");
235         }
236
237         getLockingServiceHandle().updateLockAcquireTime(keyspace, table, primaryKeyValue, lockRef);
238
239         return new ReturnType(ResultType.SUCCESS, lockRef+" is the lock holder for the key");
240     }
241
242
243
244     /**
245      *
246      * @param tableQueryObject
247      * @param consistency
248      * @return Boolean Indicates success or failure
249      * @throws MusicServiceException
250      *
251      *
252      */
253     public ResultType createTable(String keyspace, String table, PreparedQueryObject tableQueryObject,
254             String consistency) throws MusicServiceException {
255         boolean result = false;
256
257         try {
258             // create shadow locking table
259             result = getLockingServiceHandle().createLockQueue(keyspace, table);
260             if (result == false)
261                 return ResultType.FAILURE;
262
263             result = false;
264
265             // create table to track unsynced_keys
266             table = "unsyncedKeys_" + table;
267
268             String tabQuery =
269                     "CREATE TABLE IF NOT EXISTS " + keyspace + "." + table + " ( key text,PRIMARY KEY (key) );";
270             PreparedQueryObject queryObject = new PreparedQueryObject();
271
272             queryObject.appendQueryString(tabQuery);
273             result = false;
274             result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, "eventual");
275
276             // create actual table
277             result = MusicDataStoreHandle.getDSHandle().executePut(tableQueryObject, consistency);
278         } catch (MusicQueryException | MusicServiceException | MusicLockingException ex) {
279             logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), AppMessages.UNKNOWNERROR, ErrorSeverity.WARN,
280                     ErrorTypes.MUSICSERVICEERROR);
281             throw new MusicServiceException(ex.getMessage());
282         }
283         return result ? ResultType.SUCCESS : ResultType.FAILURE;
284     }
285
286     private static void syncQuorum(String keyspace, String table, String primaryKeyValue) throws Exception {
287         logger.info(EELFLoggerDelegate.applicationLogger,"Performing sync operation---");
288         PreparedQueryObject selectQuery = new PreparedQueryObject();
289         PreparedQueryObject updateQuery = new PreparedQueryObject();
290
291         // get the primary key d
292         TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, table);
293         String primaryKeyName = tableInfo.getPrimaryKey().get(0).getName(); // we only support single
294                                                                             // primary key
295         DataType primaryKeyType = tableInfo.getPrimaryKey().get(0).getType();
296         Object cqlFormattedPrimaryKeyValue =
297                         MusicUtil.convertToActualDataType(primaryKeyType, primaryKeyValue);
298
299         // get the row of data from a quorum
300         selectQuery.appendQueryString("SELECT *  FROM " + keyspace + "." + table + " WHERE "
301                         + primaryKeyName + "= ?" + ";");
302         selectQuery.addValue(cqlFormattedPrimaryKeyValue);
303         MusicUtil.writeBackToQuorum(selectQuery, primaryKeyName, updateQuery, keyspace, table,
304             cqlFormattedPrimaryKeyValue);
305     }
306
307     /**
308      *
309      * @param query
310      * @return ResultSet
311      */
312     public ResultSet quorumGet(PreparedQueryObject query) {
313         ResultSet results = null;
314         try {
315             results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(query);
316         } catch (MusicServiceException | MusicQueryException e) {
317             logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,
318                 ErrorSeverity.MAJOR, ErrorTypes.GENERALSERVICEERROR, e);
319
320         }
321         return results;
322     }
323
324     public String whoseTurnIsIt(String fullyQualifiedKey) {
325         String[] splitString = fullyQualifiedKey.split("\\.");
326         String keyspace = splitString[0];
327         String table = splitString[1];
328         String primaryKeyValue = splitString[2];
329         try {
330             LockObject lockOwner = getLockingServiceHandle().peekLockQueue(keyspace, table, primaryKeyValue);
331             if (!lockOwner.getIsLockOwner()) {
332                 return null;
333             }
334             return "$" + fullyQualifiedKey + "$" + lockOwner.getLockRef();
335         } catch (MusicLockingException | MusicServiceException | MusicQueryException e) {
336             logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.LOCKINGERROR + fullyQualifiedKey,
337                     ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
338         }
339         return null;
340     }
341     
342     public List<String> getCurrentLockHolders(String fullyQualifiedKey) {
343         String[] splitString = fullyQualifiedKey.split("\\.");
344         String keyspace = splitString[0];
345         String table = splitString[1];
346         String primaryKeyValue = splitString[2];
347         try {
348             return getLockingServiceHandle().getCurrentLockHolders(keyspace, table, primaryKeyValue);
349         } catch (MusicLockingException | MusicServiceException | MusicQueryException e) {
350             logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKINGERROR+fullyQualifiedKey ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
351         }
352         return null;
353     }
354
355     /**
356      *
357      * @param lockReference
358      * @return
359      */
360     public static String getLockNameFromId(String lockReference) {
361         StringTokenizer st = new StringTokenizer(lockReference);
362         return st.nextToken("$");
363     }
364
365     @Override
366     public void destroyLockRef(String lockId) throws MusicLockingException {
367         long start = System.currentTimeMillis();
368         String fullyQualifiedKey = lockId.substring(1, lockId.lastIndexOf("$"));
369         String lockRef = lockId.substring(lockId.lastIndexOf('$')+1);
370         String[] splitString = fullyQualifiedKey.split("\\.");
371         String keyspace = splitString[0];
372         String table = splitString[1];
373         String primaryKeyValue = splitString[2];
374         try {
375             getLockingServiceHandle().deQueueLockRef(keyspace, table, primaryKeyValue, lockRef,MusicUtil.getRetryCount());
376         } catch (MusicLockingException | MusicServiceException | MusicQueryException e) {
377             logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DESTROYLOCK+lockRef,
378                 ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR, e);
379             throw new MusicLockingException(e.getMessage());
380         }
381         long end = System.currentTimeMillis();
382         logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to destroy lock reference:" + (end - start) + " ms");
383     }
384
385     public MusicLockState destroyLockRef(String fullyQualifiedKey, String lockReference) throws MusicLockingException {
386         long start = System.currentTimeMillis();
387         String[] splitString = fullyQualifiedKey.split("\\.");
388         String keyspace = splitString[0];
389         String table = splitString[1];
390         String primaryKeyValue = splitString[2];
391         try {
392             getLockingServiceHandle().deQueueLockRef(keyspace, table, primaryKeyValue, lockReference,MusicUtil.getRetryCount());
393         } catch (MusicLockingException | MusicServiceException | MusicQueryException e) {
394             logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DESTROYLOCK + lockReference,
395                 ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR,e);
396             throw new MusicLockingException(e.getMessage());
397         }
398         long end = System.currentTimeMillis();
399         logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to destroy lock reference:" + (end - start) + " ms");
400         return new MusicLockState(LockStatus.UNLOCKED, "");
401     }
402
403     @Override
404     public MusicLockState releaseLock(String lockId, boolean voluntaryRelease) throws MusicLockingException {
405         String fullyQualifiedKey = lockId.substring(1, lockId.lastIndexOf("$"));
406         String lockRef = lockId.substring(lockId.lastIndexOf('$')+1);
407         if (voluntaryRelease) {
408             return voluntaryReleaseLock(fullyQualifiedKey, lockRef);
409         } else {
410             return forciblyReleaseLock(fullyQualifiedKey, lockRef);
411         }
412     }
413
414     public MusicLockState voluntaryReleaseLock(String fullyQualifiedKey, String lockReference)
415             throws MusicLockingException {
416         MusicLockState result = null;
417         try {
418             result = destroyLockRef(fullyQualifiedKey, lockReference);
419         } catch (Exception ex) {
420             logger.info(EELFLoggerDelegate.applicationLogger,
421                     "Exception in voluntaryReleaseLock() for " + fullyQualifiedKey + "ref: " + lockReference);
422             throw new MusicLockingException(ex.getMessage());
423         }
424         return result;
425     }
426
427     public MusicLockState forciblyReleaseLock(String fullyQualifiedKey, String lockReference) throws MusicLockingException {
428         String[] splitString = fullyQualifiedKey.split("\\.");
429         String keyspace = splitString[0];
430         String table = splitString[1];
431
432         //leave a signal that this key could potentially be unsynchronized
433         String syncTable = keyspace+".unsyncedKeys_"+table;
434         PreparedQueryObject queryObject = new PreparedQueryObject();
435         String values = "(?)";
436         queryObject.addValue(fullyQualifiedKey);
437         String insQuery = "insert into "+syncTable+" (key) values "+values+";";
438         queryObject.appendQueryString(insQuery);
439         try {
440             MusicDataStoreHandle.getDSHandle().executePut(queryObject, "critical");
441         } catch (Exception e) {
442             logger.error("Cannot forcibly release lock: " + fullyQualifiedKey + " " + lockReference + ". "
443                         + e.getMessage(), e);
444         }
445
446         //now release the lock
447         return destroyLockRef(fullyQualifiedKey, lockReference);
448     }
449
450     @Override
451     public List<String> releaseAllLocksForOwner(String ownerId, String keyspace, String table) throws MusicLockingException, MusicServiceException, MusicQueryException {
452 //        System.out.println("IN RELEASEALLLOCKSFOROWNER, ");
453
454         List<String> lockIds = getLockingServiceHandle().getAllLocksForOwner(ownerId, keyspace, table);
455         for (String lockId : lockIds) {
456 //            System.out.println(" LOCKID = " + lockId);
457             //return "$" + keyspace + "." + table + "." + lockName + "$" + String.valueOf(lockRef);
458             releaseLock("$" + keyspace + "." + table + "." + lockId, true);
459         }
460         return lockIds;
461     }
462
463     /**
464      *
465      * @param lockName
466      * @throws MusicLockingException
467      */
468     @Deprecated
469     public  void deleteLock(String lockName) throws MusicLockingException {
470         throw new MusicLockingException("Depreciated Method Delete Lock");
471     }
472
473     // Prepared Query Additions.
474
475     /**
476      *
477      * @param queryObject
478      * @return ReturnType
479      * @throws MusicServiceException
480      */
481     public  ReturnType eventualPut(PreparedQueryObject queryObject) {
482         boolean result = false;
483         try {
484             result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, MusicUtil.EVENTUAL);
485         } catch (MusicServiceException | MusicQueryException ex) {
486             logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), "[ERR512E] Failed to get Lock Handle "  ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
487             logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() + "  " + ex.getCause() + " " + ex);
488             return new ReturnType(ResultType.FAILURE, ex.getMessage());
489         }
490         if (result) {
491             return new ReturnType(ResultType.SUCCESS, "Eventual Operation Successfully performed");
492         } else {
493             return new ReturnType(ResultType.FAILURE, "Eventual Operation failed to perform");
494         }
495     }
496
497     /**
498      *
499      * @param queryObject
500      * @return ReturnType
501      * @throws MusicServiceException
502      */
503     public  ReturnType eventualPut_nb(PreparedQueryObject queryObject,String keyspace,String tablename,String primaryKey) {
504         boolean result = false;
505         long guard = 0;
506         PreparedQueryObject getGaurd = new PreparedQueryObject();
507         getGaurd.appendQueryString("SELECT guard FROM "+keyspace+".lockq_"+tablename+ " WHERE key = ? ;");
508         getGaurd.addValue(primaryKey);
509         try {
510             ResultSet getGaurdResult = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(getGaurd);
511             Row row = getGaurdResult.one();
512             if (row != null) {
513                 guard = row.getLong("guard");
514                 long timeOfWrite = System.currentTimeMillis();
515                 long ts = MusicUtil.v2sTimeStampInMicroseconds(guard, timeOfWrite);
516                 String query = queryObject.getQuery();
517                 if (!queryObject.getQuery().contains("USING TIMESTAMP")) {
518                     if (queryObject.getOperation().equalsIgnoreCase("delete"))
519                         query = query.replaceFirst("WHERE", " USING TIMESTAMP " + ts + " WHERE ");
520                     else
521                         query = query.replaceFirst("SET", "USING TIMESTAMP " + ts + " SET");
522                 }
523                 queryObject.replaceQueryString(query);
524             }
525
526         } catch (MusicServiceException | MusicQueryException e) {
527             logger.error(EELFLoggerDelegate.applicationLogger,e.getMessage(), e);
528         }
529         try {
530             result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, MusicUtil.EVENTUAL);
531         } catch (MusicServiceException | MusicQueryException ex) {
532             logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(),"[ERR512E] Failed to get Lock Handle ",
533                 ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
534             logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() + "  " + ex.getCause() + " ", ex);
535             return new ReturnType(ResultType.FAILURE, ex.getMessage());
536         }
537         if (result) {
538             return new ReturnType(ResultType.SUCCESS, "Eventual Operation Successfully performed");
539         } else {
540             return new ReturnType(ResultType.FAILURE, "Eventual Operation failed to perform");
541         }
542     }
543
544     /**
545      *
546      * @param keyspace
547      * @param table
548      * @param primaryKeyValue
549      * @param queryObject
550      * @param lockId
551      * @return
552      */
553     public ReturnType criticalPut(String keyspace, String table, String primaryKeyValue,
554             PreparedQueryObject queryObject, String lockId, Condition conditionInfo) {
555         long start = System.currentTimeMillis();
556         try {
557             String keyLock = lockId.substring(lockId.lastIndexOf(".") + 1,lockId.lastIndexOf("$"));
558             if (lockId.contains(".") && !keyLock.equals(primaryKeyValue)) {
559                 return new ReturnType(ResultType.FAILURE,"Lock value '" + keyLock + "' and key value '"
560                 + primaryKeyValue + "' not match. Please check your values: " 
561                 + lockId + " .");
562             }
563             LockObject lockObject = getLockingServiceHandle().getLockInfo(keyspace, table, primaryKeyValue,
564                     lockId.substring(lockId.lastIndexOf("$") + 1));
565
566             if ( lockObject == null ) {
567                 return new ReturnType(ResultType.FAILURE, lockId + " does not exist.");
568             } else if (!lockObject.getIsLockOwner()) {
569                 return new ReturnType(ResultType.FAILURE, lockId + " is not the lock holder");
570             } else if (lockObject.getLocktype() != LockType.WRITE) {
571                 return new ReturnType(ResultType.FAILURE,
572                         "Attempting to do write operation, but " + lockId + " is a read lock");
573             }
574
575             if (conditionInfo != null) {
576                 try {
577                     if (conditionInfo.testCondition() == false)
578                         return new ReturnType(ResultType.FAILURE, "Lock acquired but the condition is not true");
579                 } catch (Exception e) {
580                     logger.error(EELFLoggerDelegate.errorLogger, e);
581                     return new ReturnType(ResultType.FAILURE,
582                             "Exception thrown while checking the condition, check its sanctity:\n" + e.getMessage());
583                 }
584             }
585             String query = queryObject.getQuery();
586             long timeOfWrite = System.currentTimeMillis();
587             long lockOrdinal = Long.parseLong(lockId.substring(lockId.lastIndexOf("$") + 1));
588             long ts = MusicUtil.v2sTimeStampInMicroseconds(lockOrdinal, timeOfWrite);
589             // TODO: use Statement instead of modifying query
590             if (!queryObject.getQuery().contains("USING TIMESTAMP")) {
591                 if (queryObject.getOperation().equalsIgnoreCase("delete"))
592                     query = query.replaceFirst("WHERE", " USING TIMESTAMP " + ts + " WHERE ");
593                 else if (queryObject.getOperation().equalsIgnoreCase("insert"))
594                     query = query.replaceFirst(";", " USING TIMESTAMP " + ts + " ; ");
595                 else
596                     query = query.replaceFirst("SET", "USING TIMESTAMP " + ts + " SET");
597             }
598             queryObject.replaceQueryString(query);
599             MusicDataStore dsHandle = MusicDataStoreHandle.getDSHandle();
600             dsHandle.executePut(queryObject, MusicUtil.CRITICAL);
601             long end = System.currentTimeMillis();
602             logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the critical put:" + (end - start) + " ms");
603         } catch (MusicQueryException | MusicServiceException | MusicLockingException  e) {
604             logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), e);
605             return new ReturnType(ResultType.FAILURE,
606                 "Exception thrown while doing the critical put: "
607                 + e.getMessage());
608         }
609         return new ReturnType(ResultType.SUCCESS, "Update performed");
610     }
611
612
613     /**
614      *
615      * @param queryObject
616      * @param consistency
617      * @return Boolean Indicates success or failure
618      * @throws MusicServiceException
619      *
620      *
621      */
622     public ResultType nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency) throws MusicServiceException,MusicQueryException {
623         // this is mainly for some functions like keyspace creation etc which does not
624         // really need the bells and whistles of Music locking.
625         boolean result = false;
626 //        try {
627         result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, consistency);
628 //        } catch (MusicQueryException | MusicServiceException ex) {
629             // logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), AppMessages.UNKNOWNERROR,
630             //     ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR, ex);
631 //            throw new MusicServiceException(ex.getMessage(),ex);
632 //        }
633         return result ? ResultType.SUCCESS : ResultType.FAILURE;
634     }
635
636     /**
637      * This method performs DDL operation on cassandra.
638      *
639      * @param queryObject query object containing prepared query and values
640      * @return ResultSet
641      * @throws MusicServiceException
642      */
643     public ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException {
644         ResultSet results = null;
645         try {
646             results = MusicDataStoreHandle.getDSHandle().executeOneConsistencyGet(queryObject);
647         } catch (MusicQueryException | MusicServiceException e) {
648             logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e);
649             throw new MusicServiceException(e.getMessage());
650         }
651         return results;
652     }
653
654     /**
655      * This method performs DDL operations on cassandra, if the the resource is available. Lock ID
656      * is used to check if the resource is free.
657      *
658      * @param keyspace name of the keyspace
659      * @param table name of the table
660      * @param primaryKeyValue primary key value
661      * @param queryObject query object containing prepared query and values
662      * @param lockId lock ID to check if the resource is free to perform the operation.
663      * @return ResultSet
664      */
665     public ResultSet criticalGet(String keyspace, String table, String primaryKeyValue,
666                     PreparedQueryObject queryObject, String lockId) throws MusicServiceException {
667         ResultSet results = null;
668         String keyLock = lockId.substring(lockId.lastIndexOf(".") + 1,lockId.lastIndexOf("$"));
669         try {
670             if (lockId.contains(".") && !keyLock.equals(primaryKeyValue)) {
671                 throw new MusicLockingException("Lock value '" + keyLock + "' and key value '"
672                 + primaryKeyValue + "' do not match. Please check your values: " 
673                 + lockId + " .");
674             }
675             LockObject lockObject = getLockingServiceHandle().getLockInfo(keyspace, table, primaryKeyValue,
676                 lockId.substring(lockId.lastIndexOf("$") + 1));
677             if (null == lockObject) {
678                 throw new MusicLockingException("No Lock Object. Please check if lock name or key is correct." 
679                     + lockId + " .");
680             }
681             if ( !lockObject.getIsLockOwner()) {
682                 return null;// not top of the lock store q
683             }
684             results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(queryObject);
685         } catch ( MusicLockingException e ) {
686             logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity
687                     .WARN, ErrorTypes.MUSICSERVICEERROR);
688                 throw new MusicServiceException(
689                     "Cannot perform critical get for key: " + primaryKeyValue + " : " + e.getMessage());
690         } catch (MusicQueryException | MusicServiceException e) {
691             logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity
692                     .WARN, ErrorTypes.MUSICSERVICEERROR, e);
693                 throw new MusicServiceException(
694                     "Cannot perform critical get for key: " + primaryKeyValue + " : " + e.getMessage());    
695         }
696         return results;
697     }
698
699     /**
700      * This method performs DML operation on cassandra, when the lock of the dd is acquired.
701      *
702      * @param keyspaceName name of the keyspace
703      * @param tableName name of the table
704      * @param primaryKey primary key value
705      * @param queryObject query object containing prepared query and values
706      * @return ReturnType
707      * @throws MusicLockingException
708      * @throws MusicServiceException
709      * @throws MusicQueryException
710      */
711     public ReturnType atomicPut(String keyspaceName, String tableName, String primaryKey,
712             PreparedQueryObject queryObject, Condition conditionInfo)
713             throws MusicLockingException, MusicQueryException, MusicServiceException {
714         long start = System.currentTimeMillis();
715         String fullyQualifiedKey = keyspaceName + "." + tableName + "." + primaryKey;
716         String lockId = createLockReference(fullyQualifiedKey, LockType.WRITE);
717         long lockCreationTime = System.currentTimeMillis();
718         ReturnType lockAcqResult = null;
719         logger.info(EELFLoggerDelegate.applicationLogger,
720                 "***Acquiring lock for atomicPut() query : " + queryObject.getQuery() + " : " + primaryKey);
721         logger.info(EELFLoggerDelegate.applicationLogger,
722                 "***Acquiring lock for atomicPut() values: " + queryObject.getValues().toString());
723         if (conditionInfo != null) {
724             logger.info(EELFLoggerDelegate.applicationLogger,
725                     "***Acquiring lock for atomicPut() conditions: " + conditionInfo.toString());
726         }
727         try {
728             lockAcqResult = acquireLockWithLease(fullyQualifiedKey, lockId, MusicUtil.getDefaultLockLeasePeriod());
729         } catch (MusicLockingException ex) {
730             logger.error(EELFLoggerDelegate.errorLogger,
731                     "Exception while acquireLockWithLease() in atomic put for key: " + primaryKey);
732             logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage());
733             throw new MusicServiceException(
734                     "Cannot perform atomic put for key: " + primaryKey + " : " + ex.getMessage());
735         }
736         long lockAcqTime = System.currentTimeMillis();
737
738         /*
739          * if (!lockAcqResult.getResult().equals(ResultType.SUCCESS)) { logger.info(EELFLoggerDelegate.
740          * applicationLogger,"unable to acquire lock, id " + lockId);
741          * voluntaryReleaseLock(fullyQualifiedKey,lockId); return lockAcqResult; }
742          */
743
744         logger.info(EELFLoggerDelegate.applicationLogger, "acquired lock with id " + lockId);
745         String lockRef = lockId.substring(lockId.lastIndexOf("$"));
746         ReturnType criticalPutResult = null;
747         if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
748             criticalPutResult = criticalPut(keyspaceName, tableName, primaryKey, queryObject, lockRef, conditionInfo);
749             long criticalPutTime = System.currentTimeMillis();
750             long lockDeleteTime = System.currentTimeMillis();
751             String timingInfo = "|lock creation time:" + (lockCreationTime - start) + "|lock accquire time:"
752                     + (lockAcqTime - lockCreationTime) + "|critical put time:" + (criticalPutTime - lockAcqTime)
753                     + "|lock delete time:" + (lockDeleteTime - criticalPutTime) + "|";
754             criticalPutResult.setTimingInfo(timingInfo);
755         } else {
756             logger.info(EELFLoggerDelegate.applicationLogger, "unable to acquire lock, id " + lockId);
757             criticalPutResult = lockAcqResult;
758         }
759         try {
760             voluntaryReleaseLock(fullyQualifiedKey, lockId);
761         } catch (MusicLockingException ex) {
762             logger.info(EELFLoggerDelegate.applicationLogger,
763                     "Exception occured while deleting lock after atomic put for key: " + primaryKey);
764             criticalPutResult.setMessage(criticalPutResult.getMessage() + "Lock release failed");
765         }
766         return criticalPutResult;
767     }
768
769
770
771     /**
772      * This method performs DDL operation on cassasndra, when the lock for the resource is acquired.
773      *
774      * @param keyspaceName name of the keyspace
775      * @param tableName name of the table
776      * @param primaryKey primary key value
777      * @param queryObject query object containing prepared query and values
778      * @return ResultSet
779      * @throws MusicServiceException
780      * @throws MusicLockingException
781      * @throws MusicQueryException
782      */
783     public ResultSet atomicGet(String keyspaceName, String tableName, String primaryKey,
784             PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException, MusicQueryException {
785         String fullyQualifiedKey = keyspaceName + "." + tableName + "." + primaryKey;
786         String lockId = createLockReference(fullyQualifiedKey, LockType.READ);
787         long leasePeriod = MusicUtil.getDefaultLockLeasePeriod();
788         ReturnType lockAcqResult = null;
789         ResultSet result = null;
790         logger.info(EELFLoggerDelegate.applicationLogger, "Acquiring lock for atomicGet() : " + queryObject.getQuery());
791         try {
792             lockAcqResult = acquireLockWithLease(fullyQualifiedKey, lockId, MusicUtil.getDefaultLockLeasePeriod());
793         } catch (MusicLockingException ex) {
794             logger.error(EELFLoggerDelegate.errorLogger,
795                     "Exception while acquireLockWithLease() in atomic get for key: " + primaryKey);
796             logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage());
797             throw new MusicServiceException(
798                     "Cannot perform atomic get for key: " + primaryKey + " : " + ex.getMessage());
799         }
800         if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
801             logger.info(EELFLoggerDelegate.applicationLogger, "acquired lock with id " + lockId);
802             String lockRef = lockId.substring(lockId.lastIndexOf("$"));
803             result = criticalGet(keyspaceName, tableName, primaryKey, queryObject, lockRef);
804         } else {
805             logger.info(EELFLoggerDelegate.applicationLogger, "unable to acquire lock, id " + lockId);
806         }
807         try {
808             voluntaryReleaseLock(fullyQualifiedKey, lockId);
809         } catch (MusicLockingException ex) {
810             logger.info(EELFLoggerDelegate.applicationLogger,
811                     "Exception occured while deleting lock after atomic put for key: " + primaryKey);
812             throw new MusicLockingException(ex.getMessage());
813         }
814
815         return result;
816     }
817
818
819
820     /**
821      * @param lockName
822      * @return
823      */
824     public Map<String, Object> validateLock(String lockName) {
825         return MusicUtil.validateLock(lockName);
826     }
827
828     @Override
829     @Deprecated
830     public ReturnType atomicPutWithDeleteLock(String keyspaceName, String tableName, String primaryKey,
831         PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException {
832         return null;
833     }
834
835     @Override
836     public List<String> getLockQueue(String fullyQualifiedKey)
837         throws MusicServiceException, MusicQueryException, MusicLockingException {
838         String[] splitString = fullyQualifiedKey.split("\\.");
839         String keyspace = splitString[0];
840         String table = splitString[1];
841         String primaryKeyValue = splitString[2];
842
843         return getLockingServiceHandle().getLockQueue(keyspace, table, primaryKeyValue);
844     }
845     @Override
846     public long getLockQueueSize(String fullyQualifiedKey)
847         throws MusicServiceException, MusicQueryException, MusicLockingException {
848         String[] splitString = fullyQualifiedKey.split("\\.");
849         String keyspace = splitString[0];
850         String table = splitString[1];
851         String primaryKeyValue = splitString[2];
852
853         return getLockingServiceHandle().getLockQueueSize(keyspace, table, primaryKeyValue);
854     }
855
856     @Override
857     @Deprecated
858     public ResultSet atomicGetWithDeleteLock(String keyspaceName, String tableName, String primaryKey,
859             PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException {
860         //deprecated
861         return null;
862     }
863     
864     //Methods added for ORM changes
865     
866     public ResultType createKeyspace(JsonKeySpace jsonKeySpaceObject,String consistencyInfo) 
867             throws MusicServiceException,MusicQueryException {
868         ResultType result = nonKeyRelatedPut(jsonKeySpaceObject.genCreateKeyspaceQuery(), consistencyInfo);
869         logger.info(EELFLoggerDelegate.applicationLogger, " Keyspace Creation Process completed successfully");
870
871         return result;
872     }
873     
874     public ResultType dropKeyspace(JsonKeySpace jsonKeySpaceObject, String consistencyInfo) 
875             throws MusicServiceException,MusicQueryException {
876         ResultType result = nonKeyRelatedPut(jsonKeySpaceObject.genDropKeyspaceQuery(),
877                     consistencyInfo);
878         logger.info(EELFLoggerDelegate.applicationLogger, " Keyspace deletion Process completed successfully");
879         return result;
880     }
881     
882     public ResultType createTable(JsonTable jsonTableObject, String consistencyInfo) 
883             throws MusicServiceException, MusicQueryException {
884         ResultType result = null;
885         try {
886             result = createTable(jsonTableObject.getKeyspaceName(), 
887                     jsonTableObject.getTableName(), jsonTableObject.genCreateTableQuery(), consistencyInfo);
888             
889         } catch (MusicServiceException ex) {
890             logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), AppMessages.UNKNOWNERROR, ErrorSeverity.WARN,
891                     ErrorTypes.MUSICSERVICEERROR);
892             throw new MusicServiceException(ex.getMessage());
893         }
894         logger.info(EELFLoggerDelegate.applicationLogger, " Table Creation Process completed successfully ");
895         return result;
896     }
897     
898     public ResultType dropTable(JsonTable jsonTableObject,String consistencyInfo) 
899             throws MusicServiceException,MusicQueryException {
900         ResultType result = nonKeyRelatedPut(jsonTableObject.genDropTableQuery(),
901                     consistencyInfo);
902         logger.info(EELFLoggerDelegate.applicationLogger, " Table deletion Process completed successfully ");
903         
904         return result;
905     }
906     
907     @Override
908     public ResultType createIndex(JsonIndex jsonIndexObject, String consistencyInfo) 
909             throws MusicServiceException, MusicQueryException{
910         ResultType result = nonKeyRelatedPut(jsonIndexObject.genCreateIndexQuery(),
911                     consistencyInfo);
912         
913         logger.info(EELFLoggerDelegate.applicationLogger, " Index creation Process completed successfully ");
914         return result;
915     }
916     
917     /**
918      * This method performs DDL operation on cassandra.
919      *
920      * @param queryObject query object containing prepared query and values
921      * @return ResultSet
922      * @throws MusicServiceException
923      */
924     public  ResultSet select(JsonSelect jsonSelect, MultivaluedMap<String, String> rowParams) 
925             throws MusicServiceException, MusicQueryException {
926         ResultSet results = null;
927         try {
928             results = get(jsonSelect.genSelectQuery(rowParams));
929         } catch (MusicServiceException e) {
930             logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
931             throw new MusicServiceException(e.getMessage());
932         }
933         return results;
934     }
935     
936     /**
937      * Select Critical
938      */
939     public ResultSet selectCritical(JsonInsert jsonInsertObj, MultivaluedMap<String, String> rowParams)
940             throws MusicLockingException, MusicQueryException, MusicServiceException {
941         
942         ResultSet results = null;
943         String consistency = "";
944         if(null != jsonInsertObj && null != jsonInsertObj.getConsistencyInfo()) {
945             consistency = jsonInsertObj.getConsistencyInfo().get("type");
946         }
947         
948         String lockId = jsonInsertObj.getConsistencyInfo().get("lockId");
949         
950         PreparedQueryObject queryObject = jsonInsertObj.genSelectCriticalPreparedQueryObj(rowParams);
951         
952         if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
953             results = criticalGet(jsonInsertObj.getKeyspaceName(), jsonInsertObj.getTableName(), 
954                     jsonInsertObj.getPrimaryKeyVal(), queryObject,lockId);
955         } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
956             results = atomicGet(jsonInsertObj.getKeyspaceName(), jsonInsertObj.getTableName(),
957                     jsonInsertObj.getPrimaryKeyVal(), queryObject);
958         }
959         
960         return results;
961     }
962     
963     /**
964      * this is insert row into Table
965      */
966     public ReturnType insertIntoTable(JsonInsert jsonInsertObj)
967             throws MusicLockingException, MusicQueryException, MusicServiceException {
968         
969         String consistency = "";
970         if(null != jsonInsertObj && null != jsonInsertObj.getConsistencyInfo()) {
971             consistency = jsonInsertObj.getConsistencyInfo().get("type");
972         }
973         
974         ReturnType result = null;
975         
976         try {
977             PreparedQueryObject queryObj = null;
978             queryObj = jsonInsertObj.genInsertPreparedQueryObj();
979             
980             if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) {
981                 result = eventualPut(jsonInsertObj.genInsertPreparedQueryObj());
982             } else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
983                 String lockId = jsonInsertObj.getConsistencyInfo().get("lockId");
984                 if(lockId == null) {
985                     logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or"
986                             + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR);
987                     return new ReturnType(ResultType.FAILURE, "LockId cannot be null. Create lock "
988                             + "and acquire lock or use ATOMIC instead of CRITICAL");
989                 }
990                 result = criticalPut(jsonInsertObj.getKeyspaceName(), 
991                         jsonInsertObj.getTableName(), jsonInsertObj.getPrimaryKeyVal(), jsonInsertObj.genInsertPreparedQueryObj(), lockId,null);
992             } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
993                 result = atomicPut(jsonInsertObj.getKeyspaceName(), jsonInsertObj.getTableName(), 
994                         jsonInsertObj.getPrimaryKeyVal(), jsonInsertObj.genInsertPreparedQueryObj(), null);
995             }
996         } catch (Exception ex) {
997             logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity
998                 .WARN, ErrorTypes.MUSICSERVICEERROR, ex);
999             return new ReturnType(ResultType.FAILURE, ex.getMessage());
1000         }
1001         
1002         return result;
1003     }
1004     
1005      /**
1006      * This is insert row into Table
1007      */
1008     public ReturnType updateTable(JsonUpdate jsonUpdateObj, MultivaluedMap<String, String> rowParams)
1009             throws MusicLockingException, MusicQueryException, MusicServiceException {
1010         
1011         ReturnType result = null;
1012         String consistency = "";
1013         if(null != jsonUpdateObj && null != jsonUpdateObj.getConsistencyInfo()) {
1014             consistency = jsonUpdateObj.getConsistencyInfo().get("type");
1015         }
1016         PreparedQueryObject queryObject = jsonUpdateObj.genUpdatePreparedQueryObj(rowParams);
1017         
1018         Condition conditionInfo;
1019         if (jsonUpdateObj.getConditions() == null) {
1020             conditionInfo = null;
1021         } else {
1022             // to avoid parsing repeatedly, just send the select query to obtain row
1023             PreparedQueryObject selectQuery = new PreparedQueryObject();
1024             selectQuery.appendQueryString("SELECT *  FROM " + jsonUpdateObj.getKeyspaceName() + "." + jsonUpdateObj.getTableName() + " WHERE "
1025                 + jsonUpdateObj.getRowIdString() + ";");
1026             selectQuery.addValue(jsonUpdateObj.getPrimarKeyValue());
1027             conditionInfo = new Condition(jsonUpdateObj.getConditions(), selectQuery);
1028         }
1029
1030         
1031         if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) {
1032             result = eventualPut(queryObject);
1033         } else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
1034             String lockId = jsonUpdateObj.getConsistencyInfo().get("lockId");
1035             if(lockId == null) {
1036                 logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or"
1037                         + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR);
1038                
1039                 return new ReturnType(ResultType.FAILURE, "LockId cannot be null. Create lock "
1040                         + "and acquire lock or use ATOMIC instead of CRITICAL");
1041             }
1042             result = criticalPut(jsonUpdateObj.getKeyspaceName(), jsonUpdateObj.getTableName(), jsonUpdateObj.getPrimarKeyValue(),
1043                             queryObject, lockId, conditionInfo);
1044         } else if (consistency.equalsIgnoreCase("atomic_delete_lock")) {
1045             // this function is mainly for the benchmarks
1046             try {
1047                 result = atomicPutWithDeleteLock(jsonUpdateObj.getKeyspaceName(), jsonUpdateObj.getTableName(),
1048                         jsonUpdateObj.getPrimarKeyValue(), queryObject, conditionInfo);
1049             } catch (MusicLockingException e) {
1050                 logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN,
1051                     ErrorTypes.GENERALSERVICEERROR, e);
1052                 throw new MusicLockingException(AppMessages.UNKNOWNERROR.toString());
1053                 
1054             }
1055         } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
1056             try {
1057                 result = atomicPut(jsonUpdateObj.getKeyspaceName(), jsonUpdateObj.getTableName(), jsonUpdateObj.getPrimarKeyValue(),
1058                     queryObject, conditionInfo);
1059             } catch (MusicLockingException e) {
1060                 logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR, e);
1061                 throw new MusicLockingException(AppMessages.UNKNOWNERROR.toString());
1062             }
1063         } else if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL_NB)) {
1064             try {
1065                 result = eventualPut_nb(queryObject, jsonUpdateObj.getKeyspaceName(),
1066                         jsonUpdateObj.getTableName(), jsonUpdateObj.getPrimarKeyValue());
1067             }catch (Exception e) {
1068                 return new ReturnType(ResultType.FAILURE, e.getMessage());
1069             }
1070             
1071         }
1072         
1073         return result;
1074     }
1075     
1076     /**
1077      * This method is for Delete From Table
1078      */
1079     public ReturnType deleteFromTable(JsonDelete jsonDeleteObj, MultivaluedMap<String, String> rowParams)
1080             throws MusicLockingException, MusicQueryException, MusicServiceException {
1081         
1082         ReturnType result = null;
1083         String consistency = "";
1084         if(null != jsonDeleteObj && null != jsonDeleteObj.getConsistencyInfo()) {
1085             consistency = jsonDeleteObj.getConsistencyInfo().get("type");
1086         }
1087         PreparedQueryObject queryObject = jsonDeleteObj.genDeletePreparedQueryObj(rowParams);
1088         
1089         // get the conditional, if any
1090         Condition conditionInfo;
1091         if (jsonDeleteObj.getConditions() == null) {
1092             conditionInfo = null;
1093         } else {
1094             // to avoid parsing repeatedly, just send the select query to obtain row
1095             PreparedQueryObject selectQuery = new PreparedQueryObject();
1096             selectQuery.appendQueryString("SELECT *  FROM " + jsonDeleteObj.getKeyspaceName() + "." + jsonDeleteObj.getTableName() + " WHERE "
1097                 + jsonDeleteObj.getRowIdString() + ";");
1098             selectQuery.addValue(jsonDeleteObj.getPrimarKeyValue());
1099             conditionInfo = new Condition(jsonDeleteObj.getConditions(), selectQuery);
1100         }
1101         
1102         if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL))
1103             result = eventualPut(queryObject);
1104         else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
1105             String lockId = jsonDeleteObj.getConsistencyInfo().get("lockId");
1106             if(lockId == null) {
1107                 logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or"
1108                     + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR);
1109                
1110                 return new ReturnType(ResultType.FAILURE, "LockId cannot be null. Create lock "
1111                         + "and acquire lock or use ATOMIC instead of CRITICAL");
1112             }
1113             result = criticalPut(jsonDeleteObj.getKeyspaceName(), 
1114                     jsonDeleteObj.getTableName(), jsonDeleteObj.getPrimarKeyValue(),
1115                 queryObject, lockId, conditionInfo);
1116         } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
1117             result = atomicPut(jsonDeleteObj.getKeyspaceName(), 
1118                     jsonDeleteObj.getTableName(), jsonDeleteObj.getPrimarKeyValue(),
1119                 queryObject, conditionInfo);
1120         } else if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL_NB)) {                    
1121             result = eventualPut_nb(queryObject, jsonDeleteObj.getKeyspaceName(), 
1122                     jsonDeleteObj.getTableName(), jsonDeleteObj.getPrimarKeyValue());
1123         }
1124         
1125         return result;
1126     }
1127
1128
1129 }