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