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