2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
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
26 * https://creativecommons.org/licenses/by/4.0/
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.
34 * ============LICENSE_END============================================
39 package org.onap.portalapp.music.service;
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;
49 import java.util.Properties;
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;
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;
79 public class MusicService {
80 static RestTemplate template = new RestTemplate();
81 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicService.class);
84 public static void init() {
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")) {
90 } catch (Exception var11) {
91 logger.error(EELFLoggerDelegate.errorLogger, "Unable to find properties file.");
92 //throw new Exception();
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, "Cassandra Password Decrypted " + decryptedPassword);
100 logger.debug(EELFLoggerDelegate.debugLogger, "Setting Decrypted password ");
101 // set decrypted password
102 org.onap.music.main.MusicUtil.setCassPwd(decryptedPassword);
103 logger.debug(EELFLoggerDelegate.debugLogger, "Creating cassandra connections pool and sessions by calling MusicDataStore and passing the cassandra hostname ");
104 // Here we are creating cassandra connections pool and sessions by calling MusicDataStore and passing the cassandrra hostname to that.
105 MusicCore.mDstoreHandle = new MusicDataStore(org.onap.music.main.MusicUtil.getMyCassaHost());
106 // Since mDstoreHandle is already initialized in init mthod, calling this method again will have no impact on mDstoreHandle.
107 logger.debug(EELFLoggerDelegate.debugLogger, "Calling MusicCore getDSHandle() method ");
108 MusicCore.getDSHandle();
109 } catch (Exception e) {
110 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e);
113 } catch(Exception e) {
114 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e);
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);
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";
137 * Store session attribute name and values into Cassandra via Music
139 * @param attributeName
142 * @return ReturnType that includes required body information for Music api
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));
155 queryObject.appendQueryString(querySB.toString());
157 queryObject.addValue(sessionId);
158 queryObject.addValue(String.valueOf(value));
159 tableName = musicMetaTable;
161 queryObject.addValue(sessionId);
162 queryObject.addValue(attributeName);
163 queryObject.addValue(MusicUtil.musicSerialize(value));
164 tableName = musicAttrTable;
168 result = MusicCore.atomicPut(musicKeySpace, tableName, sessionId, queryObject, null);
170 result = modEventualPut(queryObject);
171 logger.debug(EELFLoggerDelegate.debugLogger, "setAttribute: attributeName: " + attributeName
172 + WITH_SESSION_ID + sessionId + RESULT + result.getMessage());
177 * Store session meta data values into Cassandra via Music
180 * @return ReturnType that includes required body information for Music api
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 (?,?,?,?,?);");
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());
200 result = MusicCore.atomicPut(musicKeySpace, musicMetaTable, session.getId(), queryObject, null);
202 result = modEventualPut(queryObject);
203 logger.debug(EELFLoggerDelegate.debugLogger,
204 "setMetaAttribute: with session id: " + session + RESULT + result.getMessage());
210 * Retrieve session meta data from Cassandra via Music
213 * @return MusicSession
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);
226 result = MusicCore.atomicGet(musicKeySpace, musicMetaTable, sessionId, queryObject);
228 result = modEventualGet(queryObject);
229 logger.debug(EELFLoggerDelegate.debugLogger, "getMetaAttribute: with session id: " + sessionId);
230 return MusicUtil.parseMetaData(result.one());
235 * Get proper column names (from meta or attribute table) base on isMeta
238 * @param attributeName
241 private static String getInsertQuery(boolean isMeta, String attributeName) {
242 logger.debug(EELFLoggerDelegate.debugLogger, "getInsertQuery: start inserting : " + attributeName);
243 StringBuilder querySB = new StringBuilder();
245 querySB.append(" (").append(MusicProperties.PRIMARY_ID).append(",").append(attributeName)
246 .append(") VALUES (?,?);");
248 querySB.append(" (").append(MusicProperties.PRIMARY_ID).append(",").append(MusicProperties.ATTRIBUTE_NAME)
249 .append(",").append(MusicProperties.ATTRIBUTE_BYTES).append(") VALUES (?,?,?);");
251 return querySB.toString();
255 * Retrieve session attribute data from Cassandra via Music
257 * @param attributeName
259 * @return attribute value with T type
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)
273 queryObject.addValue(sessionId);
275 querySB.append(" and ").append(MusicProperties.ATTRIBUTE_NAME).append("= ?");
276 queryObject.addValue(attributeName);
277 tableName = musicAttrTable;
279 tableName = musicMetaTable;
281 queryObject.appendQueryString(querySB.toString());
283 result = MusicCore.atomicGet(musicKeySpace, tableName, sessionId, queryObject);
285 result = modEventualGet(queryObject);
286 return MusicUtil.musicRestResponseDataParsing(result, attributeName);
291 * Remove session attribute data from Cassandra via Music
293 * @param attributeName
296 * @throws MusicServiceException
297 * @throws MusicLockingException
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)
309 queryObject.addValue(sessionId);
312 querySB.append(" and ").append(MusicProperties.ATTRIBUTE_NAME).append("= ?");
313 queryObject.addValue(attributeName);
314 tableName = musicAttrTable;
316 tableName = musicMetaTable;
317 queryObject.appendQueryString(querySB.toString());
319 result = MusicCore.atomicPut(musicKeySpace, tableName, sessionId, queryObject, null);
321 result = modEventualPut(queryObject);
322 logger.debug(EELFLoggerDelegate.debugLogger,
323 REMOVE_SESSION + attributeName + WITH_SESSION_ID + sessionId + RESULT + result.getMessage());
329 * Remove entire session from Cassandra via Music
333 * @throws MusicServiceException
334 * @throws MusicLockingException
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);
347 result = MusicCore.atomicPut(musicKeySpace, musicMetaTable, sessionId, queryObject, null);
349 result = modEventualPut(queryObject);
350 logger.debug(EELFLoggerDelegate.debugLogger, REMOVE_SESSION + musicMetaTable + WITH_SESSION_ID
351 + sessionId + RESULT + result.getMessage());
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);
360 result = MusicCore.atomicPut(musicKeySpace, musicAttrTable, sessionId, queryObject, null);
362 result = modEventualPut(queryObject);
364 logger.debug(EELFLoggerDelegate.debugLogger, REMOVE_SESSION + musicAttrTable + WITH_SESSION_ID
365 + sessionId + RESULT + result.getMessage());
371 * Get proper table name (Meta or Attribute) base on isMeta.
376 private static String getTableName(boolean isMeta) {
377 StringBuilder querySB = new StringBuilder();
379 querySB.append(musicMetaTable);
381 querySB.append(musicAttrTable);
382 return querySB.toString();
386 * Get proper column name (Meta or Attribute) base on isMeta.
388 * @param attributeName
392 private static String getColumn(String attributeName, boolean isMeta) {
393 StringBuilder querySB = new StringBuilder();
395 querySB.append(attributeName);
397 querySB.append("attribute_bytes");
398 return querySB.toString();
402 * Get proper column name (Meta or Attribute) base on isMeta for removing.
404 * @param attributeName
408 private static String getDelColumn(boolean isMeta, String attributeName) {
409 StringBuilder querySB = new StringBuilder();
411 querySB.append(attributeName);
412 return querySB.toString();
416 * To set session attributes in Music
418 * @param attributeName
423 * @return RestResponse<String>
424 * @throws JsonProcessingException
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;
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);
442 return portalRestResponse;
446 * To get session attribute in Music
448 * @param attributeName
452 * @return RestResponse<String>
455 public static RestResponse<String> getAttributeAPI(String attributeName, Object value, String sessionId,
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);
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);
469 return portalRestResponse;
473 * To remove session attribute or session meta in Music
475 * @param attributeName
478 * @return RestResponse<String>
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);
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);
493 return portalRestResponse;
497 * Generate body for Music api calls
499 * @return String that includes required body information for Music api
501 * @throws JsonProcessingException
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<>();
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());
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);
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);
531 * Generate body for Music delete api calls
533 * @return String that includes required body information for Music api
535 * @throws JsonProcessingException
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);
547 map.put("consistencyInfo", consistencyInfoMap);
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();
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();
568 * Generate header for Music api calls
570 * @return header that contains required header information for Music api
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));
585 * Construct URL for Music api calls
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("/");
596 path.append(musicMetaTable);
598 path.append(musicAttrTable);
600 return path.toString();
604 * Get a list of sessions that need to be cleaned up
606 * @return List<String>
608 private static List<String> getSessionToBeDeleted(){
609 logger.debug(EELFLoggerDelegate.debugLogger, "initial getSessionToBeDeleted ...");
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);
627 result = MusicCore.atomicGet(musicKeySpace, musicMetaTable, null, queryObject);
629 result = modEventualGet(queryObject);
630 Row row = result.one();
632 sessionIDList.add(row.get(MusicProperties.PRIMARY_ID, String.class));
636 logger.error(EELFLoggerDelegate.errorLogger, "Error while cleaning up music tables" , e);
638 return sessionIDList;
642 * Remove session data in music base on the defined frequency
644 * @return List<String>
646 public static void cleanUpMusic() {
647 boolean timeToCleanUp = MusicUtil.cleanUp(); // Decide whether to clean up or not
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("','");
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());
673 MusicCore.atomicPut(musicKeySpace, null, null, queryObject, null);
675 modEventualPut(queryObject);
677 logger.error(EELFLoggerDelegate.errorLogger, "Error while cleaning up music attributes tables" , e);
679 logger.debug(EELFLoggerDelegate.debugLogger, "Music sessions have been cleaned up !");
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());
691 MusicCore.atomicPut(musicKeySpace, null, null, queryObject, null);
693 modEventualPut(queryObject);
695 logger.error(EELFLoggerDelegate.errorLogger, "Error while cleaning up music meta tables" , e);
698 logger.debug(EELFLoggerDelegate.debugLogger, "Cleaned up attributes table ... ");
700 logger.debug(EELFLoggerDelegate.debugLogger, "No Session needs to be cleaned up");
706 public static ReturnType modEventualPut(PreparedQueryObject queryObject) {
707 boolean result = false;
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());
715 return new ReturnType(ResultType.SUCCESS, "Success");
717 return new ReturnType(ResultType.FAILURE, "Failure");
721 public static ResultSet modEventualGet(PreparedQueryObject queryObject) throws MusicServiceException {
723 result = MusicCore.quorumGet(queryObject);