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);
85 //MusicCore.getDSHandle();
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);
94 public static void init() {
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")) {
100 } catch (Exception var11) {
101 logger.error(EELFLoggerDelegate.errorLogger, "Unable to find properties file.");
102 //throw new Exception();
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);
117 } catch(Exception e) {
118 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e);
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);
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";
141 * Store session attribute name and values into Cassandra via Music
143 * @param attributeName
146 * @return ReturnType that includes required body information for Music api
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));
159 queryObject.appendQueryString(querySB.toString());
161 queryObject.addValue(sessionId);
162 queryObject.addValue(String.valueOf(value));
163 tableName = musicMetaTable;
165 queryObject.addValue(sessionId);
166 queryObject.addValue(attributeName);
167 queryObject.addValue(MusicUtil.musicSerialize(value));
168 tableName = musicAttrTable;
172 result = MusicCore.atomicPut(musicKeySpace, tableName, sessionId, queryObject, null);
174 result = modEventualPut(queryObject);
175 logger.debug(EELFLoggerDelegate.debugLogger, "setAttribute: attributeName: " + attributeName
176 + WITH_SESSION_ID + sessionId + RESULT + result.getMessage());
181 * Store session meta data values into Cassandra via Music
184 * @return ReturnType that includes required body information for Music api
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 (?,?,?,?,?);");
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());
204 result = MusicCore.atomicPut(musicKeySpace, musicMetaTable, session.getId(), queryObject, null);
206 result = modEventualPut(queryObject);
207 logger.debug(EELFLoggerDelegate.debugLogger,
208 "setMetaAttribute: with session id: " + session + RESULT + result.getMessage());
214 * Retrieve session meta data from Cassandra via Music
217 * @return MusicSession
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);
230 result = MusicCore.atomicGet(musicKeySpace, musicMetaTable, sessionId, queryObject);
232 result = modEventualGet(queryObject);
233 logger.debug(EELFLoggerDelegate.debugLogger, "getMetaAttribute: with session id: " + sessionId);
234 return MusicUtil.parseMetaData(result.one());
239 * Get proper column names (from meta or attribute table) base on isMeta
242 * @param attributeName
245 private static String getInsertQuery(boolean isMeta, String attributeName) {
246 logger.debug(EELFLoggerDelegate.debugLogger, "getInsertQuery: start inserting : " + attributeName);
247 StringBuilder querySB = new StringBuilder();
249 querySB.append(" (").append(MusicProperties.PRIMARY_ID).append(",").append(attributeName)
250 .append(") VALUES (?,?);");
252 querySB.append(" (").append(MusicProperties.PRIMARY_ID).append(",").append(MusicProperties.ATTRIBUTE_NAME)
253 .append(",").append(MusicProperties.ATTRIBUTE_BYTES).append(") VALUES (?,?,?);");
255 return querySB.toString();
259 * Retrieve session attribute data from Cassandra via Music
261 * @param attributeName
263 * @return attribute value with T type
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)
277 queryObject.addValue(sessionId);
279 querySB.append(" and ").append(MusicProperties.ATTRIBUTE_NAME).append("= ?");
280 queryObject.addValue(attributeName);
281 tableName = musicAttrTable;
283 tableName = musicMetaTable;
285 queryObject.appendQueryString(querySB.toString());
287 result = MusicCore.atomicGet(musicKeySpace, tableName, sessionId, queryObject);
289 result = modEventualGet(queryObject);
290 return MusicUtil.musicRestResponseDataParsing(result, attributeName);
295 * Remove session attribute data from Cassandra via Music
297 * @param attributeName
300 * @throws MusicServiceException
301 * @throws MusicLockingException
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)
313 queryObject.addValue(sessionId);
316 querySB.append(" and ").append(MusicProperties.ATTRIBUTE_NAME).append("= ?");
317 queryObject.addValue(attributeName);
318 tableName = musicAttrTable;
320 tableName = musicMetaTable;
321 queryObject.appendQueryString(querySB.toString());
323 result = MusicCore.atomicPut(musicKeySpace, tableName, sessionId, queryObject, null);
325 result = modEventualPut(queryObject);
326 logger.debug(EELFLoggerDelegate.debugLogger,
327 REMOVE_SESSION + attributeName + WITH_SESSION_ID + sessionId + RESULT + result.getMessage());
333 * Remove entire session from Cassandra via Music
337 * @throws MusicServiceException
338 * @throws MusicLockingException
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);
351 result = MusicCore.atomicPut(musicKeySpace, musicMetaTable, sessionId, queryObject, null);
353 result = modEventualPut(queryObject);
354 logger.debug(EELFLoggerDelegate.debugLogger, REMOVE_SESSION + musicMetaTable + WITH_SESSION_ID
355 + sessionId + RESULT + result.getMessage());
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);
364 result = MusicCore.atomicPut(musicKeySpace, musicAttrTable, sessionId, queryObject, null);
366 result = modEventualPut(queryObject);
368 logger.debug(EELFLoggerDelegate.debugLogger, REMOVE_SESSION + musicAttrTable + WITH_SESSION_ID
369 + sessionId + RESULT + result.getMessage());
375 * Get proper table name (Meta or Attribute) base on isMeta.
380 private static String getTableName(boolean isMeta) {
381 StringBuilder querySB = new StringBuilder();
383 querySB.append(musicMetaTable);
385 querySB.append(musicAttrTable);
386 return querySB.toString();
390 * Get proper column name (Meta or Attribute) base on isMeta.
392 * @param attributeName
396 private static String getColumn(String attributeName, boolean isMeta) {
397 StringBuilder querySB = new StringBuilder();
399 querySB.append(attributeName);
401 querySB.append("attribute_bytes");
402 return querySB.toString();
406 * Get proper column name (Meta or Attribute) base on isMeta for removing.
408 * @param attributeName
412 private static String getDelColumn(boolean isMeta, String attributeName) {
413 StringBuilder querySB = new StringBuilder();
415 querySB.append(attributeName);
416 return querySB.toString();
420 * To set session attributes in Music
422 * @param attributeName
427 * @return RestResponse<String>
428 * @throws JsonProcessingException
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;
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);
446 return portalRestResponse;
450 * To get session attribute in Music
452 * @param attributeName
456 * @return RestResponse<String>
459 public static RestResponse<String> getAttributeAPI(String attributeName, Object value, String sessionId,
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);
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);
473 return portalRestResponse;
477 * To remove session attribute or session meta in Music
479 * @param attributeName
482 * @return RestResponse<String>
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);
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);
497 return portalRestResponse;
501 * Generate body for Music api calls
503 * @return String that includes required body information for Music api
505 * @throws JsonProcessingException
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<>();
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());
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);
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);
535 * Generate body for Music delete api calls
537 * @return String that includes required body information for Music api
539 * @throws JsonProcessingException
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);
551 map.put("consistencyInfo", consistencyInfoMap);
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();
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();
572 * Generate header for Music api calls
574 * @return header that contains required header information for Music api
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));
589 * Construct URL for Music api calls
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("/");
600 path.append(musicMetaTable);
602 path.append(musicAttrTable);
604 return path.toString();
608 * Get a list of sessions that need to be cleaned up
610 * @return List<String>
612 private static List<String> getSessionToBeDeleted(){
613 logger.debug(EELFLoggerDelegate.debugLogger, "initial getSessionToBeDeleted ...");
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);
631 result = MusicCore.atomicGet(musicKeySpace, musicMetaTable, null, queryObject);
633 result = modEventualGet(queryObject);
634 Row row = result.one();
636 sessionIDList.add(row.get(MusicProperties.PRIMARY_ID, String.class));
640 logger.error(EELFLoggerDelegate.errorLogger, "Error while cleaning up music tables" , e);
642 return sessionIDList;
646 * Remove session data in music base on the defined frequency
648 * @return List<String>
650 public static void cleanUpMusic() {
651 boolean timeToCleanUp = MusicUtil.cleanUp(); // Decide whether to clean up or not
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("','");
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());
677 MusicCore.atomicPut(musicKeySpace, null, null, queryObject, null);
679 modEventualPut(queryObject);
681 logger.error(EELFLoggerDelegate.errorLogger, "Error while cleaning up music attributes tables" , e);
683 logger.debug(EELFLoggerDelegate.debugLogger, "Music sessions have been cleaned up !");
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());
695 MusicCore.atomicPut(musicKeySpace, null, null, queryObject, null);
697 modEventualPut(queryObject);
699 logger.error(EELFLoggerDelegate.errorLogger, "Error while cleaning up music meta tables" , e);
702 logger.debug(EELFLoggerDelegate.debugLogger, "Cleaned up attributes table ... ");
704 logger.debug(EELFLoggerDelegate.debugLogger, "No Session needs to be cleaned up");
710 public static ReturnType modEventualPut(PreparedQueryObject queryObject) {
711 boolean result = false;
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());
719 return new ReturnType(ResultType.SUCCESS, "Success");
721 return new ReturnType(ResultType.FAILURE, "Failure");
725 public static ResultSet modEventualGet(PreparedQueryObject queryObject) throws MusicServiceException {
727 result = MusicCore.quorumGet(queryObject);