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