Sonar Fixes - MusicDataStoreHandle.java
[music.git] / src / main / java / org / onap / music / main / MusicUtil.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
4  * ===================================================================
5  *  Copyright (c) 2017 AT&T Intellectual Property
6  * ===================================================================
7  *  Modifications Copyright (c) 2018 IBM.
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.main;
27
28 import com.datastax.driver.core.ColumnDefinitions;
29 import com.datastax.driver.core.ColumnDefinitions.Definition;
30 import com.datastax.driver.core.ResultSet;
31 import com.datastax.driver.core.Row;
32 import java.io.File;
33 import java.io.FileNotFoundException;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.math.BigInteger;
37 import java.nio.ByteBuffer;
38 import java.util.ArrayList;
39 import java.util.HashMap;
40 import java.util.List;
41 import java.util.Map;
42 import java.util.Properties;
43 import java.util.Scanner;
44 import java.util.StringTokenizer;
45 import java.util.UUID;
46 import java.util.concurrent.ConcurrentHashMap;
47 import java.util.concurrent.ConcurrentMap;
48
49 import javax.ws.rs.core.Response;
50 import javax.ws.rs.core.Response.ResponseBuilder;
51
52 import org.onap.music.datastore.MusicDataStoreHandle;
53 import org.onap.music.datastore.PreparedQueryObject;
54 import org.onap.music.eelf.logging.EELFLoggerDelegate;
55 import org.onap.music.eelf.logging.format.AppMessages;
56 import org.onap.music.eelf.logging.format.ErrorSeverity;
57 import org.onap.music.eelf.logging.format.ErrorTypes;
58 import org.onap.music.exceptions.MusicQueryException;
59 import org.onap.music.exceptions.MusicServiceException;
60 import org.onap.music.service.MusicCoreService;
61 import org.onap.music.service.impl.MusicCassaCore;
62 import org.onap.music.service.impl.MusicZKCore;
63
64 import com.datastax.driver.core.ConsistencyLevel;
65 import com.datastax.driver.core.DataType;
66 import com.sun.jersey.core.util.Base64;
67
68 /**
69  * @author nelson24
70  *
71  *         Properties This will take Properties and load them into MusicUtil.
72  *         This is a hack for now. Eventually it would bebest to do this in
73  *         another way.
74  *
75  */
76 public class MusicUtil {
77     private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class);
78
79     public static final String ATOMIC = "atomic";
80     public static final String EVENTUAL = "eventual";
81     public static final String CRITICAL = "critical";
82     public static final String EVENTUAL_NB = "eventual_nb";
83     public static final String ALL = "all";
84     public static final String QUORUM = "quorum";
85     public static final String ONE = "one";
86     public static final String ATOMICDELETELOCK = "atomic_delete_lock";
87     public static final String DEFAULTKEYSPACENAME = "TBD";
88     private static final String XLATESTVERSION = "X-latestVersion";
89     private static final String XMINORVERSION = "X-minorVersion";
90     private static final String XPATCHVERSION = "X-patchVersion";
91     public static final String SELECT = "select";
92     public static final String INSERT = "insert";
93     public static final String UPDATE = "update";
94     public static final String UPSERT = "upsert";
95     public static final String USERID = "userId";
96     public static final String PASSWORD = "password";
97     public static final String CASSANDRA = "cassandra";
98     public static final String ZOOKEEPER = "zookeeper";
99
100     public static final String AUTHORIZATION = "Authorization";
101
102     private static final String LOCALHOST = "localhost";
103     private static final String PROPERTIES_FILE = "/opt/app/music/etc/music.properties";
104
105     private static int myId = 0;
106     private static ArrayList<String> allIds = new ArrayList<>();
107     private static String publicIp = "";
108     private static ArrayList<String> allPublicIps = new ArrayList<>();
109     private static String myZkHost = LOCALHOST;
110     private static String myCassaHost = LOCALHOST;
111     private static String defaultMusicIp = LOCALHOST;
112     private static int cassandraPort = 9042;
113     private static int notifytimeout = 30000;
114     private static int notifyinterval = 5000;
115     private static int cacheObjectMaxLife = -1;
116     private static String lockUsing = MusicUtil.CASSANDRA;
117     private static boolean isCadi = false;
118     
119     private static boolean debug = true;
120     private static String version = "2.3.0";
121     private static String musicRestIp = LOCALHOST;
122     private static String musicPropertiesFilePath = PROPERTIES_FILE;
123     private static long defaultLockLeasePeriod = 6000;
124     private static final String[] propKeys = new String[] { "zookeeper.host", "cassandra.host", "music.ip", "debug",
125             "version", "music.rest.ip", "music.properties", "lock.lease.period", "id", "all.ids", "public.ip",
126             "all.pubic.ips", "cassandra.user", "cassandra.password", "aaf.endpoint.url","admin.username","admin.password","aaf.admin.url",
127             "music.namespace","admin.aaf.role","cassandra.port","lock.using"};
128     private static final String[] cosistencyLevel = new String[] {
129             "ALL","EACH_QUORUM","QUORUM","LOCAL_QUORUM","ONE","TWO","THREE","LOCAL_ONE","ANY","SERIAL","LOCAL_SERIAL"};
130     private static final Map<String,ConsistencyLevel> consistencyName = new HashMap<>();
131     static {
132         consistencyName.put("ONE",ConsistencyLevel.ONE);
133         consistencyName.put("TWO",ConsistencyLevel.TWO);
134         consistencyName.put("THREE",ConsistencyLevel.THREE);
135         consistencyName.put("SERIAL",ConsistencyLevel.SERIAL);
136         consistencyName.put("ALL",ConsistencyLevel.ALL);
137         consistencyName.put("EACH_QUORUM",ConsistencyLevel.EACH_QUORUM);
138         consistencyName.put("QUORUM",ConsistencyLevel.QUORUM);
139         consistencyName.put("LOCAL_QUORUM",ConsistencyLevel.LOCAL_QUORUM);
140         consistencyName.put("LOCAL_ONE",ConsistencyLevel.LOCAL_ONE);
141         consistencyName.put("LOCAL_SERIAL",ConsistencyLevel.LOCAL_SERIAL);
142     }
143
144     private static String cassName = "cassandra";
145     private static String cassPwd;
146     private static String aafEndpointUrl = null;
147     public static ConcurrentMap<String, Long> zkNodeMap = new ConcurrentHashMap<>();
148     private static String adminId = "username";
149     private static String adminPass= "password";
150     private static String aafAdminUrl= null;
151     private static String musicNamespace= "com.att.music.api";
152     private static String adminAafRole= "com.att.music.api.admin_api";
153     
154     public static final long MusicEternityEpochMillis = 1533081600000L; // Wednesday, August 1, 2018 12:00:00 AM
155
156     public static final long MaxLockReferenceTimePart = 1000000000000L; // millis after eternity (eq sometime in 2050)
157     
158     public static final long MaxCriticalSectionDurationMillis = 1L * 24 * 60 * 60 * 1000; // 1 day
159
160
161     public static String getLockUsing() {
162         return lockUsing;
163     }
164
165
166     public static void setLockUsing(String lockUsing) {
167         MusicUtil.lockUsing = lockUsing;
168     }
169     
170     public static String getAafAdminUrl() {
171         return aafAdminUrl;
172     }
173
174
175     public static void setAafAdminUrl(String aafAdminUrl) {
176         MusicUtil.aafAdminUrl = aafAdminUrl;
177     }
178
179
180     public static String getMusicNamespace() {
181         return musicNamespace;
182     }
183
184
185     public static void setMusicNamespace(String musicNamespace) {
186         MusicUtil.musicNamespace = musicNamespace;
187     }
188
189
190     public static String getAdminAafRole() {
191         return adminAafRole;
192     }
193
194
195     public static void setAdminAafRole(String adminAafRole) {
196         MusicUtil.adminAafRole = adminAafRole;
197     }
198
199
200
201     public static String getAdminId() {
202         return adminId;
203     }
204
205
206     public static void setAdminId(String adminId) {
207         MusicUtil.adminId = adminId;
208     }
209
210
211     public static String getAdminPass() {
212         return adminPass;
213     }
214
215     public static void setAdminPass(String adminPass) {
216         MusicUtil.adminPass = adminPass;
217     }
218
219
220     private MusicUtil() {
221         throw new IllegalStateException("Utility Class");
222     }
223     /**
224      *
225      * @return cassandra port
226      */
227     public static int getCassandraPort() {
228         return cassandraPort;
229     }
230
231     /**
232      * set cassandra port
233      * @param cassandraPort
234      */
235     public static void setCassandraPort(int cassandraPort) {
236         MusicUtil.cassandraPort = cassandraPort;
237     }
238     /**
239      * @return the cassName
240      */
241     public static String getCassName() {
242         return cassName;
243     }
244
245     /**
246      * @return the cassPwd
247      */
248     public static String getCassPwd() {
249         return cassPwd;
250     }
251
252     /**
253      * @return the aafEndpointUrl
254      */
255     public static String getAafEndpointUrl() {
256         return aafEndpointUrl;
257     }
258
259     /**
260      *
261      * @param aafEndpointUrl
262      */
263     public static void setAafEndpointUrl(String aafEndpointUrl) {
264         MusicUtil.aafEndpointUrl = aafEndpointUrl;
265     }
266
267     /**
268      *
269      * @return
270      */
271     public static int getMyId() {
272         return myId;
273     }
274
275     /**
276      *
277      * @param myId
278      */
279     public static void setMyId(int myId) {
280         MusicUtil.myId = myId;
281     }
282
283     /**
284      *
285      * @return
286      */
287     public static List<String> getAllIds() {
288         return allIds;
289     }
290
291     /**
292      *
293      * @param allIds
294      */
295     public static void setAllIds(List<String> allIds) {
296         MusicUtil.allIds = (ArrayList<String>) allIds;
297     }
298
299     /**
300      *
301      * @return
302      */
303     public static String getPublicIp() {
304         return publicIp;
305     }
306
307     /**
308      *
309      * @param publicIp
310      */
311     public static void setPublicIp(String publicIp) {
312         MusicUtil.publicIp = publicIp;
313     }
314
315     /**
316      *
317      * @return
318      */
319     public static List<String> getAllPublicIps() {
320         return allPublicIps;
321     }
322
323     /**
324      *
325      * @param allPublicIps
326      */
327     public static void setAllPublicIps(List<String> allPublicIps) {
328         MusicUtil.allPublicIps = (ArrayList<String>) allPublicIps;
329     }
330
331     /**
332      * Returns An array of property names that should be in the Properties
333      * files.
334      *
335      * @return
336      */
337     public static String[] getPropkeys() {
338         return propKeys;
339     }
340
341     /**
342      * Get MusicRestIp - default = localhost property file value - music.rest.ip
343      *
344      * @return
345      */
346     public static String getMusicRestIp() {
347         return musicRestIp;
348     }
349
350     /**
351      * Set MusicRestIp
352      *
353      * @param musicRestIp
354      */
355     public static void setMusicRestIp(String musicRestIp) {
356         MusicUtil.musicRestIp = musicRestIp;
357     }
358
359     /**
360      * Get MusicPropertiesFilePath - Default = /opt/music/music.properties
361      * property file value - music.properties
362      *
363      * @return
364      */
365     public static String getMusicPropertiesFilePath() {
366         return musicPropertiesFilePath;
367     }
368
369     /**
370      * Set MusicPropertiesFilePath
371      *
372      * @param musicPropertiesFilePath
373      */
374     public static void setMusicPropertiesFilePath(String musicPropertiesFilePath) {
375         MusicUtil.musicPropertiesFilePath = musicPropertiesFilePath;
376     }
377
378     /**
379      * Get DefaultLockLeasePeriod - Default = 6000 property file value -
380      * lock.lease.period
381      *
382      * @return
383      */
384     public static long getDefaultLockLeasePeriod() {
385         return defaultLockLeasePeriod;
386     }
387
388     /**
389      * Set DefaultLockLeasePeriod
390      *
391      * @param defaultLockLeasePeriod
392      */
393     public static void setDefaultLockLeasePeriod(long defaultLockLeasePeriod) {
394         MusicUtil.defaultLockLeasePeriod = defaultLockLeasePeriod;
395     }
396
397     /**
398      * Set Debug
399      *
400      * @param debug
401      */
402     public static void setDebug(boolean debug) {
403         MusicUtil.debug = debug;
404     }
405
406     /**
407      * Is Debug - Default = true property file value - debug
408      *
409      * @return
410      */
411     public static boolean isDebug() {
412         return debug;
413     }
414
415     /**
416      * Set Version
417      *
418      * @param version
419      */
420     public static void setVersion(String version) {
421         MusicUtil.version = version;
422     }
423
424     /**
425      * Return the version property file value - version
426      *
427      * @return
428      */
429     public static String getVersion() {
430         return version;
431     }
432
433     /**
434      * Get MyZkHost - Zookeeper Hostname - Default = localhost property file
435      * value - zookeeper.host
436      *
437      * @return
438      */
439     public static String getMyZkHost() {
440         return myZkHost;
441     }
442
443     /**
444      * Set MyZkHost - Zookeeper Hostname
445      *
446      * @param myZkHost
447      */
448     public static void setMyZkHost(String myZkHost) {
449         MusicUtil.myZkHost = myZkHost;
450     }
451
452     /**
453      * Get MyCassHost - Cassandra Hostname - Default = localhost property file
454      * value - cassandra.host
455      *
456      * @return
457      */
458     public static String getMyCassaHost() {
459         return myCassaHost;
460     }
461
462     /**
463      * Set MyCassHost - Cassandra Hostname
464      *
465      * @param myCassaHost
466      */
467     public static void setMyCassaHost(String myCassaHost) {
468         MusicUtil.myCassaHost = myCassaHost;
469     }
470
471     /**
472      * Get DefaultMusicIp - Default = localhost property file value - music.ip
473      *
474      * @return
475      */
476     public static String getDefaultMusicIp() {
477         return defaultMusicIp;
478     }
479
480     /**
481      * Set DefaultMusicIp
482      *
483      * @param defaultMusicIp
484      */
485     public static void setDefaultMusicIp(String defaultMusicIp) {
486         MusicUtil.defaultMusicIp = defaultMusicIp;
487     }
488
489     /**
490      *
491      * @return
492      */
493     public static String getTestType() {
494         String testType = "";
495         try {
496             Scanner fileScanner = new Scanner(new File(""));
497             testType = fileScanner.next();// ignore the my id line
498             @SuppressWarnings("unused")
499             String batchSize = fileScanner.next();// ignore the my public ip
500                                                     // line
501             fileScanner.close();
502         } catch (FileNotFoundException e) {
503             logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
504         }
505         return testType;
506
507     }
508
509     /**
510      *
511      * @param time
512      */
513     public static void sleep(long time) {
514         try {
515             Thread.sleep(time);
516         } catch (InterruptedException e) {
517             logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
518             Thread.currentThread().interrupt();
519         }
520     }
521
522     /**
523      * Utility function to check if the query object is valid.
524      *
525      * @param withparams
526      * @param queryObject
527      * @return
528      */
529     public static boolean isValidQueryObject(boolean withparams, PreparedQueryObject queryObject) {
530         if (withparams) {
531             int noOfValues = queryObject.getValues().size();
532             int noOfParams = 0;
533             char[] temp = queryObject.getQuery().toCharArray();
534             for (int i = 0; i < temp.length; i++) {
535                 if (temp[i] == '?')
536                     noOfParams++;
537             }
538             return (noOfValues == noOfParams);
539         } else {
540             return !queryObject.getQuery().isEmpty();
541         }
542
543     }
544
545     public static void setCassName(String cassName) {
546         MusicUtil.cassName = cassName;
547     }
548
549     public static void setCassPwd(String cassPwd) {
550         MusicUtil.cassPwd = cassPwd;
551     }
552
553     @SuppressWarnings("unchecked")
554     public static String convertToCQLDataType(DataType type, Object valueObj) throws Exception {
555
556         String value = "";
557         switch (type.getName()) {
558         case UUID:
559             value = valueObj + "";
560             break;
561         case TEXT:
562         case VARCHAR:
563             String valueString = valueObj + "";
564             valueString = valueString.replace("'", "''");
565             value = "'" + valueString + "'";
566             break;
567         case MAP: {
568             Map<String, Object> otMap = (Map<String, Object>) valueObj;
569             value = "{" + jsonMaptoSqlString(otMap, ",") + "}";
570             break;
571         }
572         default:
573             value = valueObj + "";
574             break;
575         }
576         return value;
577     }
578
579     /**
580      *
581      * @param colType
582      * @param valueObj
583      * @return
584      * @throws MusicTypeConversionException
585      * @throws Exception
586      */
587     @SuppressWarnings("unchecked")
588     public static Object convertToActualDataType(DataType colType, Object valueObj) throws Exception {
589         String valueObjString = valueObj + "";
590         switch (colType.getName()) {
591             case UUID:
592                 return UUID.fromString(valueObjString);
593             case VARINT:
594                 return BigInteger.valueOf(Long.parseLong(valueObjString));
595             case BIGINT:
596                 return Long.parseLong(valueObjString);
597             case INT:
598                 return Integer.parseInt(valueObjString);
599             case FLOAT:
600                 return Float.parseFloat(valueObjString);
601             case DOUBLE:
602                 return Double.parseDouble(valueObjString);
603             case BOOLEAN:
604                 return Boolean.parseBoolean(valueObjString);
605             case MAP:
606                 return (Map<String, Object>) valueObj;
607             case LIST:
608                 return (List<Object>)valueObj;
609             case BLOB:
610
611             default:
612                 return valueObjString;
613         }
614     }
615
616     public static ByteBuffer convertToActualDataType(DataType colType, byte[] valueObj) {
617          ByteBuffer buffer = ByteBuffer.wrap(valueObj);
618          return buffer;
619     }
620
621     /**
622      *
623      * Utility function to parse json map into sql like string
624      *
625      * @param jMap
626      * @param lineDelimiter
627      * @return
628      */
629
630     public static String jsonMaptoSqlString(Map<String, Object> jMap, String lineDelimiter) throws Exception{
631         StringBuilder sqlString = new StringBuilder();
632         int counter = 0;
633         for (Map.Entry<String, Object> entry : jMap.entrySet()) {
634             Object ot = entry.getValue();
635             String value = ot + "";
636             if (ot instanceof String) {
637                 value = "'" + value.replace("'", "''") + "'";
638             }
639             sqlString.append("'" + entry.getKey() + "':" + value);
640             if (counter != jMap.size() - 1)
641                 sqlString.append(lineDelimiter);
642             counter = counter + 1;
643         }
644         return sqlString.toString();
645     }
646
647     @SuppressWarnings("unused")
648     public static String buildVersion(String major, String minor, String patch) {
649         if (minor != null) {
650             major += "." + minor;
651             if (patch != null) {
652                 major += "." + patch;
653             }
654         }
655         return major;
656     }
657
658     /**
659      * Currently this will build a header with X-latestVersion, X-minorVersion and X-pathcVersion
660      * X-latestVerstion will be equal to the latest full version.
661      * X-minorVersion - will be equal to the latest minor version.
662      * X-pathVersion - will be equal to the latest patch version.
663      * Future plans will change this.
664      * @param response
665      * @param major
666      * @param minor
667      * @param patch
668      * @return
669      */
670     public static ResponseBuilder buildVersionResponse(String major, String minor, String patch) {
671         ResponseBuilder response = Response.noContent();
672         String versionIn = buildVersion(major,minor,patch);
673         String version = MusicUtil.getVersion();
674         String[] verArray = version.split("\\.",3);
675         if ( minor != null ) {
676             response.header(XMINORVERSION,minor);
677         } else {
678             response.header(XMINORVERSION,verArray[1]);
679         }
680         if ( patch != null ) {
681             response.header(XPATCHVERSION,patch);
682         } else {
683             response.header(XPATCHVERSION,verArray[2]);
684         }
685         response.header(XLATESTVERSION,version);
686         logger.info(EELFLoggerDelegate.applicationLogger,"Version In:" + versionIn);
687         return response;
688     }
689
690
691     public static Map<String,String> extractBasicAuthentication(String authorization){
692         Map<String,String> authValues = new HashMap<>();
693         if(authorization == null) {
694             authValues.put("ERROR", "Authorization cannot be null");
695             return authValues;
696         }
697         authorization = authorization.replaceFirst("Basic", "");
698         String decoded = Base64.base64Decode(authorization);
699         StringTokenizer token = new StringTokenizer(decoded, ":");
700         authValues.put(MusicUtil.USERID, token.nextToken());
701         authValues.put(MusicUtil.PASSWORD,token.nextToken());
702         return authValues;
703
704     }
705
706     public static boolean isValidConsistency(String consistency) {
707         for (String string : cosistencyLevel) {
708             if (string.equalsIgnoreCase(consistency))
709                 return true;
710         }
711         return false;
712
713     }
714
715     public static ConsistencyLevel getConsistencyLevel(String consistency) {
716         return consistencyName.get(consistency.toUpperCase());
717         }
718
719         public static void loadProperties() throws Exception {
720         Properties prop = new Properties();
721         InputStream input = null;
722         try {
723             // load the properties file
724             input = MusicUtil.class.getClassLoader().getResourceAsStream("music.properties");
725             prop.load(input);
726         } catch (Exception ex) {
727             logger.error(EELFLoggerDelegate.errorLogger, "Unable to find properties file.");
728             throw new Exception();
729         } finally {
730             if (input != null) {
731                 try {
732                     input.close();
733                 } catch (IOException e) {
734                     e.printStackTrace();
735                 }
736             }
737         }
738         // get the property value and return it
739         MusicUtil.setMyCassaHost(prop.getProperty("cassandra.host"));
740         String zkHosts = prop.getProperty("zookeeper.host");
741         MusicUtil.setMyZkHost(zkHosts);
742         MusicUtil.setCassName(prop.getProperty("cassandra.user"));
743         MusicUtil.setCassPwd(prop.getProperty("cassandra.password"));
744         MusicUtil.setCassandraPort(Integer.parseInt(prop.getProperty("cassandra.port")));
745         MusicUtil.setNotifyTimeOut(Integer.parseInt(prop.getProperty("notify.timeout")));
746         MusicUtil.setNotifyInterval(Integer.parseInt(prop.getProperty("notify.interval")));
747         MusicUtil.setCacheObjectMaxLife(Integer.parseInt(prop.getProperty("cacheobject.maxlife")));
748     }
749
750     public static void setNotifyInterval(int notifyinterval) {
751         MusicUtil.notifyinterval = notifyinterval;
752     }
753     public static void setNotifyTimeOut(int notifytimeout) {
754         MusicUtil.notifytimeout = notifytimeout;
755     }
756
757     public static int getNotifyInterval() {
758         return MusicUtil.notifyinterval;
759     }
760
761     public static int getNotifyTimeout() {
762         return MusicUtil.notifytimeout;
763     }
764
765     public static int getCacheObjectMaxLife() {
766         return MusicUtil.cacheObjectMaxLife;
767     }
768
769     public static void setCacheObjectMaxLife(int cacheObjectMaxLife) {
770         MusicUtil.cacheObjectMaxLife = cacheObjectMaxLife;
771     }
772     
773     /**
774      * Given the time of write for an update in a critical section, this method provides a transformed timestamp
775      * that ensures that a previous lock holder who is still alive can never corrupt a later critical section.
776      * The main idea is to us the lock reference to clearly demarcate the timestamps across critical sections.
777      * @param the UUID lock reference associated with the write.
778      * @param the long timeOfWrite which is the actual time at which the write took place
779      * @throws MusicServiceException
780      * @throws MusicQueryException
781      */
782     public static long v2sTimeStampInMicroseconds(long ordinal, long timeOfWrite) throws MusicServiceException, MusicQueryException {
783         // TODO: use acquire time instead of music eternity epoch
784         long ts = ordinal * MaxLockReferenceTimePart + (timeOfWrite - MusicEternityEpochMillis);
785
786         return ts;
787     }
788     
789     public static MusicCoreService  getMusicCoreService() {
790         if(getLockUsing().equals(MusicUtil.CASSANDRA))
791             return MusicCassaCore.getInstance();
792         else if (getLockUsing().equals(MusicUtil.ZOOKEEPER))
793             return MusicZKCore.getInstance();
794         else
795             return MusicCassaCore.getInstance();
796     }
797     
798     /**
799      * @param lockName
800      * @return
801      */
802     public static Map<String, Object> validateLock(String lockName) {
803         Map<String, Object> resultMap = new HashMap<>();
804         String[] locks = lockName.split("\\.");
805         if(locks.length < 3) {
806             resultMap.put("Error", "Invalid lock. Please make sure lock is of the type keyspaceName.tableName.primaryKey");
807             return resultMap;
808         }
809         String keyspace= locks[0];
810         if(keyspace.startsWith("$"))
811             keyspace = keyspace.substring(1);
812         resultMap.put("keyspace",keyspace);
813         return resultMap;
814     }
815
816
817     public static void setIsCadi(boolean isCadi) {
818         // TODO Auto-generated method stub
819         MusicUtil.isCadi = isCadi;
820     }
821
822     public static void writeBackToQuorum(PreparedQueryObject selectQuery, String primaryKeyName,
823         PreparedQueryObject updateQuery, String keyspace, String table,
824         Object cqlFormattedPrimaryKeyValue)
825         throws Exception {
826         try {
827             ResultSet results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(selectQuery);
828             // write it back to a quorum
829             Row row = results.one();
830             ColumnDefinitions colInfo = row.getColumnDefinitions();
831             int totalColumns = colInfo.size();
832             int counter = 1;
833             StringBuilder fieldValueString = new StringBuilder("");
834             for (Definition definition : colInfo) {
835                 String colName = definition.getName();
836                 if (colName.equals(primaryKeyName))
837                     continue;
838                 DataType colType = definition.getType();
839                 Object valueObj = MusicDataStoreHandle.getDSHandle().getColValue(row, colName, colType);
840                 Object valueString = MusicUtil.convertToActualDataType(colType, valueObj);
841                 fieldValueString.append(colName + " = ?");
842                 updateQuery.addValue(valueString);
843                 if (counter != (totalColumns - 1))
844                     fieldValueString.append(",");
845                 counter = counter + 1;
846             }
847             updateQuery.appendQueryString("UPDATE " + keyspace + "." + table + " SET "
848                 + fieldValueString + " WHERE " + primaryKeyName + "= ? " + ";");
849             updateQuery.addValue(cqlFormattedPrimaryKeyValue);
850
851             MusicDataStoreHandle.getDSHandle().executePut(updateQuery, "critical");
852         } catch (MusicServiceException | MusicQueryException e) {
853             logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.QUERYERROR +""+updateQuery ,
854                 ErrorSeverity.MAJOR, ErrorTypes.QUERYERROR);
855         }
856     }
857     
858     public static boolean getIsCadi() {
859         return MusicUtil.isCadi;
860     }
861
862 }
863