Code changes to fix cassandra issue
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / music / service / MusicService.java
1 /*
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright Â© 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  *.
37  */
38
39 package org.onap.portalapp.music.service;
40
41 import java.io.InputStream;
42 import java.text.DateFormat;
43 import java.text.SimpleDateFormat;
44 import java.util.ArrayList;
45 import java.util.Date;
46 import java.util.HashMap;
47 import java.util.List;
48 import java.util.Map;
49 import java.util.Properties;
50
51 import org.onap.music.datastore.PreparedQueryObject;
52 import org.onap.music.eelf.logging.EELFLoggerDelegate;
53 import org.onap.music.exceptions.MusicLockingException;
54 import org.onap.music.exceptions.MusicQueryException;
55 import org.onap.music.exceptions.MusicServiceException;
56 import org.onap.music.main.CipherUtil;
57 import org.onap.music.main.MusicCore;
58 import org.onap.music.main.ResultType;
59 import org.onap.music.main.ReturnType;
60 import org.onap.portalapp.music.conf.MusicSession;
61 import org.onap.portalapp.music.model.RestResponse;
62 import org.onap.portalapp.music.model.RestStatusEnum;
63 import org.onap.portalapp.music.util.MusicProperties;
64 import org.onap.portalapp.music.util.MusicUtil;
65 import org.springframework.http.HttpEntity;
66 import org.springframework.http.HttpHeaders;
67 import org.springframework.http.HttpMethod;
68 import org.springframework.http.MediaType;
69 import org.springframework.http.ResponseEntity;
70 import org.springframework.session.Session;
71 import org.springframework.web.client.RestTemplate;
72 import org.onap.music.datastore.MusicDataStore;
73
74 import com.datastax.driver.core.ResultSet;
75 import com.datastax.driver.core.Row;
76 import com.fasterxml.jackson.core.JsonProcessingException;
77 import com.fasterxml.jackson.databind.ObjectMapper;
78
79 public class MusicService {
80         static RestTemplate template = new RestTemplate();
81         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicService.class);
82         
83     
84     public static void init() {
85         try {
86                 Properties prop = new Properties();
87                 // We load encryption key from key.properties on the classpath. This key is used for decrypting cassandra password
88             try(InputStream input = MusicUtil.class.getClassLoader().getResourceAsStream("key.properties")) {
89                 prop.load(input);
90             } catch (Exception var11) {
91                 logger.error(EELFLoggerDelegate.errorLogger, "Unable to find properties file.");
92                 //throw new Exception();
93             }
94                 try {
95                         // Load music.properties from classpath
96                 org.onap.music.main.MusicUtil.loadProperties();
97                 // decrypt encrypted password using the key we loaded before.
98                 String decryptedPassword = CipherUtil.decryptPKC(org.onap.music.main.MusicUtil.getCassPwd(), prop.getProperty("cipher.enc.key"));
99                 logger.debug(EELFLoggerDelegate.debugLogger, "Successfully decrypted cassandra password ");
100                 // set decrypted password 
101                 org.onap.music.main.MusicUtil.setCassPwd(decryptedPassword);
102                 // Here we are creating cassandra connections pool and sessions by calling MusicDataStore and passing the cassandrra hostname to that. 
103                 MusicCore.mDstoreHandle = new MusicDataStore(org.onap.music.main.MusicUtil.getMyCassaHost());
104                 logger.debug(EELFLoggerDelegate.debugLogger, "Successfully created cassandra connection pool ");
105                                 // Since mDstoreHandle is already initialized in init mthod, calling this method again will have no impact on mDstoreHandle.
106                 MusicCore.getDSHandle();
107             } catch (Exception e) {
108                 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e);
109                 logger.debug(EELFLoggerDelegate.debugLogger, e.getMessage(), e);
110             }
111                 
112         } catch(Exception e) {
113                 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e);
114                 logger.debug(EELFLoggerDelegate.debugLogger, e.getMessage(), e);
115         }
116     }
117
118
119         private static boolean isAtomicPut = MusicUtil.isAtomicPut();
120         private static boolean isAtomicGet = MusicUtil.isAtomicGet();
121         private static String musicKeySpace = MusicProperties.getProperty(MusicProperties.MUSIC_SESSION_KEYSPACE);
122         private static String musicMetaTable = MusicProperties.getProperty(MusicProperties.MUSIC_SESSION_META_TABLES);
123         private static String musicAttrTable = MusicProperties.getProperty(MusicProperties.MUSIC_SESSION_ATTR_TABLES);
124
125   private static final String WITH_SESSION_ID = " with session id: ";
126   private static final String RESULT = "result:";
127   private static final String WHERE = " WHERE ";
128   private static final String FROM = " FROM ";
129   private static final String DELETE = "DELETE ";
130   private static final String REMOVE_SESSION = "removeSession: ";
131   private static final String SUCCESS = "success";
132   public static final String ATOMIC = "atomic";
133   public static final String EVENTUAL = "eventual";
134   public static final String CRITICAL = "critical";
135
136         /**
137          * Store session attribute name and values into Cassandra via Music
138          *
139          * @param attributeName
140          * @param value
141          * @param sessionId
142          * @return ReturnType that includes required body information for Music api
143          * @throws Exception
144          */
145         public static ReturnType setAttribute(String attributeName, Object value, String sessionId) throws MusicLockingException {
146                 logger.debug(EELFLoggerDelegate.debugLogger, "setAttribute: start with id " + sessionId);
147                 String tableName = null;
148                 ReturnType result = null;
149                 boolean isMeta = MusicUtil.isSessionMetaAttr(attributeName);
150                 PreparedQueryObject queryObject = new PreparedQueryObject();
151                 StringBuilder querySB = new StringBuilder();
152                 querySB.append("INSERT INTO ").append(musicKeySpace).append(".").append(getTableName(isMeta))
153                                 .append(getInsertQuery(isMeta, attributeName));
154
155                 queryObject.appendQueryString(querySB.toString());
156                 if (isMeta) {
157                         queryObject.addValue(sessionId);
158                         queryObject.addValue(String.valueOf(value));
159                         tableName = musicMetaTable;
160                 } else {
161                         queryObject.addValue(sessionId);
162                         queryObject.addValue(attributeName);
163                         queryObject.addValue(MusicUtil.musicSerialize(value));
164                         tableName = musicAttrTable;
165
166                 }
167                 if (isAtomicPut)
168                         result = MusicCore.atomicPut(musicKeySpace, tableName, sessionId, queryObject, null);
169                 else
170                         result = modEventualPut(queryObject);
171                 logger.debug(EELFLoggerDelegate.debugLogger, "setAttribute: attributeName: " + attributeName
172                                 + WITH_SESSION_ID + sessionId + RESULT + result.getMessage());
173                 return result;
174         }
175
176         /**
177          * Store session meta data values into Cassandra via Music
178          *
179          * @param session
180          * @return ReturnType that includes required body information for Music api
181          * @throws Exception
182          */
183         public static ReturnType setMetaAttribute(Session session) throws MusicLockingException {
184                 logger.debug(EELFLoggerDelegate.debugLogger, "setMetaAttribute: start with session id: " + session.getId());
185                 ReturnType result = null;
186                 PreparedQueryObject queryObject = new PreparedQueryObject();
187                 StringBuilder querySB = new StringBuilder();
188                 querySB.append("INSERT INTO ").append(musicKeySpace).append(".").append(musicMetaTable).append("(")
189                                 .append(MusicProperties.PRIMARY_ID).append(",").append(MusicProperties.CREATION_TIME).append(",")
190                                 .append(MusicProperties.LAST_ACCESS_TIME).append(",").append(MusicProperties.MAX_INACTIVE_INTERVAL)
191                                 .append(",").append(MusicProperties.SESSION_ID).append(") VALUES (?,?,?,?,?);");
192
193                 queryObject.appendQueryString(querySB.toString());
194                 queryObject.addValue(session.getId());
195                 queryObject.addValue(String.valueOf(session.getCreationTime()));
196                 queryObject.addValue(String.valueOf(session.getLastAccessedTime()));
197                 queryObject.addValue(String.valueOf(session.getMaxInactiveInterval()));
198                 queryObject.addValue(session.getId());
199                 if (isAtomicPut)
200                         result = MusicCore.atomicPut(musicKeySpace, musicMetaTable, session.getId(), queryObject, null);
201                 else
202                         result = modEventualPut(queryObject);
203                 logger.debug(EELFLoggerDelegate.debugLogger,
204                                 "setMetaAttribute: with session id: " + session + RESULT + result.getMessage());
205
206                 return result;
207         }
208
209         /**
210          * Retrieve session meta data from Cassandra via Music
211          *
212          * @param sessionId
213          * @return MusicSession
214          * @throws Exception
215          */
216         public static MusicSession getMetaAttribute(String sessionId) throws MusicLockingException,MusicServiceException {
217                 logger.debug(EELFLoggerDelegate.debugLogger, "getMetaAttribute: start with session Id: "+ sessionId);
218                 ResultSet result = null;
219                 PreparedQueryObject queryObject = new PreparedQueryObject();
220                 StringBuilder querySB = new StringBuilder();
221                 querySB.append("SELECT * FROM ").append(musicKeySpace).append(".").append(musicMetaTable).append(WHERE)
222                                 .append(MusicProperties.PRIMARY_ID).append("=?;");
223                 queryObject.appendQueryString(querySB.toString());
224                 queryObject.addValue(sessionId);
225                 if (isAtomicGet)
226                         result = MusicCore.atomicGet(musicKeySpace, musicMetaTable, sessionId, queryObject);
227                 else
228                         result = modEventualGet(queryObject);
229                 logger.debug(EELFLoggerDelegate.debugLogger, "getMetaAttribute: with session id: " + sessionId);
230                 return MusicUtil.parseMetaData(result.one());
231         }
232
233         
234         /**
235          * Get proper column names (from meta or attribute table) base on isMeta
236          *
237          * @param isMeta
238          * @param attributeName
239          * @return String
240          */
241         private static String getInsertQuery(boolean isMeta, String attributeName) {
242                 logger.debug(EELFLoggerDelegate.debugLogger, "getInsertQuery: start inserting : " + attributeName);
243                 StringBuilder querySB = new StringBuilder();
244                 if (isMeta) {
245                         querySB.append(" (").append(MusicProperties.PRIMARY_ID).append(",").append(attributeName)
246                                         .append(") VALUES (?,?);");
247                 } else {
248                         querySB.append(" (").append(MusicProperties.PRIMARY_ID).append(",").append(MusicProperties.ATTRIBUTE_NAME)
249                                         .append(",").append(MusicProperties.ATTRIBUTE_BYTES).append(") VALUES (?,?,?);");
250                 }
251                 return querySB.toString();
252         }
253
254         /**
255          * Retrieve session attribute data from Cassandra via Music
256          *
257          * @param attributeName
258          * @param sessionId
259          * @return attribute value with T type
260          * @throws Exception
261          */
262         public static <T> T getAttribute(String attributeName, String sessionId) throws Exception {
263                 logger.debug(EELFLoggerDelegate.debugLogger, "getAttribute: start with session id: " + sessionId);
264                 ResultSet result = null;
265                 String tableName = null;
266                 boolean isMeta = MusicUtil.isSessionMetaAttr(attributeName);
267                 PreparedQueryObject queryObject = new PreparedQueryObject();
268                 StringBuilder querySB = new StringBuilder();
269                 querySB.append("SELECT ").append(getColumn(attributeName, isMeta)).append(FROM).append(musicKeySpace)
270                                 .append(".").append(getTableName(isMeta)).append(WHERE).append(MusicProperties.PRIMARY_ID)
271                                 .append("= ?");
272
273                 queryObject.addValue(sessionId);
274                 if (!isMeta) {
275                         querySB.append(" and ").append(MusicProperties.ATTRIBUTE_NAME).append("= ?");
276                         queryObject.addValue(attributeName);
277                         tableName = musicAttrTable;
278                 } else
279                         tableName = musicMetaTable;
280
281                 queryObject.appendQueryString(querySB.toString());
282                 if (isAtomicGet)
283                         result = MusicCore.atomicGet(musicKeySpace, tableName, sessionId, queryObject);
284                 else
285                         result = modEventualGet(queryObject);
286                 return MusicUtil.musicRestResponseDataParsing(result, attributeName);
287
288         }
289
290         /**
291          * Remove session attribute data from Cassandra via Music
292          *
293          * @param attributeName
294          * @param sessionId
295          * @return ReturnType
296          * @throws MusicServiceException
297          * @throws MusicLockingException
298          */
299         public static ReturnType removeAttribute(String attributeName, String sessionId) throws MusicLockingException {
300                 logger.debug(EELFLoggerDelegate.debugLogger, "removeAttribute: start with session id: " + sessionId);
301                 boolean isMeta = MusicUtil.isSessionMetaAttr(attributeName);
302                 ReturnType result = null;
303                 String tableName = null;
304                 PreparedQueryObject queryObject = new PreparedQueryObject();
305                 StringBuilder querySB = new StringBuilder();
306                 querySB.append(DELETE).append(getDelColumn(isMeta, attributeName)).append(FROM).append(musicKeySpace)
307                                 .append(".").append(getTableName(isMeta)).append(WHERE).append(MusicProperties.PRIMARY_ID)
308                                 .append("= ? ");
309                 queryObject.addValue(sessionId);
310
311                 if (!isMeta) {
312                         querySB.append(" and ").append(MusicProperties.ATTRIBUTE_NAME).append("= ?");
313                         queryObject.addValue(attributeName);
314                         tableName = musicAttrTable;
315                 } else
316                         tableName = musicMetaTable;
317                 queryObject.appendQueryString(querySB.toString());
318                 if (isAtomicPut)
319                         result = MusicCore.atomicPut(musicKeySpace, tableName, sessionId, queryObject, null);
320                 else
321                         result = modEventualPut(queryObject);
322                 logger.debug(EELFLoggerDelegate.debugLogger,
323         REMOVE_SESSION + attributeName + WITH_SESSION_ID + sessionId + RESULT + result.getMessage());
324
325                 return result;
326         }
327
328         /**
329          * Remove entire session from Cassandra via Music
330          *
331          * @param sessionId
332          * @return ReturnType
333          * @throws MusicServiceException
334          * @throws MusicLockingException
335          */
336         public static ReturnType removeSession(String sessionId) throws MusicLockingException {
337                 ReturnType result = null;
338                 boolean isAtomic = isAtomicPut;
339                 logger.debug(EELFLoggerDelegate.debugLogger, "removeSession: start with session id: " + sessionId);
340                 PreparedQueryObject queryObject = new PreparedQueryObject();
341                 StringBuilder querySB = new StringBuilder();
342                 querySB.append(DELETE).append(FROM).append(musicKeySpace).append(".").append(musicMetaTable)
343                                 .append(WHERE).append(MusicProperties.PRIMARY_ID).append("= ? ");
344                 queryObject.appendQueryString(querySB.toString());
345                 queryObject.addValue(sessionId);
346                 if (isAtomic)
347                         result = MusicCore.atomicPut(musicKeySpace, musicMetaTable, sessionId, queryObject, null);
348                 else
349                         result = modEventualPut(queryObject);
350                 logger.debug(EELFLoggerDelegate.debugLogger, REMOVE_SESSION + musicMetaTable + WITH_SESSION_ID
351                                 + sessionId + RESULT + result.getMessage());
352
353                 queryObject = new PreparedQueryObject();
354                 querySB = new StringBuilder();
355                 querySB.append(DELETE).append(FROM).append(musicKeySpace).append(".").append(musicAttrTable)
356                                 .append(WHERE).append(MusicProperties.PRIMARY_ID).append("= ? ");
357                 queryObject.appendQueryString(querySB.toString());
358                 queryObject.addValue(sessionId);
359                 if (isAtomic)
360                         result = MusicCore.atomicPut(musicKeySpace, musicAttrTable, sessionId, queryObject, null);
361                 else
362                         result = modEventualPut(queryObject);
363
364                 logger.debug(EELFLoggerDelegate.debugLogger, REMOVE_SESSION + musicAttrTable + WITH_SESSION_ID
365                                 + sessionId + RESULT + result.getMessage());
366
367                 return result;
368         }
369
370         /**
371          * Get proper table name (Meta or Attribute) base on isMeta.
372          *
373          * @param isMeta
374          * @return String
375          */
376         private static String getTableName(boolean isMeta) {
377                 StringBuilder querySB = new StringBuilder();
378                 if (isMeta)
379                         querySB.append(musicMetaTable);
380                 else
381                         querySB.append(musicAttrTable);
382                 return querySB.toString();
383         }
384
385         /**
386          * Get proper column name (Meta or Attribute) base on isMeta.
387          *
388          * @param attributeName
389          * @param isMeta
390          * @return String
391          */
392         private static String getColumn(String attributeName, boolean isMeta) {
393                 StringBuilder querySB = new StringBuilder();
394                 if (isMeta)
395                         querySB.append(attributeName);
396                 else
397                         querySB.append("attribute_bytes");
398                 return querySB.toString();
399         }
400
401         /**
402          * Get proper column name (Meta or Attribute) base on isMeta for removing.
403          *
404          * @param attributeName
405          * @param isMeta
406          * @return String
407          */
408         private static String getDelColumn(boolean isMeta, String attributeName) {
409                 StringBuilder querySB = new StringBuilder();
410                 if (isMeta)
411                         querySB.append(attributeName);
412                 return querySB.toString();
413         }
414
415         /**
416          * To set session attributes in Music
417          *
418          * @param attributeName
419          * @param value
420          * @param session
421          * @param sessionId
422          * @param isMeta
423          * @return RestResponse<String>
424          * @throws JsonProcessingException
425          */
426
427         public static RestResponse<String> setAttributeAPI(String attributeName, Object value, Session session,
428                         String sessionId, String className, boolean isMeta) throws JsonProcessingException {
429                 logger.debug(EELFLoggerDelegate.debugLogger, "setAttribute: " + attributeName);
430                 RestResponse<String> portalRestResponse = null;
431                 HttpEntity<Map<String, Object>> entity = new HttpEntity<>(
432                                 getMusicRestBody(attributeName, value, sessionId, session, className, isMeta), getMusicHeader());
433                 String url = getInsertUrl(isMeta);
434                 ResponseEntity<String> response = null;
435                 try {
436                         response = template.exchange(url, HttpMethod.POST, entity, String.class);
437                         portalRestResponse = new RestResponse<>(RestStatusEnum.OK, SUCCESS, response.getBody());
438                 } catch (Exception e) {
439                         logger.debug(EELFLoggerDelegate.debugLogger, e.getLocalizedMessage());
440                         portalRestResponse = new RestResponse<>(RestStatusEnum.ERROR, e.getMessage(), null);
441                 }
442                 return portalRestResponse;
443         }
444
445         /**
446          * To get session attribute in Music
447          *
448          * @param attributeName
449          * @param value
450          * @param sessionId
451          * @param isMeta
452          * @return RestResponse<String>
453          */
454
455         public static RestResponse<String> getAttributeAPI(String attributeName, Object value, String sessionId,
456                         boolean isMeta) {
457                 logger.debug(EELFLoggerDelegate.debugLogger, "setAttribute: " + attributeName);
458                 RestResponse<String> portalRestResponse = null;
459                 HttpEntity<String> entity = new HttpEntity<>(null, getMusicHeader());
460                 ResponseEntity<String> response = null;
461                 String url = getSelectSessionIdUrl(attributeName, sessionId, isMeta);
462                 try {
463                         response = template.exchange(url, HttpMethod.GET, entity, String.class);
464                         portalRestResponse = new RestResponse<>(RestStatusEnum.OK, SUCCESS, response.getBody());
465                 } catch (Exception e) {
466                         logger.debug(EELFLoggerDelegate.debugLogger, e.getLocalizedMessage());
467                         portalRestResponse = new RestResponse<>(RestStatusEnum.ERROR, e.getMessage(), null);
468                 }
469                 return portalRestResponse;
470         }
471
472         /**
473          * To remove session attribute or session meta in Music
474          *
475          * @param attributeName
476          * @param sessionId
477          * @param isMeta
478          * @return RestResponse<String>
479          */
480         public static RestResponse<String> removeAttributeAPI(String attributeName, String sessionId, boolean isMeta) {
481                 RestResponse<String> portalRestResponse = null;
482                 HttpEntity<Map<String, Object>> entity = new HttpEntity<>(getMusicDelRestBody(null), getMusicHeader());
483                 ResponseEntity<String> response = null;
484                 String url = getSelectSessionIdUrl(attributeName, sessionId, true);
485                 try {
486                         url = getSelectSessionIdUrl(attributeName, sessionId, false);
487                         response = template.exchange(url, HttpMethod.DELETE, entity, String.class);
488                         portalRestResponse = new RestResponse<>(RestStatusEnum.OK, SUCCESS, response.getBody());
489                 } catch (Exception e) {
490                         logger.debug(EELFLoggerDelegate.debugLogger, e.getLocalizedMessage());
491                         portalRestResponse = new RestResponse<>(RestStatusEnum.ERROR, e.getMessage(), null);
492                 }
493                 return portalRestResponse;
494         }
495
496         /**
497          * Generate body for Music api calls
498          *
499          * @return String that includes required body information for Music api
500          *         calls
501          * @throws JsonProcessingException
502          */
503         public static Map<String, Object> getMusicRestBody(String attributeName, Object value, String sessionId,
504                         Session session, String className, boolean isMeta) throws JsonProcessingException {
505                 Map<String, Object> map = new HashMap<>();
506                 /* Set up column values */
507                 Map<String, Object> valueMap = new HashMap<>();
508                 if (isMeta) {
509                         valueMap.put(MusicProperties.PRIMARY_ID, session.getId());
510                         valueMap.put(MusicProperties.SESSION_ID, session.getId());
511                         valueMap.put(MusicProperties.CREATION_TIME, session.getCreationTime().toString());
512                         valueMap.put(MusicProperties.LAST_ACCESS_TIME, session.getLastAccessedTime().toString());
513                         valueMap.put(MusicProperties.MAX_INACTIVE_INTERVAL, session.getMaxInactiveInterval().toString());
514                 } else {
515                         ObjectMapper mapper = new ObjectMapper();
516                         valueMap.put(MusicProperties.PRIMARY_ID, sessionId);
517                         valueMap.put(MusicProperties.ATTRIBUTE_NAME, attributeName);
518                         valueMap.put(MusicProperties.ATTRIBUTE_BYTES, mapper.writeValueAsString(value));
519                         valueMap.put(MusicProperties.ATTRIBUTE_CLASS, className);
520                 }
521                 map.put("values", valueMap);
522                 /* Set up consistency setting */
523                 Map<String, String> consistencyInfoMap = new HashMap<>();
524                 consistencyInfoMap.put(MusicProperties.getProperty(MusicProperties.MUSIC_CONSISTENCYINFO),
525                                 MusicProperties.getProperty(MusicProperties.MUSIC_CONSISTENCYINFO_VALUE));
526                 map.put("consistencyInfo", consistencyInfoMap);
527                 return map;
528         }
529
530         /**
531          * Generate body for Music delete api calls
532          *
533          * @return String that includes required body information for Music api
534          *         calls
535          * @throws JsonProcessingException
536          */
537         public static Map<String, Object> getMusicDelRestBody(String attributeName) {
538                 Map<String, Object> map = new HashMap<>();
539                 Map<String, String> consistencyInfoMap = new HashMap<>();
540                 consistencyInfoMap.put(MusicProperties.getProperty(MusicProperties.MUSIC_CONSISTENCYINFO),
541                                 MusicProperties.getProperty(MusicProperties.MUSIC_CONSISTENCYINFO_VALUE));
542                 if (attributeName != null && !attributeName.isEmpty()) {
543                         Map<String, String> conditionsMap = new HashMap<>();
544                         conditionsMap.put("attribute_name", attributeName);
545                         map.put("conditions", conditionsMap);
546                 }
547                 map.put("consistencyInfo", consistencyInfoMap);
548                 return map;
549         }
550
551         private static String getSelectSessionIdUrl(String attributeName, String sessionId, boolean isMeta) {
552                 String path = constructPath(isMeta);
553                 StringBuilder attriPath = new StringBuilder();
554                 attriPath.append(path).append(MusicProperties.getProperty(MusicProperties.MUSIC_ROWS)).append("?")
555                                 .append(MusicProperties.PRIMARY_ID).append("=").append(sessionId);
556                 return attriPath.toString();
557         }
558
559         private static String getInsertUrl(boolean isMeta) {
560                 String path = constructPath(isMeta);
561                 StringBuilder attriPath = new StringBuilder();
562                 attriPath.append(path);
563                 attriPath.append(MusicProperties.getProperty(MusicProperties.MUSIC_ROWS));
564                 return attriPath.toString();
565         }
566
567         /**
568          * Generate header for Music api calls
569          *
570          * @return header that contains required header information for Music api
571          *         calls
572          */
573         private static HttpHeaders getMusicHeader() {
574                 HttpHeaders headers = new HttpHeaders();
575                 headers.setContentType(MediaType.APPLICATION_JSON);
576                 headers.add("X-minorVersion", MusicProperties.getProperty(MusicProperties.MUSIC_X_MINOR_VERSION));
577                 headers.add("X-patchVersion", MusicProperties.getProperty(MusicProperties.MUSIC_X_PATCH_VERSION));
578                 headers.add("ns", MusicProperties.getProperty(MusicProperties.MUSIC_NS));
579                 headers.add("userId", MusicProperties.getProperty(MusicProperties.MUSIC_USER_ID));
580                 headers.add("password", MusicProperties.getProperty(MusicProperties.MUSIC_PASSWORD));
581                 return headers;
582         }
583
584         /**
585          * Construct URL for Music api calls
586          *
587          * @return path
588          */
589         private static String constructPath(boolean isMeta) {
590                 StringBuilder path = new StringBuilder();
591                 path.append(MusicProperties.getProperty(MusicProperties.MUSIC_ENDPOINT))
592                                 .append(MusicProperties.getProperty(MusicProperties.MUSIC_VERSION)).append("/")
593                                 .append(MusicProperties.getProperty(MusicProperties.MUSIC_KEYSPACE)).append("/").append(musicKeySpace)
594                                 .append("/").append(MusicProperties.getProperty(MusicProperties.MUSIC_TABLES)).append("/");
595                 if (isMeta)
596                         path.append(musicMetaTable);
597                 else
598                         path.append(musicAttrTable);
599                 path.append("/");
600                 return path.toString();
601         }
602
603         /**
604          * Get a list of sessions that need to be cleaned up
605          *
606          * @return List<String>
607          */
608         private static List<String> getSessionToBeDeleted(){
609                 logger.debug(EELFLoggerDelegate.debugLogger, "initial getSessionToBeDeleted ...");
610
611                 PreparedQueryObject queryObject = new PreparedQueryObject();
612                 ResultSet result = null;
613                 List<String> sessionIDList = new ArrayList<>();
614                 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
615                 StringBuilder querySB = new StringBuilder();
616                 String cleanUpThreshold = MusicProperties.getProperty(MusicProperties.MUSIC_CLEAN_UP_THRESHOLD); //Clean up sessions that's cleanUpThreshold hours ago
617                 Date dateForCleanup = new Date(System.currentTimeMillis() - 3600 * 1000 * Integer.valueOf(cleanUpThreshold)); // Get the threshold date that needs to be clean up
618                 String dateForCleanupCondition = dateFormat.format(dateForCleanup);
619                 querySB.append("SELECT ").append(MusicProperties.PRIMARY_ID).append(FROM).append(musicKeySpace)
620                 .append(".").append(getTableName(true)).append(WHERE).append(MusicProperties.LAST_ACCESS_TIME)
621                 .append("< ? ").append(" ALLOW FILTERING");
622                 queryObject.appendQueryString(querySB.toString());
623                 queryObject.addValue(dateForCleanupCondition);
624
625                 try{
626                         if (isAtomicGet)
627                                 result = MusicCore.atomicGet(musicKeySpace, musicMetaTable, null, queryObject);
628                         else
629                                 result = modEventualGet(queryObject);
630                         Row row = result.one();
631                         while(row!=null){
632                                 sessionIDList.add(row.get(MusicProperties.PRIMARY_ID, String.class));
633                                 row = result.one();
634                         }
635                 }catch(Exception e){
636                         logger.error(EELFLoggerDelegate.errorLogger, "Error while cleaning up music tables" , e);
637                 }
638                 return sessionIDList;
639         }
640
641         /**
642          * Remove session data in music base on the defined frequency
643          *
644          * @return List<String>
645          */
646         public static void cleanUpMusic() {
647                 boolean timeToCleanUp = MusicUtil.cleanUp(); // Decide whether to clean up or not
648
649                 if(timeToCleanUp){
650                         /**Getting a list of sessions that need to be cleaned up*/
651                         List<String> sessionIDList = getSessionToBeDeleted();
652                         if(sessionIDList!=null || !sessionIDList.isEmpty()){
653                                 StringBuilder sessionIDListCondition = new StringBuilder();
654                                 sessionIDListCondition.append("('");
655                                 for(String s : sessionIDList){
656                                         sessionIDListCondition.append(s);
657                                         sessionIDListCondition.append("','");
658                                 }
659                                 sessionIDListCondition.deleteCharAt(sessionIDListCondition.length()-1);
660                                 sessionIDListCondition.deleteCharAt(sessionIDListCondition.length()-1);
661                                 sessionIDListCondition.append(")");
662                                 StringBuilder querySB = new StringBuilder();
663                                 PreparedQueryObject queryObject = new PreparedQueryObject();
664                                 /**Deleting attributes table**/
665                                 querySB = new StringBuilder();
666                                 queryObject = new PreparedQueryObject();
667                                 querySB.append("DELETE FROM ").append(musicKeySpace)
668                                 .append(".").append(getTableName(false)).append(WHERE).append(MusicProperties.PRIMARY_ID)
669                                 .append(" in ").append(sessionIDListCondition);
670                                 queryObject.appendQueryString(querySB.toString());
671                                 try{
672                                         if (isAtomicPut)
673                                                 MusicCore.atomicPut(musicKeySpace, null, null, queryObject, null);
674                                         else
675                                                 modEventualPut(queryObject);
676                                 }catch(Exception e){
677                                         logger.error(EELFLoggerDelegate.errorLogger, "Error while cleaning up music attributes tables" , e);
678                                 }
679                                 logger.debug(EELFLoggerDelegate.debugLogger, "Music sessions have been cleaned up !");
680
681                                 /**Deleting meta table**/
682                                 logger.debug(EELFLoggerDelegate.debugLogger, "Cleaning up meta table ...");
683                                 querySB = new StringBuilder();
684                                 queryObject = new PreparedQueryObject();
685                                 querySB.append("DELETE FROM ").append(musicKeySpace)
686                                 .append(".").append(getTableName(true)).append(WHERE).append(MusicProperties.PRIMARY_ID)
687                                 .append(" in ").append(sessionIDListCondition);
688                                 queryObject.appendQueryString(querySB.toString());
689                                 try{
690                                         if (isAtomicPut)
691                                                 MusicCore.atomicPut(musicKeySpace, null, null, queryObject, null);
692                                         else
693                                                 modEventualPut(queryObject);
694                                 }catch(Exception e){
695                                         logger.error(EELFLoggerDelegate.errorLogger, "Error while cleaning up music meta tables" , e);
696                                 }
697
698                                 logger.debug(EELFLoggerDelegate.debugLogger, "Cleaned up attributes table ... ");
699                         }else{
700                                 logger.debug(EELFLoggerDelegate.debugLogger, "No Session needs to be cleaned up");
701                         }
702
703                 }
704         }
705
706         public static ReturnType modEventualPut(PreparedQueryObject queryObject) {
707                  boolean result = false;
708                 try {
709                     result = MusicCore.getDSHandle().executePut(queryObject,CRITICAL);
710                 } catch (MusicServiceException | MusicQueryException ex) {
711                          logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() + "  " + ex.getCause() + " " + ex);
712                     return new ReturnType(ResultType.FAILURE, ex.getMessage());
713                 }
714                 if (result) {
715                     return new ReturnType(ResultType.SUCCESS, "Success");
716                 } else {
717                     return new ReturnType(ResultType.FAILURE, "Failure");
718                 }
719         }
720         
721         public static ResultSet modEventualGet(PreparedQueryObject queryObject) throws MusicServiceException {
722                 ResultSet result;
723                 result = MusicCore.quorumGet(queryObject);
724                 return result;
725         }
726
727
728 }