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