diff options
author | Manoop Talasila <talasila@research.att.com> | 2018-06-21 17:22:24 +0000 |
---|---|---|
committer | Gerrit Code Review <gerrit@onap.org> | 2018-06-21 17:22:24 +0000 |
commit | 91f92ed363e4f6b5b103a37f18af5ca7a21af9ba (patch) | |
tree | 4fea4198990100aeff1bae293a6919d918fae612 | |
parent | 2edaa4d6a5f7066e0c718f85a7bf7b8dabd0c59b (diff) | |
parent | a68c7de8ca9d38fbdf0801252a4185c8fd94cea6 (diff) |
Merge "Music health check apis"
12 files changed, 1032 insertions, 77 deletions
diff --git a/docs/platform/offeredapis.rst b/docs/platform/offeredapis.rst index eadbf64a..de6655b6 100644 --- a/docs/platform/offeredapis.rst +++ b/docs/platform/offeredapis.rst @@ -9,6 +9,8 @@ Offered APIs :depth: 2 The following API calls are available for the PORTAL Platform subsystem: + +Changed the V1 api's to V3 api's as a part of API versioning of ONAP components. PORTAL API Services ^^^^^^^^^^^^^^^^^^^^^^ diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/config/ExternalSecurityConfig.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/config/ExternalSecurityConfig.java index 5354fa39..9f125b75 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/config/ExternalSecurityConfig.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/config/ExternalSecurityConfig.java @@ -41,11 +41,13 @@ import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; +import org.onap.portalapp.music.util.MusicUtil; import org.onap.portalapp.portal.utils.MusicCookieCsrfTokenRepository; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.csrf.CookieCsrfTokenRepository; import org.springframework.security.web.util.matcher.RegexRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; @@ -67,6 +69,9 @@ public class ExternalSecurityConfig extends WebSecurityConfigurerAdapter { return false; } }; - http.csrf().csrfTokenRepository(MusicCookieCsrfTokenRepository.withHttpOnlyFalse()).requireCsrfProtectionMatcher(csrfRequestMatcher); + if(MusicUtil.isMusicEnable()) + http.csrf().csrfTokenRepository(MusicCookieCsrfTokenRepository.withHttpOnlyFalse()).requireCsrfProtectionMatcher(csrfRequestMatcher); + else + http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).requireCsrfProtectionMatcher(csrfRequestMatcher); } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/conf/MusicSessionRepositoryHandler.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/conf/MusicSessionRepositoryHandler.java new file mode 100644 index 00000000..cd911b80 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/conf/MusicSessionRepositoryHandler.java @@ -0,0 +1,105 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright © 2018 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ +package org.onap.portalapp.music.conf; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.music.exceptions.MusicLockingException; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.portalapp.music.service.MusicService; +import org.onap.portalapp.music.util.MusicUtil; +import org.springframework.session.Session; + +public class MusicSessionRepositoryHandler { + + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicSessionRepositoryHandler.class); + private final Map<String, Session> sessions = new ConcurrentHashMap<>(); + private boolean musicCache = MusicUtil.isCached(); + + + public Session get(String id) { + if(musicCache){ + // todo need to add the clean up for "sessions" map if musicCache is enabled + return this.sessions.get(id); + }else{ + try { + Session session = MusicService.getMetaAttribute(id); + return session; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "get failed with id " + id, e); + return null; + } + } + } + + + + public void remove(String id) { + if(musicCache){ + // todo need to add the clean up for "sessions" map if musicCache is enabled + sessions.remove(id); + }else{ + try { + MusicService.removeSession(id); + } catch (MusicLockingException e) { + logger.error(EELFLoggerDelegate.errorLogger, "removeSession locking failed with id " + id, e); + } catch (MusicServiceException e) { + logger.error(EELFLoggerDelegate.errorLogger, "removeSession failed with id " + id, e); + } + } + } + + + + public void put(String id, MusicSession musicSession) { + if(musicCache){ + // todo need to add the clean up for "sessions" map if musicCache is enabled + sessions.put(id, musicSession); + }else{ + try { + MusicService.setMetaAttribute(musicSession); + MusicService.cleanUpMusic(); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "setMetaAttribute failed with id " + id, e); + } + } + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/filter/MusicSessionRepositoryFilter.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/filter/MusicSessionRepositoryFilter.java new file mode 100644 index 00000000..84181e8f --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/filter/MusicSessionRepositoryFilter.java @@ -0,0 +1,70 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright © 2018 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + *. + */ + +package org.onap.portalapp.music.filter; + +import java.io.IOException; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; + +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.portalapp.music.util.MusicUtil; +import org.springframework.web.filter.DelegatingFilterProxy; + +public class MusicSessionRepositoryFilter extends DelegatingFilterProxy{ + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class); + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + try{ + if (request instanceof HttpServletRequest) { + String path = ((HttpServletRequest)request).getRequestURI().substring(((HttpServletRequest) request).getContextPath().length()); + if(MusicUtil.isExcludedApi(path) || !MusicUtil.isMusicEnable()) + request.setAttribute("org.springframework.session.web.http.SessionRepositoryFilter.FILTERED", Boolean.TRUE); + } + }catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to check the exclude apis ", e); + } + super.doFilter(request, response, filterChain); + } +}
\ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/util/MusicProperties.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/util/MusicProperties.java new file mode 100644 index 00000000..5ff22635 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/util/MusicProperties.java @@ -0,0 +1,189 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright © 2018 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portalapp.music.util; + + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.portalapp.music.service.MusicService; + + +public class MusicProperties { + + public static final String MUSIC_ENDPOINT = "music.endpoint"; + + public static final String MUSIC_VERSION = "music.version"; + + public static final String MUSIC_KEYSPACE = "music.keyspace"; + + public static final String MUSIC_SESSION_KEYSPACE = "music.session.keyspace"; + + public static final String MUSIC_TABLES = "TABLES"; + + public static final String MUSIC_SESSION_ATTR_TABLES = "music.session.attr.tables"; + + public static final String MUSIC_SESSION_META_TABLES = "music.session.meta.tables"; + + public static final String MUSIC_ROWS = "ROW"; + + public static final String MUSIC_SESSION_ROW = "music.sesion.rows"; + + public static final String MUSIC_X_MINOR_VERSION = "music.x.minor.version"; + + public static final String MUSIC_X_PATCH_VERSION = "music.x.patch.version"; + + public static final String MUSIC_AID = "AID"; + + public static final String MUSIC_NS = "music.ns"; + + public static final String MUSIC_USER_ID = "music.user.id"; + + public static final String MUSIC_PASSWORD = "music.password"; + + public static final String MUSIC_CONSISTENCYINFO = "music.consistency.info"; + + public static final String MUSIC_CONSISTENCYINFO_VALUE = "music.consistency.info.value"; + + public static final String MUSIC_CACHE = "music.cache"; + + public static final String MUSIC_SERIALIZE_COMPRESS = "music.serialize.compress"; + + public static final String MUSIC_ATOMIC_GET = "music.atomic.get"; + + public static final String MUSIC_ATOMIC_PUT = "music.atomic.put"; + + public static final String MUSIC_ATOMIC_POST = "music.atomic.post"; + + public static final String MUSIC_EXCLUDE_API = "music.exclude.api"; + + public static final String MUSIC_CLEAN_UP_FREQUENCY = "music.cleanup.frequency"; + + public static final String MUSIC_CLEAN_UP_THRESHOLD = "music.cleanup.threshold"; + + public static final String MUSIC_ENABLE = "music.enable"; + + public static final String SESSION_MAX_INACTIVE_INTERVAL_SECONDS = "music.session.max.inactive.interval.seconds"; + + public static final String ATTRIBUTE_NAME = "ATTRIBUTE_NAME"; + + public static final String ATTRIBUTE_BYTES = "ATTRIBUTE_BYTES"; + + public static final String ATTRIBUTE_CLASS = "ATTRIBUTE_CLASS"; + + public static final String PRIMARY_ID = "PRIMARY_ID"; + + public static final String SESSION_ID = "SESSION_ID"; + + public static final String CREATION_TIME = "CREATION_TIME"; + + public static final String LAST_ACCESS_TIME = "LAST_ACCESS_TIME"; + + public static final String MAX_INACTIVE_INTERVAL = "MAX_INACTIVE_INTERVAL"; + + public static final String EXPIRY_TIME = "EXPIRY_TIME"; + + public static final String PRINCIPAL_NAME = "PRINCIPAL_NAME"; + + private MusicProperties(){} + + private static Properties properties; + + private static String propertyFileName = "music.properties"; + + private static final Object lockObject = new Object(); + + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicProperties.class); + + /** + * Gets the property value for the specified key. If a value is found, leading + * and trailing space is trimmed. + * + * @param property + * Property key + * @return Value for the named property; null if the property file was not + * loaded or the key was not found. + */ + public static String getProperty(String property) { + if (properties == null) { + synchronized (lockObject) { + try { + if (!initialize()) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to read property file " + propertyFileName); + return null; + } + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to read property file " + propertyFileName ,e); + return null; + } + } + } + String value = properties.getProperty(property); + if (value != null) + value = value.trim(); + return value; + } + + /** + * Reads properties from a portal.properties file on the classpath. + * + * Clients do NOT need to call this method. Clients MAY call this method to test + * whether the properties file can be loaded successfully. + * + * @return True if properties were successfully loaded, else false. + * @throws IOException + * On failure + */ + private static boolean initialize() throws IOException { + if (properties != null) + return true; + InputStream in = MusicProperties.class.getClassLoader().getResourceAsStream(propertyFileName); + if (in == null) + return false; + properties = new Properties(); + try { + properties.load(in); + } finally { + in.close(); + } + return true; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/util/MusicUtil.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/util/MusicUtil.java new file mode 100644 index 00000000..308528d5 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/util/MusicUtil.java @@ -0,0 +1,219 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright © 2018 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ +package org.onap.portalapp.music.util; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.nio.ByteBuffer; +import java.time.Duration; +import java.time.Instant; +import java.util.Arrays; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.portalapp.music.conf.MusicSession; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; + +public class MusicUtil { + private static final Set<String> sessionAttrNameSet = new HashSet<>(Arrays.asList("CREATION_TIME", "LAST_ACCESS_TIME","MAX_INACTIVE_INTERVAL","EXPIRY_TIME","PRINCIPAL_NAME")); + + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class); + private static String atomicPut = MusicProperties.getProperty(MusicProperties.MUSIC_ATOMIC_PUT); + private static String atomicGet = MusicProperties.getProperty(MusicProperties.MUSIC_ATOMIC_GET); + private static String cached = MusicProperties.getProperty(MusicProperties.MUSIC_CACHE); + private static String cleanUpFreq = MusicProperties.getProperty(MusicProperties.MUSIC_CLEAN_UP_FREQUENCY); + private static String musicSerializeCompress = MusicProperties.getProperty(MusicProperties.MUSIC_SERIALIZE_COMPRESS); + private static String musicEnable = MusicProperties.getProperty(MusicProperties.MUSIC_ENABLE); + private static final int MILLIS_IN_HOUR = 3600000; + + public static boolean isSessionMetaAttr(String key){ + return sessionAttrNameSet.contains(key); + } + + public static <T> T musicRestResponseDataParsing(ResultSet rs, String attributeName) throws Exception{ + logger.debug(EELFLoggerDelegate.debugLogger, "musicRestResponseDataParsing: start"); + Row row = rs.one(); + if(!sessionAttrNameSet.contains(attributeName)){ + if(row!=null) + return MusicUtil.musicDeserialize(row.getBytes("attribute_bytes")); + }else{ + return (T) row.getString(attributeName); + } + return null; + } + + public static <T> T musicDeserialize (ByteBuffer byteBuf) throws Exception{ + logger.debug(EELFLoggerDelegate.debugLogger, "musicDeserialize: start"); + ByteArrayInputStream byteArr = new ByteArrayInputStream(byteBuf.array()); + ObjectInputStream ois = null; + if(isMusicSerializeCompress()){ + GZIPInputStream zos = new GZIPInputStream(byteArr); + ois = new ObjectInputStream(zos); + }else{ + ois = new ObjectInputStream(byteArr); + } + return (T) ois.readObject(); + } + + public static ByteBuffer musicSerialize (Object value) throws Exception{ + logger.debug(EELFLoggerDelegate.debugLogger, "musicSerialize: start"); + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + try { + if(isMusicSerializeCompress()){ + GZIPOutputStream zos = new GZIPOutputStream(bo); + ObjectOutputStream oos = new ObjectOutputStream(zos); + oos.writeObject(value); + oos.flush(); + zos.finish(); + }else{ + ObjectOutputStream oos = new ObjectOutputStream(bo); + oos.writeObject(value); + oos.flush(); + } + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to serialize "); + } + return ByteBuffer.wrap(bo.toByteArray()); + } + + public static MusicSession parseMetaData (Row row) throws Exception{ + logger.debug(EELFLoggerDelegate.debugLogger, "parseMetaData: start"); + + if(row==null) + return null; + String sessionId = row.getString("primary_id"); + MusicSession musicSession = new MusicSession(sessionId); + musicSession.setCreationTime(Instant.parse(row.getString("creation_time"))); + musicSession.setLastAccessedTime(Instant.parse(row.getString("last_access_time"))); + musicSession.setMaxInactiveInterval(Duration.parse(row.getString("max_inactive_interval"))); + return musicSession; + } + + public static Set<String> getMusicExcludedAPI(){ + Set<String> excludedApiSet = new HashSet<>(); + String musicExcludedApi = MusicProperties.getProperty(MusicProperties.MUSIC_EXCLUDE_API); + String[] musicExcludedApiArray = musicExcludedApi.split(","); + if(musicExcludedApiArray.length>0){ + for(String str : musicExcludedApiArray){ + excludedApiSet.add(str.trim()); + } + } + return excludedApiSet; + } + + public static boolean isExcludedApi(String api){ + Set<String> excludedApiSet = getMusicExcludedAPI(); + for(String str: excludedApiSet){ + if(api.matches(str)) + return true; + } + return false; + } + + + public static boolean isMusicSerializeCompress(){ + if(musicSerializeCompress==null){ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to read property file " + MusicProperties.MUSIC_SERIALIZE_COMPRESS +" fall back to eventual put"); + return false; + } + return musicSerializeCompress.trim().equalsIgnoreCase("true"); + } + + public static boolean isAtomicPut(){ + if(atomicPut==null){ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to read property file " + MusicProperties.MUSIC_ATOMIC_PUT +" fall back to eventual put"); + return false; + } + return atomicPut.trim().equalsIgnoreCase("true"); + } + + public static boolean isAtomicGet(){ + if(atomicGet==null){ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to read property file " + MusicProperties.MUSIC_ATOMIC_GET +" fall back to eventual get"); + return false; + } + return atomicGet.trim().equalsIgnoreCase("true"); + } + + public static boolean isCached(){ + if(cached==null){ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to read property file " + MusicProperties.MUSIC_CACHE +" fall back to non cache"); + return false; + } + return cached.trim().equalsIgnoreCase("true"); + } + + public static int convertHoursToMillSec(int hour){ + return hour* MILLIS_IN_HOUR; + } + + public static boolean cleanUp(){ + Date lastCleanUpDate = MusicCleanUp.getInstance().getLastCleanUpTime(); + if(lastCleanUpDate==null) + return false; + else{ + int cleanUpDurationMili = convertHoursToMillSec(Integer.valueOf(cleanUpFreq)); + Date currentTime = new Date(); + long diffInMillies = Math.abs(currentTime.getTime() - lastCleanUpDate.getTime()); + if(diffInMillies > cleanUpDurationMili){ + MusicCleanUp.getInstance().updateLastCleanUpTimeToCurrent(); + return true; + } + else + return false; + } + } + + public static boolean isMusicEnable(){ + if(musicEnable==null) + return false; + if(musicEnable.equals("true")) + return true; + else + return false; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java index f1628e02..811e10ce 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java @@ -179,28 +179,31 @@ public class HealthCheckController extends EPUnRestrictedBaseController { } statusCollection.add(dbInfo); - HealthStatusInfo CassandraStatusInfo = new HealthStatusInfo("Music-Cassandra"); - //CassandraStatusInfo.hostName = EcompPortalUtils.getMyHostName(); - CassandraStatusInfo.ipAddress = MusicUtil.getMyCassaHost(); - - if (!HealthMonitor.isCassandraStatusOk()) { - overallStatus = false; - CassandraStatusInfo.healthCheckStatus = statusDown; - CassandraStatusInfo.description = "Check the logs for more details"; - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.MusicHealthCheckCassandraError); - } - statusCollection.add(CassandraStatusInfo); - - HealthStatusInfo zookeeperStatusInfo = new HealthStatusInfo("Music-zookeeper"); - //zookeeperStatusInfo.hostName = EcompPortalUtils.getMyHostName(); - zookeeperStatusInfo.ipAddress = MusicUtil.getMyZkHost(); - if (!HealthMonitor.isZookeeperStatusOk()) { - overallStatus = false; - zookeeperStatusInfo.healthCheckStatus = statusDown; - zookeeperStatusInfo.description = "Check the logs for more details"; - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.MusicHealthCheckZookeeperError); + org.onap.portalapp.music.util.MusicUtil MusicUtilSDK = new org.onap.portalapp.music.util.MusicUtil(); + if(MusicUtilSDK.isMusicEnable()){ + HealthStatusInfo CassandraStatusInfo = new HealthStatusInfo("Music-Cassandra"); + //CassandraStatusInfo.hostName = EcompPortalUtils.getMyHostName(); + CassandraStatusInfo.ipAddress = MusicUtil.getMyCassaHost(); + + if (!HealthMonitor.isCassandraStatusOk()) { + overallStatus = false; + CassandraStatusInfo.healthCheckStatus = statusDown; + CassandraStatusInfo.description = "Check the logs for more details"; + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.MusicHealthCheckCassandraError); + } + statusCollection.add(CassandraStatusInfo); + + HealthStatusInfo zookeeperStatusInfo = new HealthStatusInfo("Music-zookeeper"); + //zookeeperStatusInfo.hostName = EcompPortalUtils.getMyHostName(); + zookeeperStatusInfo.ipAddress = MusicUtil.getMyZkHost(); + if (!HealthMonitor.isZookeeperStatusOk()) { + overallStatus = false; + zookeeperStatusInfo.healthCheckStatus = statusDown; + zookeeperStatusInfo.description = "Check the logs for more details"; + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.MusicHealthCheckZookeeperError); + } + statusCollection.add(zookeeperStatusInfo); } - statusCollection.add(zookeeperStatusInfo); String json = ""; try { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java index 6f934e98..82f5637d 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java @@ -37,11 +37,8 @@ */ package org.onap.portalapp.portal.listener; -import java.io.IOException; -import java.util.HashSet; +import java.time.Instant; import java.util.List; -import java.util.Set; -import java.util.UUID; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; @@ -93,6 +90,7 @@ public class HealthMonitor { private static boolean dbPermissionsOk; private static boolean zookeeperStatusOk; private static boolean cassandraStatusOk; + private static String APPLICATION = "Portal"; /** * Read directly by external classes. @@ -194,31 +192,34 @@ public class HealthMonitor { numIntervalsDatabasePermissionsIncorrect = 0; } } - - zookeeperStatusOk = this.checkZookeeperStatus(); - if (zookeeperStatusOk == false) { - if ((numIntervalsZookeeperNotHealthy % numIntervalsBetweenAlerts) == 0) { - logger.debug(EELFLoggerDelegate.debugLogger, - "monitorEPHealth: cluster nodes down, logging to error log to trigger alert."); - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.MusicHealthCheckZookeeperError); - numIntervalsZookeeperNotHealthy++; - } else { - numIntervalsZookeeperNotHealthy = 0; + org.onap.portalapp.music.util.MusicUtil MusicUtilSDK = new org.onap.portalapp.music.util.MusicUtil(); + if(MusicUtilSDK.isMusicEnable()){ + zookeeperStatusOk = this.checkZookeeperStatus(); + if (zookeeperStatusOk == false) { + if ((numIntervalsZookeeperNotHealthy % numIntervalsBetweenAlerts) == 0) { + logger.debug(EELFLoggerDelegate.debugLogger, + "monitorEPHealth: cluster nodes down, logging to error log to trigger alert."); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.MusicHealthCheckZookeeperError); + numIntervalsZookeeperNotHealthy++; + } else { + numIntervalsZookeeperNotHealthy = 0; + } } - } - cassandraStatusOk = this.checkCassandraStatus(); - if (cassandraStatusOk == false) { - if ((numIntervalsCassandraNotHealthy % numIntervalsBetweenAlerts) == 0) { - logger.debug(EELFLoggerDelegate.debugLogger, - "monitorEPHealth: cluster nodes down, logging to error log to trigger alert."); - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.MusicHealthCheckCassandraError); - numIntervalsCassandraNotHealthy++; - } else { - numIntervalsCassandraNotHealthy = 0; + cassandraStatusOk = this.checkCassandraStatus(); + if (cassandraStatusOk == false) { + if ((numIntervalsCassandraNotHealthy % numIntervalsBetweenAlerts) == 0) { + logger.debug(EELFLoggerDelegate.debugLogger, + "monitorEPHealth: cluster nodes down, logging to error log to trigger alert."); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.MusicHealthCheckCassandraError); + numIntervalsCassandraNotHealthy++; + } else { + numIntervalsCassandraNotHealthy = 0; + } } } + // // Get UEB status. Publish a bogus message to EP inbox, if 200 OK // returned, status is Up. @@ -396,30 +397,23 @@ public class HealthMonitor { } private Boolean getAdminKeySpace() { - String musicKeySpace = MusicProperties.getProperty(MusicProperties.MUSIC_SESSION_KEYSPACE ); - //deletePortalHealthcheck(musicKeySpace); + String musicKeySpace = MusicProperties.getProperty(MusicProperties.MUSIC_SESSION_KEYSPACE); + Instant creationTime = Instant.now(); PreparedQueryObject pQuery = new PreparedQueryObject(); - pQuery.appendQueryString("insert into "+musicKeySpace+".healthcheck (id) values (?)"); - pQuery.addValue(UUID.randomUUID()); + pQuery.appendQueryString( + "UPDATE " + musicKeySpace + ".health_check SET creation_time = ? WHERE primary_id = ?"); + pQuery.addValue(creationTime.toString()); + pQuery.addValue(APPLICATION); try { - MusicCore.nonKeyRelatedPut(pQuery, MusicUtil.EVENTUAL); + MusicCore.nonKeyRelatedPut(pQuery, MusicUtil.ATOMIC); + MusicCore.nonKeyRelatedPut(pQuery, MusicUtil.CRITICAL); } catch (MusicServiceException e) { - logger.error(EELFLoggerDelegate.errorLogger, "getAdminKeySpace() failed", e.getCause()); return Boolean.FALSE; } - return Boolean.TRUE; - } + return Boolean.TRUE; - - private void deletePortalHealthcheck(String musicKeySpace) { - PreparedQueryObject pQuery = new PreparedQueryObject(); - pQuery.appendQueryString("TRUNCATE "+musicKeySpace+".healthcheck"); - try { - MusicCore.nonKeyRelatedPut(pQuery, MusicUtil.EVENTUAL); - } catch (MusicServiceException e) { - logger.error(EELFLoggerDelegate.errorLogger, "deletePortalHealthcheck() failed", e.getCause()); - } } + private boolean checkDatabasePermissions() { boolean isUp = false; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterface.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterface.java index 0522b395..825d33a2 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterface.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterface.java @@ -37,7 +37,9 @@ */ package org.onap.portalapp.portal.scheduler; +import java.lang.reflect.Type; import java.util.Collections; +import java.util.Date; import javax.security.auth.login.CredentialException; import javax.ws.rs.client.Client; @@ -48,8 +50,10 @@ import javax.ws.rs.core.Response; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; +import org.apache.cxf.jaxrs.impl.ResponseImpl; import org.eclipse.jetty.util.security.Password; import org.json.simple.JSONObject; +import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum; import org.onap.portalapp.portal.logging.logic.EPLogUtil; import org.onap.portalapp.portal.scheduler.client.HttpBasicClient; import org.onap.portalapp.portal.scheduler.client.HttpsBasicClient; @@ -59,6 +63,14 @@ import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.client.HttpClientErrorException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; + @Service public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { @@ -75,9 +87,30 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { super(); } + Gson gson = null; + + private final ObjectMapper mapper = new ObjectMapper(); + + private void init() { + logger.debug(EELFLoggerDelegate.debugLogger, "initializing"); + GsonBuilder builder = new GsonBuilder(); + + // Register an adapter to manage the date types as long values + builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { + public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) + throws JsonParseException { + return new Date(json.getAsJsonPrimitive().getAsLong()); + } + }); + + gson = builder.create(); + } + public void initRestClient() { logger.debug(EELFLoggerDelegate.debugLogger, "Starting to initialize rest client"); + init(); + final String username; final String password; @@ -103,7 +136,7 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { } try { if (StringUtils.isBlank(password)) { - throw new CredentialException(PASSWORD_IS_EMPTY); + throw new CredentialException(PASSWORD_IS_EMPTY); } } catch (Exception ex) { logger.error(EELFLoggerDelegate.errorLogger, "Unable to initialize rest client", ex); @@ -147,7 +180,26 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { int status = cres.getStatus(); restObject.setStatusCode(status); - t = (T) cres.readEntity(t.getClass()); + if (cres != null && cres.getEntity() != null) { + try { + String str = ((ResponseImpl) cres).readEntity(String.class); + if (t.getClass().getName().equals(String.class.getName())) { + t = (T) str; + + } else { + t = (T) gson.fromJson(str, t.getClass()); + } + + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e); + } + } else { + t = null; + restObject.set(t); + } + + // t = (T) cres.readEntity(t.getClass()); + if (t.equals("")) { restObject.set(null); } else { @@ -155,12 +207,11 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { } } catch (HttpClientErrorException e) { String message = String.format( - " HttpClientErrorException: Exception For the POST . MethodName: %s, Url: %s", methodName,url); + " HttpClientErrorException: Exception For the POST . MethodName: %s, Url: %s", methodName, url); logger.error(EELFLoggerDelegate.errorLogger, message, e); EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value()); } catch (Exception e) { - String message = String.format( - "Exception For the POST . MethodName: %s, Url: %s", methodName,url); + String message = String.format("Exception For the POST . MethodName: %s, Url: %s", methodName, url); logger.error(EELFLoggerDelegate.errorLogger, message, e); EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value()); @@ -176,7 +227,7 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { String methodName = "Post"; String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path; - logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR POST : "+ url); + logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR POST : " + url); try { @@ -186,8 +237,21 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { final Response cres = client.target(url).request().accept("application/json").headers(commonHeaders) .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON)); - if (cres.getEntity() != null) { - t = (T) cres.readEntity(t.getClass()); + if (cres != null && cres.getEntity() != null) { + + try { + String str = ((ResponseImpl) cres).readEntity(String.class); + if (t.getClass().getName().equals(String.class.getName())) { + t = (T) str; + + } else { + t = (T) gson.fromJson(str, t.getClass()); + } + + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e); + } + // t = (T) cres.readEntity(t.getClass()); restObject.set(t); } else { t = null; @@ -198,24 +262,23 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { restObject.setStatusCode(status); if (status >= 200 && status <= 299) { - String message = String.format( - " REST api POST was successful!", methodName); + String message = String.format(" REST api POST was successful!", methodName); logger.debug(EELFLoggerDelegate.debugLogger, message); } else { - String message = String.format( - " FAILED with http status . MethodName: %s, Status: %s, Url: %s", methodName,status,url); + String message = String.format(" FAILED with http status . MethodName: %s, Status: %s, Url: %s", + methodName, status, url); logger.debug(EELFLoggerDelegate.debugLogger, message); } } catch (HttpClientErrorException e) { String message = String.format( - " HttpClientErrorException: Exception For the POST . MethodName: %s, Url: %s", methodName,url); + " HttpClientErrorException: Exception For the POST . MethodName: %s, Url: %s", methodName, url); logger.error(EELFLoggerDelegate.errorLogger, message, e); EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value()); } catch (Exception e) { String message = String.format( - " HttpClientErrorException: Exception For the POST . MethodName: %s, Url: %s", methodName,url); + " HttpClientErrorException: Exception For the POST . MethodName: %s, Url: %s", methodName, url); logger.error(EELFLoggerDelegate.errorLogger, message, e); EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value()); throw e; diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/music/conf/MusicSessionRepositoryHandlerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/music/conf/MusicSessionRepositoryHandlerTest.java new file mode 100644 index 00000000..3b622f2e --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/music/conf/MusicSessionRepositoryHandlerTest.java @@ -0,0 +1,103 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright © 2018 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ +package org.onap.portalapp.music.conf; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.main.MusicCore; +import org.onap.portalapp.music.service.MusicService; +import org.onap.portalapp.music.util.MusicUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.session.Session; + +import com.datastax.driver.core.ResultSet; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({MusicUtil.class, MusicCore.class}) +public class MusicSessionRepositoryHandlerTest { + + @Mock + private MusicService musicService; + + @Mock + ResultSet resultSet; + + @Before + public void setUp() { + PowerMockito.mockStatic(MusicUtil.class); + PowerMockito.mockStatic(MusicCore.class); + Mockito.when(MusicUtil.isCached()).thenReturn(true); + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + MusicSessionRepositoryHandler musicSessionRepositoryHandler = new MusicSessionRepositoryHandler(); + + MusicSession ms = new MusicSession(); + + + @SuppressWarnings("static-access") + @Test + public void getTest() throws Exception { + Mockito.when(MusicCore.get(Matchers.any(PreparedQueryObject.class))).thenReturn(resultSet); + Mockito.when(musicService.getMetaAttribute("test_id")).thenReturn(ms); + Session session = musicSessionRepositoryHandler.get("test_id"); + assertNotNull(session); + } + + @SuppressWarnings("static-access") + @Test + public void getFailWithIdTest() throws Exception { + Mockito.when(MusicCore.get(Matchers.any(PreparedQueryObject.class))).thenReturn(resultSet); + Mockito.when((musicService).getMetaAttribute("test_id")).thenThrow(new NullPointerException()); + Session session = musicSessionRepositoryHandler.get("test_id"); + assertNull(session); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/music/util/MusicPropertiesTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/music/util/MusicPropertiesTest.java new file mode 100644 index 00000000..721f9410 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/music/util/MusicPropertiesTest.java @@ -0,0 +1,54 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright © 2018 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ +package org.onap.portalapp.music.util; + +import static org.junit.Assert.assertNull; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class MusicPropertiesTest { + + @Test + public void getPropertyTest() { + assertNull(MusicProperties.getProperty("test")); + } +} + diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/music/util/MusicUtilTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/music/util/MusicUtilTest.java new file mode 100644 index 00000000..a570ab89 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/music/util/MusicUtilTest.java @@ -0,0 +1,148 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright © 2018 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ +package org.onap.portalapp.music.util; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.music.conf.MusicSession; +import org.onap.portalapp.music.service.MusicService; +import org.onap.portalapp.music.util.MusicCleanUp; +import org.onap.portalapp.music.util.MusicProperties; +import org.onap.portalapp.music.util.MusicUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ MusicProperties.class, MusicSession.class, MusicService.class, MusicCleanUp.class }) +public class MusicUtilTest { + + ResultSet result = Mockito.mock(ResultSet.class); + + Row rw = Mockito.mock(Row.class); + + @Before + public void setUp() throws Exception { + MusicCleanUp musCleapUp = mock(MusicCleanUp.class); + PowerMockito.mockStatic(MusicProperties.class); + PowerMockito.mockStatic(MusicSession.class); + PowerMockito.mockStatic(MusicService.class); + PowerMockito.mockStatic(MusicCleanUp.class); + Mockito.when(MusicProperties.getProperty(MusicProperties.MUSIC_ATOMIC_PUT)).thenReturn("atomic-put"); + Mockito.when(MusicProperties.getProperty(MusicProperties.MUSIC_ATOMIC_GET)).thenReturn("atomic-get"); + Mockito.when(MusicProperties.getProperty(MusicProperties.MUSIC_CACHE)).thenReturn("cache"); + Mockito.when(MusicProperties.getProperty(MusicProperties.MUSIC_EXCLUDE_API)).thenReturn("test1,test2"); + PowerMockito.when(MusicProperties.getProperty(MusicProperties.MUSIC_SERIALIZE_COMPRESS)).thenReturn("compress"); + PowerMockito.when(MusicCleanUp.getInstance()).thenReturn(musCleapUp); + PowerMockito.when(musCleapUp.getLastCleanUpTime()).thenReturn(null); + MockitoAnnotations.initMocks(this); + } + + @Test + public void isSessionMetaAttrTest() { + assertTrue(MusicUtil.isSessionMetaAttr("CREATION_TIME")); + } + + @Test + public void musicRestResponseDataParsingTest() throws Exception { + List<Row> rows = new ArrayList<Row>(); + Mockito.doReturn("creation time").when(rw).getString("CREATION_TIME"); + rows.add(rw); + Mockito.doReturn(rows.get(0)).when(result).one(); + assertNotNull(MusicUtil.musicRestResponseDataParsing(result, "CREATION_TIME")); + } + + @Test + public void getMusicExcludedAPITest() { + assertNotNull(MusicUtil.getMusicExcludedAPI()); + } + + @Test + public void isExcludedApiTest() { + assertTrue(MusicUtil.isExcludedApi("test1")); + } + + @Test + public void isExcludedApiFalseTest() { + assertFalse(MusicUtil.isExcludedApi("test3")); + } + + @Test + public void isMusicSerializeCompressReturnFalseTest() { + assertFalse(MusicUtil.isMusicSerializeCompress()); + } + + @Test + public void isAtomicPutTest() { + assertFalse(MusicUtil.isAtomicPut()); + } + + @Test + public void isAtomicGetTest() { + assertFalse(MusicUtil.isAtomicGet()); + } + + @Test + public void isCachedTest() { + assertFalse(MusicUtil.isCached()); + } + + @Test + public void convertHoursToMillSecTest() { + assertNotNull(MusicUtil.convertHoursToMillSec(1)); + } + + @Test + public void cleanUpTest() { + assertFalse(MusicUtil.cleanUp()); + } +} |