summaryrefslogtreecommitdiffstats
path: root/ecomp-portal-BE-common/src/main/java
diff options
context:
space:
mode:
Diffstat (limited to 'ecomp-portal-BE-common/src/main/java')
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/service/MusicService.java688
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/util/MusicProperties.java225
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/util/MusicUtil.java220
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulController.java31
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/FunctionalMenuController.java12
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java21
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppController.java41
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPServiceCookie.java54
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/exceptions/NoHealthyServiceException.java4
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java1
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java25
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterface.java104
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterfaceIfc.java5
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpBasicClient.java15
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java2
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java34
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/WidgetMService.java18
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/WidgetMServiceImpl.java9
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java3
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/FunctionalMenuItem.java7
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EPCommonSystemProperties.java6
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java18
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/MusicCookieCsrfTokenRepository.java28
-rw-r--r--ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/CommonSessionCookieUtil.java151
24 files changed, 1144 insertions, 578 deletions
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/service/MusicService.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/service/MusicService.java
new file mode 100644
index 00000000..323a71fe
--- /dev/null
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/service/MusicService.java
@@ -0,0 +1,688 @@
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal
+ * ===================================================================
+ * Copyright © 2017 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.service;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.onap.music.datastore.PreparedQueryObject;
+import org.onap.music.eelf.logging.EELFLoggerDelegate;
+import org.onap.music.exceptions.MusicLockingException;
+import org.onap.music.exceptions.MusicQueryException;
+import org.onap.music.exceptions.MusicServiceException;
+import org.onap.music.main.MusicCore;
+import org.onap.music.main.ResultType;
+import org.onap.music.main.ReturnType;
+import org.onap.portalapp.music.conf.MusicSession;
+import org.onap.portalapp.music.model.RestResponse;
+import org.onap.portalapp.music.model.RestStatusEnum;
+import org.onap.portalapp.music.util.MusicProperties;
+import org.onap.portalapp.music.util.MusicUtil;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.session.Session;
+import org.springframework.web.client.RestTemplate;
+
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+public class MusicService {
+ static RestTemplate template = new RestTemplate();
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicService.class);
+
+ private static boolean isAtomicPut = MusicUtil.isAtomicPut();
+ private static boolean isAtomicGet = MusicUtil.isAtomicGet();
+ private static String musicKeySpace = MusicProperties.getProperty(MusicProperties.MUSIC_SESSION_KEYSPACE);
+ private static String musicMetaTable = MusicProperties.getProperty(MusicProperties.MUSIC_SESSION_META_TABLES);
+ private static String musicAttrTable = MusicProperties.getProperty(MusicProperties.MUSIC_SESSION_ATTR_TABLES);
+
+ private static final String WITH_SESSION_ID = " with session id: ";
+ private static final String RESULT = "result:";
+ private static final String WHERE = " WHERE ";
+ private static final String FROM = " FROM ";
+ private static final String DELETE = "DELETE ";
+ private static final String REMOVE_SESSION = "removeSession: ";
+ private static final String SUCCESS = "success";
+ public static final String ATOMIC = "atomic";
+ public static final String EVENTUAL = "eventual";
+ public static final String CRITICAL = "critical";
+
+ /**
+ * Store session attribute name and values into Cassandra via Music
+ *
+ * @param attributeName
+ * @param value
+ * @param sessionId
+ * @return ReturnType that includes required body information for Music api
+ * @throws Exception
+ */
+ public static ReturnType setAttribute(String attributeName, Object value, String sessionId) throws MusicLockingException {
+ logger.debug(EELFLoggerDelegate.debugLogger, "setAttribute: start with id " + sessionId);
+ String tableName = null;
+ ReturnType result = null;
+ boolean isMeta = MusicUtil.isSessionMetaAttr(attributeName);
+ PreparedQueryObject queryObject = new PreparedQueryObject();
+ StringBuilder querySB = new StringBuilder();
+ querySB.append("INSERT INTO ").append(musicKeySpace).append(".").append(getTableName(isMeta))
+ .append(getInsertQuery(isMeta, attributeName));
+
+ queryObject.appendQueryString(querySB.toString());
+ if (isMeta) {
+ queryObject.addValue(sessionId);
+ queryObject.addValue(String.valueOf(value));
+ tableName = musicMetaTable;
+ } else {
+ queryObject.addValue(sessionId);
+ queryObject.addValue(attributeName);
+ queryObject.addValue(MusicUtil.musicSerialize(value));
+ tableName = musicAttrTable;
+
+ }
+ if (isAtomicPut)
+ result = MusicCore.atomicPut(musicKeySpace, tableName, sessionId, queryObject, null);
+ else
+ result = modEventualPut(queryObject);
+ logger.debug(EELFLoggerDelegate.debugLogger, "setAttribute: attributeName: " + attributeName
+ + WITH_SESSION_ID + sessionId + RESULT + result.getMessage());
+ return result;
+ }
+
+ /**
+ * Store session meta data values into Cassandra via Music
+ *
+ * @param session
+ * @return ReturnType that includes required body information for Music api
+ * @throws Exception
+ */
+ public static ReturnType setMetaAttribute(Session session) throws MusicLockingException {
+ logger.debug(EELFLoggerDelegate.debugLogger, "setMetaAttribute: start with session id: " + session.getId());
+ ReturnType result = null;
+ PreparedQueryObject queryObject = new PreparedQueryObject();
+ StringBuilder querySB = new StringBuilder();
+ querySB.append("INSERT INTO ").append(musicKeySpace).append(".").append(musicMetaTable).append("(")
+ .append(MusicProperties.PRIMARY_ID).append(",").append(MusicProperties.CREATION_TIME).append(",")
+ .append(MusicProperties.LAST_ACCESS_TIME).append(",").append(MusicProperties.MAX_INACTIVE_INTERVAL)
+ .append(",").append(MusicProperties.SESSION_ID).append(") VALUES (?,?,?,?,?);");
+
+ queryObject.appendQueryString(querySB.toString());
+ queryObject.addValue(session.getId());
+ queryObject.addValue(String.valueOf(session.getCreationTime()));
+ queryObject.addValue(String.valueOf(session.getLastAccessedTime()));
+ queryObject.addValue(String.valueOf(session.getMaxInactiveInterval()));
+ queryObject.addValue(session.getId());
+ if (isAtomicPut)
+ result = MusicCore.atomicPut(musicKeySpace, musicMetaTable, session.getId(), queryObject, null);
+ else
+ result = modEventualPut(queryObject);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "setMetaAttribute: with session id: " + session + RESULT + result.getMessage());
+
+ return result;
+ }
+
+ /**
+ * Retrieve session meta data from Cassandra via Music
+ *
+ * @param sessionId
+ * @return MusicSession
+ * @throws Exception
+ */
+ public static MusicSession getMetaAttribute(String sessionId) throws MusicLockingException,MusicServiceException {
+ logger.debug(EELFLoggerDelegate.debugLogger, "getMetaAttribute: start with session Id: "+ sessionId);
+ ResultSet result = null;
+ PreparedQueryObject queryObject = new PreparedQueryObject();
+ StringBuilder querySB = new StringBuilder();
+ querySB.append("SELECT * FROM ").append(musicKeySpace).append(".").append(musicMetaTable).append(WHERE)
+ .append(MusicProperties.PRIMARY_ID).append("=?;");
+ queryObject.appendQueryString(querySB.toString());
+ queryObject.addValue(sessionId);
+ if (isAtomicGet)
+ result = MusicCore.atomicGet(musicKeySpace, musicMetaTable, sessionId, queryObject);
+ else
+ result = modEventualGet(queryObject);
+ logger.debug(EELFLoggerDelegate.debugLogger, "getMetaAttribute: with session id: " + sessionId);
+ return MusicUtil.parseMetaData(result.one());
+ }
+
+
+ /**
+ * Get proper column names (from meta or attribute table) base on isMeta
+ *
+ * @param isMeta
+ * @param attributeName
+ * @return String
+ */
+ private static String getInsertQuery(boolean isMeta, String attributeName) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "getInsertQuery: start inserting : " + attributeName);
+ StringBuilder querySB = new StringBuilder();
+ if (isMeta) {
+ querySB.append(" (").append(MusicProperties.PRIMARY_ID).append(",").append(attributeName)
+ .append(") VALUES (?,?);");
+ } else {
+ querySB.append(" (").append(MusicProperties.PRIMARY_ID).append(",").append(MusicProperties.ATTRIBUTE_NAME)
+ .append(",").append(MusicProperties.ATTRIBUTE_BYTES).append(") VALUES (?,?,?);");
+ }
+ return querySB.toString();
+ }
+
+ /**
+ * Retrieve session attribute data from Cassandra via Music
+ *
+ * @param attributeName
+ * @param sessionId
+ * @return attribute value with T type
+ * @throws Exception
+ */
+ public static <T> T getAttribute(String attributeName, String sessionId) throws Exception {
+ logger.debug(EELFLoggerDelegate.debugLogger, "getAttribute: start with session id: " + sessionId);
+ ResultSet result = null;
+ String tableName = null;
+ boolean isMeta = MusicUtil.isSessionMetaAttr(attributeName);
+ PreparedQueryObject queryObject = new PreparedQueryObject();
+ StringBuilder querySB = new StringBuilder();
+ querySB.append("SELECT ").append(getColumn(attributeName, isMeta)).append(FROM).append(musicKeySpace)
+ .append(".").append(getTableName(isMeta)).append(WHERE).append(MusicProperties.PRIMARY_ID)
+ .append("= ?");
+
+ queryObject.addValue(sessionId);
+ if (!isMeta) {
+ querySB.append(" and ").append(MusicProperties.ATTRIBUTE_NAME).append("= ?");
+ queryObject.addValue(attributeName);
+ tableName = musicAttrTable;
+ } else
+ tableName = musicMetaTable;
+
+ queryObject.appendQueryString(querySB.toString());
+ if (isAtomicGet)
+ result = MusicCore.atomicGet(musicKeySpace, tableName, sessionId, queryObject);
+ else
+ result = modEventualGet(queryObject);
+ return MusicUtil.musicRestResponseDataParsing(result, attributeName);
+
+ }
+
+ /**
+ * Remove session attribute data from Cassandra via Music
+ *
+ * @param attributeName
+ * @param sessionId
+ * @return ReturnType
+ * @throws MusicServiceException
+ * @throws MusicLockingException
+ */
+ public static ReturnType removeAttribute(String attributeName, String sessionId) throws MusicLockingException {
+ logger.debug(EELFLoggerDelegate.debugLogger, "removeAttribute: start with session id: " + sessionId);
+ boolean isMeta = MusicUtil.isSessionMetaAttr(attributeName);
+ ReturnType result = null;
+ String tableName = null;
+ PreparedQueryObject queryObject = new PreparedQueryObject();
+ StringBuilder querySB = new StringBuilder();
+ querySB.append(DELETE).append(getDelColumn(isMeta, attributeName)).append(FROM).append(musicKeySpace)
+ .append(".").append(getTableName(isMeta)).append(WHERE).append(MusicProperties.PRIMARY_ID)
+ .append("= ? ");
+ queryObject.addValue(sessionId);
+
+ if (!isMeta) {
+ querySB.append(" and ").append(MusicProperties.ATTRIBUTE_NAME).append("= ?");
+ queryObject.addValue(attributeName);
+ tableName = musicAttrTable;
+ } else
+ tableName = musicMetaTable;
+ queryObject.appendQueryString(querySB.toString());
+ if (isAtomicPut)
+ result = MusicCore.atomicPut(musicKeySpace, tableName, sessionId, queryObject, null);
+ else
+ result = modEventualPut(queryObject);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ REMOVE_SESSION + attributeName + WITH_SESSION_ID + sessionId + RESULT + result.getMessage());
+
+ return result;
+ }
+
+ /**
+ * Remove entire session from Cassandra via Music
+ *
+ * @param sessionId
+ * @return ReturnType
+ * @throws MusicServiceException
+ * @throws MusicLockingException
+ */
+ public static ReturnType removeSession(String sessionId) throws MusicLockingException {
+ ReturnType result = null;
+ boolean isAtomic = isAtomicPut;
+ logger.debug(EELFLoggerDelegate.debugLogger, "removeSession: start with session id: " + sessionId);
+ PreparedQueryObject queryObject = new PreparedQueryObject();
+ StringBuilder querySB = new StringBuilder();
+ querySB.append(DELETE).append(FROM).append(musicKeySpace).append(".").append(musicMetaTable)
+ .append(WHERE).append(MusicProperties.PRIMARY_ID).append("= ? ");
+ queryObject.appendQueryString(querySB.toString());
+ queryObject.addValue(sessionId);
+ if (isAtomic)
+ result = MusicCore.atomicPut(musicKeySpace, musicMetaTable, sessionId, queryObject, null);
+ else
+ result = modEventualPut(queryObject);
+ logger.debug(EELFLoggerDelegate.debugLogger, REMOVE_SESSION + musicMetaTable + WITH_SESSION_ID
+ + sessionId + RESULT + result.getMessage());
+
+ queryObject = new PreparedQueryObject();
+ querySB = new StringBuilder();
+ querySB.append(DELETE).append(FROM).append(musicKeySpace).append(".").append(musicAttrTable)
+ .append(WHERE).append(MusicProperties.PRIMARY_ID).append("= ? ");
+ queryObject.appendQueryString(querySB.toString());
+ queryObject.addValue(sessionId);
+ if (isAtomic)
+ result = MusicCore.atomicPut(musicKeySpace, musicAttrTable, sessionId, queryObject, null);
+ else
+ result = modEventualPut(queryObject);
+
+ logger.debug(EELFLoggerDelegate.debugLogger, REMOVE_SESSION + musicAttrTable + WITH_SESSION_ID
+ + sessionId + RESULT + result.getMessage());
+
+ return result;
+ }
+
+ /**
+ * Get proper table name (Meta or Attribute) base on isMeta.
+ *
+ * @param isMeta
+ * @return String
+ */
+ private static String getTableName(boolean isMeta) {
+ StringBuilder querySB = new StringBuilder();
+ if (isMeta)
+ querySB.append(musicMetaTable);
+ else
+ querySB.append(musicAttrTable);
+ return querySB.toString();
+ }
+
+ /**
+ * Get proper column name (Meta or Attribute) base on isMeta.
+ *
+ * @param attributeName
+ * @param isMeta
+ * @return String
+ */
+ private static String getColumn(String attributeName, boolean isMeta) {
+ StringBuilder querySB = new StringBuilder();
+ if (isMeta)
+ querySB.append(attributeName);
+ else
+ querySB.append("attribute_bytes");
+ return querySB.toString();
+ }
+
+ /**
+ * Get proper column name (Meta or Attribute) base on isMeta for removing.
+ *
+ * @param attributeName
+ * @param isMeta
+ * @return String
+ */
+ private static String getDelColumn(boolean isMeta, String attributeName) {
+ StringBuilder querySB = new StringBuilder();
+ if (isMeta)
+ querySB.append(attributeName);
+ return querySB.toString();
+ }
+
+ /**
+ * To set session attributes in Music
+ *
+ * @param attributeName
+ * @param value
+ * @param session
+ * @param sessionId
+ * @param isMeta
+ * @return RestResponse<String>
+ * @throws JsonProcessingException
+ */
+
+ public static RestResponse<String> setAttributeAPI(String attributeName, Object value, Session session,
+ String sessionId, String className, boolean isMeta) throws JsonProcessingException {
+ logger.debug(EELFLoggerDelegate.debugLogger, "setAttribute: " + attributeName);
+ RestResponse<String> portalRestResponse = null;
+ HttpEntity<Map<String, Object>> entity = new HttpEntity<>(
+ getMusicRestBody(attributeName, value, sessionId, session, className, isMeta), getMusicHeader());
+ String url = getInsertUrl(isMeta);
+ ResponseEntity<String> response = null;
+ try {
+ response = template.exchange(url, HttpMethod.POST, entity, String.class);
+ portalRestResponse = new RestResponse<>(RestStatusEnum.OK, SUCCESS, response.getBody());
+ } catch (Exception e) {
+ logger.debug(EELFLoggerDelegate.debugLogger, e.getLocalizedMessage());
+ portalRestResponse = new RestResponse<>(RestStatusEnum.ERROR, e.getMessage(), null);
+ }
+ return portalRestResponse;
+ }
+
+ /**
+ * To get session attribute in Music
+ *
+ * @param attributeName
+ * @param value
+ * @param sessionId
+ * @param isMeta
+ * @return RestResponse<String>
+ */
+
+ public static RestResponse<String> getAttributeAPI(String attributeName, Object value, String sessionId,
+ boolean isMeta) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "setAttribute: " + attributeName);
+ RestResponse<String> portalRestResponse = null;
+ HttpEntity<String> entity = new HttpEntity<>(null, getMusicHeader());
+ ResponseEntity<String> response = null;
+ String url = getSelectSessionIdUrl(attributeName, sessionId, isMeta);
+ try {
+ response = template.exchange(url, HttpMethod.GET, entity, String.class);
+ portalRestResponse = new RestResponse<>(RestStatusEnum.OK, SUCCESS, response.getBody());
+ } catch (Exception e) {
+ logger.debug(EELFLoggerDelegate.debugLogger, e.getLocalizedMessage());
+ portalRestResponse = new RestResponse<>(RestStatusEnum.ERROR, e.getMessage(), null);
+ }
+ return portalRestResponse;
+ }
+
+ /**
+ * To remove session attribute or session meta in Music
+ *
+ * @param attributeName
+ * @param sessionId
+ * @param isMeta
+ * @return RestResponse<String>
+ */
+ public static RestResponse<String> removeAttributeAPI(String attributeName, String sessionId, boolean isMeta) {
+ RestResponse<String> portalRestResponse = null;
+ HttpEntity<Map<String, Object>> entity = new HttpEntity<>(getMusicDelRestBody(null), getMusicHeader());
+ ResponseEntity<String> response = null;
+ String url = getSelectSessionIdUrl(attributeName, sessionId, true);
+ try {
+ url = getSelectSessionIdUrl(attributeName, sessionId, false);
+ response = template.exchange(url, HttpMethod.DELETE, entity, String.class);
+ portalRestResponse = new RestResponse<>(RestStatusEnum.OK, SUCCESS, response.getBody());
+ } catch (Exception e) {
+ logger.debug(EELFLoggerDelegate.debugLogger, e.getLocalizedMessage());
+ portalRestResponse = new RestResponse<>(RestStatusEnum.ERROR, e.getMessage(), null);
+ }
+ return portalRestResponse;
+ }
+
+ /**
+ * Generate body for Music api calls
+ *
+ * @return String that includes required body information for Music api
+ * calls
+ * @throws JsonProcessingException
+ */
+ public static Map<String, Object> getMusicRestBody(String attributeName, Object value, String sessionId,
+ Session session, String className, boolean isMeta) throws JsonProcessingException {
+ Map<String, Object> map = new HashMap<>();
+ /* Set up column values */
+ Map<String, Object> valueMap = new HashMap<>();
+ if (isMeta) {
+ valueMap.put(MusicProperties.PRIMARY_ID, session.getId());
+ valueMap.put(MusicProperties.SESSION_ID, session.getId());
+ valueMap.put(MusicProperties.CREATION_TIME, session.getCreationTime().toString());
+ valueMap.put(MusicProperties.LAST_ACCESS_TIME, session.getLastAccessedTime().toString());
+ valueMap.put(MusicProperties.MAX_INACTIVE_INTERVAL, session.getMaxInactiveInterval().toString());
+ } else {
+ ObjectMapper mapper = new ObjectMapper();
+ valueMap.put(MusicProperties.PRIMARY_ID, sessionId);
+ valueMap.put(MusicProperties.ATTRIBUTE_NAME, attributeName);
+ valueMap.put(MusicProperties.ATTRIBUTE_BYTES, mapper.writeValueAsString(value));
+ valueMap.put(MusicProperties.ATTRIBUTE_CLASS, className);
+ }
+ map.put("values", valueMap);
+ /* Set up consistency setting */
+ Map<String, String> consistencyInfoMap = new HashMap<>();
+ consistencyInfoMap.put(MusicProperties.getProperty(MusicProperties.MUSIC_CONSISTENCYINFO),
+ MusicProperties.getProperty(MusicProperties.MUSIC_CONSISTENCYINFO_VALUE));
+ map.put("consistencyInfo", consistencyInfoMap);
+ return map;
+ }
+
+ /**
+ * Generate body for Music delete api calls
+ *
+ * @return String that includes required body information for Music api
+ * calls
+ * @throws JsonProcessingException
+ */
+ public static Map<String, Object> getMusicDelRestBody(String attributeName) {
+ Map<String, Object> map = new HashMap<>();
+ Map<String, String> consistencyInfoMap = new HashMap<>();
+ consistencyInfoMap.put(MusicProperties.getProperty(MusicProperties.MUSIC_CONSISTENCYINFO),
+ MusicProperties.getProperty(MusicProperties.MUSIC_CONSISTENCYINFO_VALUE));
+ if (attributeName != null && !attributeName.isEmpty()) {
+ Map<String, String> conditionsMap = new HashMap<>();
+ conditionsMap.put("attribute_name", attributeName);
+ map.put("conditions", conditionsMap);
+ }
+ map.put("consistencyInfo", consistencyInfoMap);
+ return map;
+ }
+
+ private static String getSelectSessionIdUrl(String attributeName, String sessionId, boolean isMeta) {
+ String path = constructPath(isMeta);
+ StringBuilder attriPath = new StringBuilder();
+ attriPath.append(path).append(MusicProperties.getProperty(MusicProperties.MUSIC_ROWS)).append("?")
+ .append(MusicProperties.PRIMARY_ID).append("=").append(sessionId);
+ return attriPath.toString();
+ }
+
+ private static String getInsertUrl(boolean isMeta) {
+ String path = constructPath(isMeta);
+ StringBuilder attriPath = new StringBuilder();
+ attriPath.append(path);
+ attriPath.append(MusicProperties.getProperty(MusicProperties.MUSIC_ROWS));
+ return attriPath.toString();
+ }
+
+ /**
+ * Generate header for Music api calls
+ *
+ * @return header that contains required header information for Music api
+ * calls
+ */
+ private static HttpHeaders getMusicHeader() {
+ HttpHeaders headers = new HttpHeaders();
+ headers.setContentType(MediaType.APPLICATION_JSON);
+ headers.add("X-minorVersion", MusicProperties.getProperty(MusicProperties.MUSIC_X_MINOR_VERSION));
+ headers.add("X-patchVersion", MusicProperties.getProperty(MusicProperties.MUSIC_X_PATCH_VERSION));
+ headers.add("ns", MusicProperties.getProperty(MusicProperties.MUSIC_NS));
+ headers.add("userId", MusicProperties.getProperty(MusicProperties.MUSIC_USER_ID));
+ headers.add("password", MusicProperties.getProperty(MusicProperties.MUSIC_PASSWORD));
+ return headers;
+ }
+
+ /**
+ * Construct URL for Music api calls
+ *
+ * @return path
+ */
+ private static String constructPath(boolean isMeta) {
+ StringBuilder path = new StringBuilder();
+ path.append(MusicProperties.getProperty(MusicProperties.MUSIC_ENDPOINT))
+ .append(MusicProperties.getProperty(MusicProperties.MUSIC_VERSION)).append("/")
+ .append(MusicProperties.getProperty(MusicProperties.MUSIC_KEYSPACE)).append("/").append(musicKeySpace)
+ .append("/").append(MusicProperties.getProperty(MusicProperties.MUSIC_TABLES)).append("/");
+ if (isMeta)
+ path.append(musicMetaTable);
+ else
+ path.append(musicAttrTable);
+ path.append("/");
+ return path.toString();
+ }
+
+ /**
+ * Get a list of sessions that need to be cleaned up
+ *
+ * @return List<String>
+ */
+ private static List<String> getSessionToBeDeleted(){
+ logger.debug(EELFLoggerDelegate.debugLogger, "initial getSessionToBeDeleted ...");
+
+ PreparedQueryObject queryObject = new PreparedQueryObject();
+ ResultSet result = null;
+ List<String> sessionIDList = new ArrayList<>();
+ DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
+ StringBuilder querySB = new StringBuilder();
+ String cleanUpThreshold = MusicProperties.getProperty(MusicProperties.MUSIC_CLEAN_UP_THRESHOLD); //Clean up sessions that's cleanUpThreshold hours ago
+ Date dateForCleanup = new Date(System.currentTimeMillis() - 3600 * 1000 * Integer.valueOf(cleanUpThreshold)); // Get the threshold date that needs to be clean up
+ String dateForCleanupCondition = dateFormat.format(dateForCleanup);
+ querySB.append("SELECT ").append(MusicProperties.PRIMARY_ID).append(FROM).append(musicKeySpace)
+ .append(".").append(getTableName(true)).append(WHERE).append(MusicProperties.LAST_ACCESS_TIME)
+ .append("< ? ").append(" ALLOW FILTERING");
+ queryObject.appendQueryString(querySB.toString());
+ queryObject.addValue(dateForCleanupCondition);
+
+ try{
+ if (isAtomicGet)
+ result = MusicCore.atomicGet(musicKeySpace, musicMetaTable, null, queryObject);
+ else
+ result = modEventualGet(queryObject);
+ Row row = result.one();
+ while(row!=null){
+ sessionIDList.add(row.get(MusicProperties.PRIMARY_ID, String.class));
+ row = result.one();
+ }
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "Error while cleaning up music tables" , e);
+ }
+ return sessionIDList;
+ }
+
+ /**
+ * Remove session data in music base on the defined frequency
+ *
+ * @return List<String>
+ */
+ public static void cleanUpMusic() {
+ boolean timeToCleanUp = MusicUtil.cleanUp(); // Decide whether to clean up or not
+
+ if(timeToCleanUp){
+ /**Getting a list of sessions that need to be cleaned up*/
+ List<String> sessionIDList = getSessionToBeDeleted();
+ if(sessionIDList!=null || !sessionIDList.isEmpty()){
+ StringBuilder sessionIDListCondition = new StringBuilder();
+ sessionIDListCondition.append("('");
+ for(String s : sessionIDList){
+ sessionIDListCondition.append(s);
+ sessionIDListCondition.append("','");
+ }
+ sessionIDListCondition.deleteCharAt(sessionIDListCondition.length()-1);
+ sessionIDListCondition.deleteCharAt(sessionIDListCondition.length()-1);
+ sessionIDListCondition.append(")");
+ StringBuilder querySB = new StringBuilder();
+ PreparedQueryObject queryObject = new PreparedQueryObject();
+ /**Deleting attributes table**/
+ querySB = new StringBuilder();
+ queryObject = new PreparedQueryObject();
+ querySB.append("DELETE FROM ").append(musicKeySpace)
+ .append(".").append(getTableName(false)).append(WHERE).append(MusicProperties.PRIMARY_ID)
+ .append(" in ").append(sessionIDListCondition);
+ queryObject.appendQueryString(querySB.toString());
+ try{
+ if (isAtomicPut)
+ MusicCore.atomicPut(musicKeySpace, null, null, queryObject, null);
+ else
+ modEventualPut(queryObject);
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "Error while cleaning up music attributes tables" , e);
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger, "Music sessions have been cleaned up !");
+
+ /**Deleting meta table**/
+ logger.debug(EELFLoggerDelegate.debugLogger, "Cleaning up meta table ...");
+ querySB = new StringBuilder();
+ queryObject = new PreparedQueryObject();
+ querySB.append("DELETE FROM ").append(musicKeySpace)
+ .append(".").append(getTableName(true)).append(WHERE).append(MusicProperties.PRIMARY_ID)
+ .append(" in ").append(sessionIDListCondition);
+ queryObject.appendQueryString(querySB.toString());
+ try{
+ if (isAtomicPut)
+ MusicCore.atomicPut(musicKeySpace, null, null, queryObject, null);
+ else
+ modEventualPut(queryObject);
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "Error while cleaning up music meta tables" , e);
+ }
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "Cleaned up attributes table ... ");
+ }else{
+ logger.debug(EELFLoggerDelegate.debugLogger, "No Session needs to be cleaned up");
+ }
+
+ }
+ }
+
+ public static ReturnType modEventualPut(PreparedQueryObject queryObject) {
+ boolean result = false;
+ try {
+ result = MusicCore.getDSHandle().executePut(queryObject,CRITICAL);
+ } catch (MusicServiceException | MusicQueryException ex) {
+ logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() + " " + ex.getCause() + " " + ex);
+ return new ReturnType(ResultType.FAILURE, ex.getMessage());
+ }
+ if (result) {
+ return new ReturnType(ResultType.SUCCESS, "Success");
+ } else {
+ return new ReturnType(ResultType.FAILURE, "Failure");
+ }
+ }
+
+ public static ResultSet modEventualGet(PreparedQueryObject queryObject) throws MusicServiceException {
+ ResultSet result;
+ result = MusicCore.quorumGet(queryObject);
+ return result;
+ }
+
+
+}
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
deleted file mode 100644
index e867deb1..00000000
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/util/MusicProperties.java
+++ /dev/null
@@ -1,225 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * ONAP Portal
- * ===================================================================
- * Copyright (C) 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;
- }
-
- /**
- * Tests whether a property value is available for the specified key.
- *
- * @param key
- * Property key
- * @return True if the key is known, otherwise false.
- */
-/* public static boolean containsProperty(String key) {
- return environment.containsProperty(key);
- }*/
-
- /**
- * Returns the property value associated with the given key (never
- * {@code null}), after trimming any trailing space.
- *
- * @param key
- * Property key
- * @return Property value; the empty string if the environment was not
- * autowired, which should never happen.
- * @throws IllegalStateException
- * if the key is not found
- */
-/* public static String getProperty(String key) {
- String value = "";
- if (environment == null) {
- // logger.error(EELFLoggerDelegate.errorLogger, "getProperty: environment is null, should never happen!");
- } else {
- value = environment.getRequiredProperty(key);
- // java.util.Properties preserves trailing space
- if (value != null)
- value = value.trim();
- }
- return value;
- }*/
-
-}
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
deleted file mode 100644
index 9667bfef..00000000
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/music/util/MusicUtil.java
+++ /dev/null
@@ -1,220 +0,0 @@
-/*
- * ============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) {
- String message="Failed to serialize ";
- logger.error(EELFLoggerDelegate.errorLogger, message, e);
- }
- 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/ExternalAppsRestfulController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulController.java
index 7615b660..5aea7f1c 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulController.java
@@ -50,8 +50,11 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.onap.portalapp.controller.EPRestrictedRESTfulBaseController;
+import org.onap.portalapp.music.conf.MusicSession;
+import org.onap.portalapp.music.util.MusicUtil;
import org.onap.portalapp.portal.domain.EPApp;
import org.onap.portalapp.portal.domain.EPRole;
+import org.onap.portalapp.portal.domain.EPServiceCookie;
import org.onap.portalapp.portal.domain.EPUser;
import org.onap.portalapp.portal.logging.aop.EPAuditLog;
import org.onap.portalapp.portal.service.AdminRolesService;
@@ -70,6 +73,8 @@ import org.onap.portalapp.validation.DataValidator;
import org.onap.portalapp.validation.SecureString;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse;
+import org.onap.portalsdk.core.onboarding.util.CipherUtil;
+import org.onap.portalsdk.core.util.SystemProperties;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
@@ -240,4 +245,30 @@ public class ExternalAppsRestfulController extends EPRestrictedRESTfulBaseContro
logger.warn(EELFLoggerDelegate.errorLogger, "Handling bad request", e);
response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());
}
+
+ @EPAuditLog
+ @RequestMapping(value = { "/validateCookie" }, method = RequestMethod.POST)
+ public boolean validateCookie(@RequestBody EPServiceCookie epServiceCookie, HttpServletRequest request) throws Exception {
+ Map<String,String> epServiceCookieValueMap = epServiceCookie.getValue();
+ if(epServiceCookieValueMap!=null) {
+ String multifactorauthfrontendurl = SystemProperties.getProperty("frontend_url");
+ String encryptedJSessionId = epServiceCookieValueMap.get(multifactorauthfrontendurl);
+ if(encryptedJSessionId != null) {
+ String jSessionId = CipherUtil.decryptPKC(encryptedJSessionId);
+ if(jSessionId != null) {
+ if(jSessionId.equals(request.getSession().getId())) {
+ if(MusicUtil.isMusicEnable()) {
+ MusicSession musicSession = new MusicSession();
+ String sessionId = musicSession.getAttribute(encryptedJSessionId);
+ logger.info(EELFLoggerDelegate.errorLogger, "Music sessionid : "+sessionId);
+ return (sessionId != null);
+ } else {
+ return true;
+ }
+ }
+ }
+ }
+ }
+ return false;
+ }
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/FunctionalMenuController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/FunctionalMenuController.java
index 97af4373..5e13127c 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/FunctionalMenuController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/FunctionalMenuController.java
@@ -49,6 +49,7 @@ import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.core.Response;
import org.json.JSONObject;
import org.onap.portalapp.controller.EPRestrictedBaseController;
@@ -74,6 +75,7 @@ import org.onap.portalapp.util.EPUserUtils;
import org.onap.portalapp.validation.DataValidator;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@@ -641,10 +643,18 @@ public class FunctionalMenuController extends EPRestrictedBaseController {
*/
@RequestMapping(value = {
"/portalApi/userApplicationRoles" }, method = RequestMethod.GET, produces = "application/json")
- public List<BusinessCardApplicationRolesList> getAppList(HttpServletRequest request,
+ public List<BusinessCardApplicationRolesList> getAppList(HttpServletRequest request, HttpServletResponse response,
@RequestParam("userId") String userId) throws IOException {
List<BusinessCardApplicationRolesList> AppRoles = null;
+
+ if(!UserUtils.getUserSession(request).getOrgUserId().equalsIgnoreCase(userId)) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Not authorized to view roles of others ");
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ response.getWriter().flush();
+ return null;
+ }
+
try {
List<BusinessCardApplicationRole> userAppRoleList = functionalMenuService.getUserAppRolesList(userId);
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 6818d505..ca66809f 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
@@ -192,16 +192,17 @@ public class HealthCheckController extends EPUnRestrictedBaseController {
}
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);
+ /*
+ * 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);
+ */
}
String json = "";
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppController.java
index 41273ecf..92449a3a 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppController.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppController.java
@@ -89,12 +89,12 @@ import org.springframework.web.client.AsyncRestTemplate;
@EPAuditLog
@NoArgsConstructor
public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseController {
+ public static final String FEED_ML = "feed.ml";
private WidgetMService widgetMService;
private AppsCacheService appCacheService;
private static final String MACHINE_LEARNING_SERVICE_CTX = "/ml_api";
private static final String REGISTER_ACTION = MACHINE_LEARNING_SERVICE_CTX + "/" + "registerAction";
- private static final String CONSUL_ML_SERVICE_ID = "machine-learning";
private static final String APP_KEY = "uebkey";
private static final String ERROR_MSG = " Error retrieving Application to capture app name for analytics; Proceeding with empty app name";
private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class);
@@ -102,7 +102,6 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl
private final SuccessCallback<ResponseEntity<String>> successCallback = arg -> logger.info(EELFLoggerDelegate.debugLogger, arg.getBody());
private final FailureCallback failureCallback = arg -> logger.error(EELFLoggerDelegate.errorLogger, "storeAuxAnalytics failed", arg);
-
@Autowired
public WebAnalyticsExtAppController(AppsCacheService appCacheService, WidgetMService consulHealthService) {
this.appCacheService = appCacheService;
@@ -170,19 +169,23 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl
try {
MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
String appName = "";
- try {
- appName = getAppName(request, appName);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
+ try {
+ appName = getAppName(request, appName);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
ERROR_MSG, e);
- }
+ }
- try {
- storeAuxAnalytics(analyticsMap, appName);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,
+ try {
+ if(SystemProperties.containsProperty(FEED_ML) &&
+ SystemProperties.getProperty(FEED_ML).equals("true")) {
+ storeAuxAnalytics(analyticsMap, appName);
+ }
+
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
ERROR_MSG, e);
- }
+ }
MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
@@ -218,7 +221,7 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl
private EPApp getApp(HttpServletRequest request) {
String appKeyValue = request.getHeader(APP_KEY);
EPApp appRecord = null;
- if (appKeyValue == null || "".equals(appKeyValue)) {
+ if (appKeyValue == null || appKeyValue.equals("")) {
logger.error(EELFLoggerDelegate.errorLogger, " App Key unavailable; Proceeding with null app name");
} else {
appRecord = appCacheService.getAppFromUeb(appKeyValue);
@@ -226,15 +229,16 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl
return appRecord;
}
- private void storeAuxAnalytics(Analytics analyticsMap, String appName) {
+ protected void storeAuxAnalytics(Analytics analyticsMap, String appName) {
logger.info(EELFLoggerDelegate.debugLogger,
" Registering an action for recommendation: AppName/Function/UserId " + appName + "/"
+ analyticsMap.getFunction() + "/" + analyticsMap.getUserid());
+
Map<String, String> requestMapping = new HashMap<>();
requestMapping.put("id", analyticsMap.getUserid());
requestMapping.put("action", appName + "|" + analyticsMap.getFunction());
-
+
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
@@ -243,12 +247,11 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl
// send it!
ListenableFuture<ResponseEntity<String>> out = restTemplate.exchange(
- EcompPortalUtils.widgetMsProtocol() + "://"
- + widgetMService.getServiceLocation(CONSUL_ML_SERVICE_ID,
- SystemProperties.getProperty("microservices.m-learn.local.port"))
+ EcompPortalUtils.widgetMLProtocol() + "://"
+ + widgetMService.getMLServiceLocation()
+ REGISTER_ACTION,
HttpMethod.POST, entity, String.class);
out.addCallback(successCallback, failureCallback);
}
-}
+} \ No newline at end of file
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPServiceCookie.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPServiceCookie.java
new file mode 100644
index 00000000..b4eb6fcc
--- /dev/null
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPServiceCookie.java
@@ -0,0 +1,54 @@
+/*-
+ * ============LICENSE_START==========================================
+ * ONAP Portal
+ * ===================================================================
+ * Copyright (C) 2017 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.portal.domain;
+
+import java.util.Map;
+
+
+public class EPServiceCookie {
+ Map<String, String> value;
+
+ public Map<String, String> getValue() {
+ return value;
+ }
+
+ public void setValue(Map<String, String> value) {
+ this.value = value;
+ }
+
+} \ No newline at end of file
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/exceptions/NoHealthyServiceException.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/exceptions/NoHealthyServiceException.java
index 2f78f807..3a4dc174 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/exceptions/NoHealthyServiceException.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/exceptions/NoHealthyServiceException.java
@@ -37,9 +37,9 @@
*/
package org.onap.portalapp.portal.exceptions;
-import com.ecwid.consul.ConsulException;
-public class NoHealthyServiceException extends ConsulException{
+
+public class NoHealthyServiceException extends Exception{
private static final long serialVersionUID = -7089437673127729813L;
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java
index 39c906a1..3209f35a 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java
@@ -42,6 +42,7 @@ package org.onap.portalapp.portal.interceptor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
+import java.util.HashMap;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
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 4805a77d..31a323e4 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
@@ -143,18 +143,18 @@ public class HealthMonitor {
}
if(org.onap.portalapp.music.util.MusicUtil.isMusicEnable()){
- zookeeperStatusOk = checkZookeeperStatus();
-
- if (!zookeeperStatusOk) {
- 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;
- }
- }
+ /*
+ * zookeeperStatusOk = checkZookeeperStatus();
+ *
+ * if (!zookeeperStatusOk) { 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 = checkCassandraStatus();
if (!cassandraStatusOk) {
@@ -257,6 +257,7 @@ public class HealthMonitor {
String state = zkNodeStatistics.substring(zkNodeStatistics.indexOf("Mode:"),
zkNodeStatistics.indexOf("Node"));
logger.info(EELFLoggerDelegate.applicationLogger,
+
"Getting Status for zookeeper :" + zookeeperNode.trim() + ":------:" + state);
if (state.contains("leader") || state.contains("follower")) {
return true;
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 14dfebee..93310a97 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,32 +37,34 @@
*/
package org.onap.portalapp.portal.scheduler;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonDeserializer;
import java.util.Collections;
import java.util.Date;
+
import javax.security.auth.login.CredentialException;
-import javax.ws.rs.client.Client;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.Response;
-import lombok.NoArgsConstructor;
+
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
+import org.apache.cxf.jaxrs.client.WebClient;
+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;
import org.onap.portalapp.portal.scheduler.restobjects.RestObject;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonDeserializer;
+
+import lombok.NoArgsConstructor;
+
@SuppressWarnings("MalformedFormatString")
@Service
@NoArgsConstructor
@@ -73,10 +75,10 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc {
+ " MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON";
private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class);
- private static Client client = null;
+ private static WebClient client = null;
private static Gson gson = null;
- private MultivaluedHashMap<String, Object> commonHeaders;
+ private MultivaluedHashMap<String, String> commonHeaders;
private static void init() {
logger.debug(EELFLoggerDelegate.debugLogger, "initializing");
@@ -89,7 +91,7 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc {
gson = builder.create();
}
- public void initRestClient() {
+ public void initRestClient(String URI) {
logger.debug(EELFLoggerDelegate.debugLogger, "Starting to initialize rest client");
init();
@@ -130,19 +132,28 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc {
commonHeaders = new MultivaluedHashMap<>();
commonHeaders.put("Authorization", Collections.singletonList(("Basic " + authStringEnc)));
- try {
- if (!username.isEmpty()) {
-
- client = HttpBasicClient.getClient();
- } else {
-
- client = HttpsBasicClient.getClient();
- }
- } catch (Exception e) {
- logger.debug(EELFLoggerDelegate.debugLogger, "Unable to initialize rest client",e.getMessage());
-
- }
+ // try {
+ // if (!username.isEmpty()) {
+ //
+ // client = HttpBasicClient.getClient();
+ // } else {
+ //
+ // client = HttpsBasicClient.getClient();
+ // }
+ // } catch (Exception e) {
+ // logger.debug(EELFLoggerDelegate.debugLogger, "Unable to initialize rest client",e.getMessage());
+ //
+ // }
+
+ client = WebClient.create(URI);
+ client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
+ //client.path("");
+ client.headers(commonHeaders);
+
logger.debug(EELFLoggerDelegate.debugLogger, "Client Initialized");
+
+
+
}
@@ -155,10 +166,13 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc {
logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR GET : ", url);
try {
- initRestClient();
-
- final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders).get();
+ initRestClient(url);
+
+
+ //final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders).get();
+ final ResponseImpl cres = (ResponseImpl)client.get();
+ logger.debug(EELFLoggerDelegate.debugLogger, "The implemenation class of Response : ", cres.getClass().getName());
int status = cres.getStatus();
restObject.setStatusCode(status);
@@ -211,11 +225,10 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc {
try {
- initRestClient();
+ initRestClient(url);
// Change the content length
- final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders)
- .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON));
+ final ResponseImpl cres = (ResponseImpl)client.post(requestDetails.toJSONString());
if (cres != null && cres.getEntity() != null) {
@@ -268,38 +281,5 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc {
throw new UnsupportedOperationException();
}
- @SuppressWarnings("unchecked")
- public <T> void Delete(T t, JSONObject requestDetails, String sourceID, String path, RestObject<T> restObject) {
-
- String methodName = "Delete";
- String url = "";
- Response cres;
-
- try {
- initRestClient();
-
- url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
-
- cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders)
- // .entity(r)
- .build("DELETE", Entity.entity(requestDetails, MediaType.APPLICATION_JSON)).invoke();
-
- int status = cres.getStatus();
- restObject.setStatusCode(status);
- if (cres.getEntity() != null) {
- t = (T) cres.readEntity(t.getClass());
- restObject.set(t);
- }
-
- } catch (HttpClientErrorException e) {
- logger.error(EELFLoggerDelegate.errorLogger, " HttpClientErrorException:Exception For the Delete",
- methodName, url, e);
- EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Exception For the Delete", methodName, url, e);
- EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
- throw e;
- }
- }
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterfaceIfc.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterfaceIfc.java
index 8d37a125..77ebe6a0 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterfaceIfc.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterfaceIfc.java
@@ -45,13 +45,10 @@ import org.springframework.stereotype.Service;
@Service
public interface SchedulerRestInterfaceIfc {
- void initRestClient();
+ void initRestClient(String URI);
<T> void Get(T t, String sourceId, String path, org.onap.portalapp.portal.scheduler.restobjects.RestObject<T> restObject ) throws Exception;
- <T> void Delete(T t, JSONObject requestDetails, String sourceID, String path, RestObject<T> restObject)
- throws Exception;
-
<T> void Post(T t, JSONObject r, String path, RestObject<T> restObject) throws Exception;
void logRequest(JSONObject requestDetails);
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpBasicClient.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpBasicClient.java
index 17dc3f1e..b2fff55f 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpBasicClient.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpBasicClient.java
@@ -42,10 +42,11 @@ package org.onap.portalapp.portal.scheduler.client;
import javax.servlet.ServletContext;
+import javax.ws.rs.RuntimeType;
import javax.ws.rs.client.Client;
-import javax.ws.rs.client.ClientBuilder;
-import org.glassfish.jersey.client.ClientConfig;
+import org.apache.cxf.jaxrs.client.spec.ClientBuilderImpl;
+import org.apache.cxf.jaxrs.impl.ConfigurationImpl;
import org.glassfish.jersey.client.ClientProperties;
import org.onap.portalapp.portal.scheduler.util.CustomJacksonJaxBJsonProvider;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
@@ -71,10 +72,14 @@ public class HttpBasicClient{
*/
public static Client getClient() throws Exception {
- ClientConfig config = new ClientConfig();
- config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
+ //ClientConfig config = new ClientConfig();
+
+ ConfigurationImpl config = new ConfigurationImpl(RuntimeType.CLIENT);
+ config.setProperty(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
+ ClientBuilderImpl impl = new ClientBuilderImpl();
- return ClientBuilder.newClient(config)
+ Class.forName(org.apache.cxf.jaxrs.impl.ResponseImpl.class.getName());
+ return impl.withConfig(config).build()
.register(CustomJacksonJaxBJsonProvider.class);
}
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java
index 9784356c..4e83b921 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java
@@ -2893,7 +2893,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic
roleFunction = dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId",
appFuncsParams, null);
}
- if (!roleFunction.isEmpty()) {
+ if (!roleFunction.isEmpty() && roleId != null) {
EPAppRoleFunction apRoleFunction = new EPAppRoleFunction();
apRoleFunction.setAppId(app.getId());
apRoleFunction.setRoleId(roleId);
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java
index bfc232aa..ab688820 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java
@@ -1084,7 +1084,7 @@ public class UserRolesCommonServiceImpl {
applyChangesToUserAppRolesForMyLoginsRequest(user, appId);
- boolean systemUser = newAppRolesForUser.isSystemUser();
+ Boolean systemUser = (newAppRolesForUser.getIsSystemUser() != null ? newAppRolesForUser.getIsSystemUser() : false);
if ((app.getCentralAuth() || app.getId().equals(PortalConstants.PORTAL_APP_ID)) && systemUser) {
@@ -2303,10 +2303,15 @@ public class UserRolesCommonServiceImpl {
EPApp app = appsService.getApp(appId);
//If local or centralized application
if (appId == PortalConstants.PORTAL_APP_ID || app.getCentralAuth()) {
+ Map<String, Object> params = new HashMap<>();
+ params.put("id", app.getId());
+ params.put("active", true);
@SuppressWarnings("unchecked")
- List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null);
+ //List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null);
+ //List<Object[]> userList = (List<Object[]>) dataAccessService.executeNamedQuery("getActiveUsersForApp", params, null);
+ List<EPUser> userList = (List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsersForApp", params, null);
for (EPUser user : userList) {
- UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(appId, user, app);
+ UserApplicationRoles userWithAppRoles = convertToUserApplicationRoles(user, app.getId());
if (userWithAppRoles.getRoles() != null && userWithAppRoles.getRoles().size() > 0)
userApplicationRoles.add(userWithAppRoles);
}
@@ -2336,6 +2341,29 @@ public class UserRolesCommonServiceImpl {
/**
*
+ * @param user
+ * @param app_id
+ * @return
+ */
+ private UserApplicationRoles convertToUserApplicationRoles(EPUser user, Long appId) {
+ UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
+ userWithRemoteAppRoles.setAppId(appId);
+ userWithRemoteAppRoles.setOrgUserId(user.getOrgUserId());
+ userWithRemoteAppRoles.setFirstName(user.getFirstName());
+ userWithRemoteAppRoles.setLastName(user.getLastName());
+ List<RemoteRole> roleList = new ArrayList<RemoteRole>();
+ for(EPUserApp userApp :user.getEPUserApps()) {
+ RemoteRole remoteRole = new RemoteRole();
+ remoteRole.setName(userApp.getRole().getName());
+ remoteRole.setId(userApp.getRole().getId());
+ roleList.add(remoteRole);
+ }
+ userWithRemoteAppRoles.setRoles(roleList);
+ return userWithRemoteAppRoles;
+ }
+
+ /**
+ *
* @param appId
* @param user
* @param appgetUsersFromAppEndpoint
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/WidgetMService.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/WidgetMService.java
index dd03d06d..1c53a0c3 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/WidgetMService.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/WidgetMService.java
@@ -37,17 +37,12 @@
*/
package org.onap.portalapp.portal.service;
-import java.util.List;
-
import org.onap.portalapp.portal.exceptions.NoHealthyServiceException;
-import com.ecwid.consul.ConsulException;
-import com.orbitz.consul.model.health.ServiceHealth;
-
public interface WidgetMService {
/**
- * This method returns the location of one healthy node if found in Consul -
- * If not found in / by Consul, it falls back to 'localhost'
+ * This method returns the location of Widget MS -
+ *
*
* @param service
* @param fallbackPortOnLocalhost
@@ -56,4 +51,13 @@ public interface WidgetMService {
*/
public String getServiceLocation(String service, String fallbackPortOnLocalhost) throws NoHealthyServiceException;
+
+ /**
+ * This method returns the location of Machine learning -
+ *
+ *
+ * @return Service location
+ */
+ public String getMLServiceLocation();
+
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/WidgetMServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/WidgetMServiceImpl.java
index 21f1648d..29180d5e 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/WidgetMServiceImpl.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/WidgetMServiceImpl.java
@@ -39,6 +39,7 @@ package org.onap.portalapp.portal.service;
import org.onap.portalapp.portal.utils.EcompPortalUtils;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.util.SystemProperties;
import org.springframework.stereotype.Component;
@Component
@@ -53,5 +54,13 @@ public class WidgetMServiceImpl implements WidgetMService {
logger.debug(logger.debugLogger, "returned service location: "+ localFallbackServiceLocation);
return localFallbackServiceLocation;
}
+
+ @Override
+ public String getMLServiceLocation() {
+ logger.debug(logger.debugLogger, "Requested Service: ML");
+ String localFallbackServiceLocation = EcompPortalUtils.mlLocalOrDockerHost() + ":" + SystemProperties.getProperty("microservices.ml.port");
+ logger.debug(logger.debugLogger, "returned service location: "+ localFallbackServiceLocation);
+ return localFallbackServiceLocation;
+ }
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java
index cbfe1787..3d7363e2 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/AppWithRolesForUser.java
@@ -53,9 +53,8 @@ import lombok.ToString;
@ToString
public class AppWithRolesForUser {
private String orgUserId;
- private boolean isSystemUser;
+ private Boolean isSystemUser;
private Long appId;
private String appName;
private List<RoleInAppForUser> appRoles;
-
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/FunctionalMenuItem.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/FunctionalMenuItem.java
index 14ad2f4c..a2148c2f 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/FunctionalMenuItem.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/FunctionalMenuItem.java
@@ -73,7 +73,7 @@ public class FunctionalMenuItem implements Serializable {
public Integer column;
@Column(name = "TEXT")
- @Max(value = 100)
+ //@Max(value = 100)
@SafeHtml
@NotNull
public String text;
@@ -83,13 +83,13 @@ public class FunctionalMenuItem implements Serializable {
public Integer parentMenuId;
@Column(name = "URL")
- @Max(value = 128)
+ //@Max(value = 128)
@SafeHtml
@NotNull
public String url;
@Column(name="ACTIVE_YN")
- @Max(value = 1)
+ //@Max(value = 1)
@SafeHtml
@NotNull
public String active_yn;
@@ -134,4 +134,5 @@ public class FunctionalMenuItem implements Serializable {
public void setRestrictedApp(Boolean restrictedApp) {
this.restrictedApp = restrictedApp;
}
+
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EPCommonSystemProperties.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EPCommonSystemProperties.java
index e253bfcf..981a2ac6 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EPCommonSystemProperties.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EPCommonSystemProperties.java
@@ -90,6 +90,9 @@ public class EPCommonSystemProperties extends SystemProperties {
public static final String WIDGET_MS_PROTOCOL = "microservices.widget.protocol";
public static final String WIDGET_MS_HOSTNAME = "microservices.widget.hostname";
+ public static final String WIDGET_ML_PROTOCOL = "microservices.ml.protocol";
+ public static final String WIDGET_ML_HOSTNAME = "microservices.ml.hostname";
+ public static final String WIDGET_ML_PORT = "microservices.ml.port";
public static final String REMOTE_CENTRALIZED_SYSTEM_ACCESS = "remote_centralized_system_access";
public static final String APP_DISPLAY_PASSWORD = "*******";
@@ -102,4 +105,7 @@ public class EPCommonSystemProperties extends SystemProperties {
public static final String PASSWORD = "password";
public static final String PORTAL_LEFT_MENU = "portal_left_menu";
+ public static final String EPSERVICE_COOKIE_SECURE = "epsservice.cookie.secure";
+ public static final String MULTI_FACTOR_AUTH_FRONTEND_URL = "frontend_url";
+
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java
index 30eeac04..7c9aa76b 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java
@@ -376,6 +376,15 @@ public class EcompPortalUtils {
public static String widgetMsProtocol() {
return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_PROTOCOL, "https");
}
+
+ /**
+ * Answers the protocol to use.
+ *
+ * @return Protocol name from property file; defaults to https.
+ */
+ public static String widgetMLProtocol() {
+ return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_ML_PROTOCOL, "https");
+ }
/**
* Answers the host to use.
@@ -385,6 +394,15 @@ public class EcompPortalUtils {
public static String localOrDockerHost() {
return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_MS_HOSTNAME, "localhost");
}
+
+ /**
+ * Answers the host to use.
+ *
+ * @return Host name from property file; defaults to localhost.
+ */
+ public static String mlLocalOrDockerHost() {
+ return getPropertyOrDefault(EPCommonSystemProperties.WIDGET_ML_HOSTNAME, "localhost");
+ }
/**
* It returns headers where username and password of external central auth is
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/MusicCookieCsrfTokenRepository.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/MusicCookieCsrfTokenRepository.java
index 988b97a5..891f6d78 100644
--- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/MusicCookieCsrfTokenRepository.java
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/MusicCookieCsrfTokenRepository.java
@@ -50,6 +50,20 @@ import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.DefaultCsrfToken;
import org.springframework.util.StringUtils;
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
+import org.onap.portalsdk.core.onboarding.util.CipherUtil;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.util.HashMap;
+import java.util.Map;
+import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
+
public final class MusicCookieCsrfTokenRepository implements CsrfTokenRepository {
static final String CSRF_COOKIE_NAME = "XSRF-TOKEN";
@@ -111,12 +125,22 @@ public final class MusicCookieCsrfTokenRepository implements CsrfTokenRepository
return new MusicCookieCsrfTokenRepository(result);
}
- private String getSessionIdFromCookie (HttpServletRequest request){
+ private String getSessionIdFromCookie (HttpServletRequest request) throws JsonParseException, JsonMappingException, UnsupportedEncodingException, IOException, CipherUtilException{
Cookie cookies[] = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (EP_SERVICE.equals(cookie.getName())) {
- return cookie.getValue();
+ ObjectMapper mapper = new ObjectMapper();
+ Map<String,String> epServiceCookieValueMap = mapper.readValue(URLDecoder.decode(cookie.getValue(), "UTF-8"),HashMap.class);
+ String sessionId = null;
+ if(epServiceCookieValueMap!=null) {
+ String multifactorauthfrontendurl = EPCommonSystemProperties.getProperty(EPCommonSystemProperties.MULTI_FACTOR_AUTH_FRONTEND_URL);
+ String encryptedJSessionId = epServiceCookieValueMap.get(multifactorauthfrontendurl);
+ if(encryptedJSessionId != null) {
+ sessionId = CipherUtil.decryptPKC(encryptedJSessionId);
+ }
+ }
+ return sessionId;
}
}
}
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/CommonSessionCookieUtil.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/CommonSessionCookieUtil.java
new file mode 100644
index 00000000..e0b712a2
--- /dev/null
+++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/CommonSessionCookieUtil.java
@@ -0,0 +1,151 @@
+/*-
+ * ============LICENSE_START==========================================
+ * ONAP Portal
+ * ===================================================================
+ * Copyright (c) 2019 Samsung. 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.util;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
+import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
+import org.onap.portalsdk.core.onboarding.util.CipherUtil;
+import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
+import org.onap.portalsdk.core.web.support.AppUtils;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+public class CommonSessionCookieUtil {
+
+ public static final String EP_SERVICE = "EPService";
+ public static Integer cookieMaxAge = -1;
+ public static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CommonSessionCookieUtil.class);
+ public static boolean EP_SERVICE_SECURE = false;
+
+ public static void setUpEPServiceCookie(HttpServletRequest request, HttpServletResponse response) throws CipherUtilException, JsonParseException, JsonMappingException, IOException {
+ //set up EPService cookie
+ EP_SERVICE_SECURE = Boolean.parseBoolean(EPCommonSystemProperties.getProperty(EPCommonSystemProperties.EPSERVICE_COOKIE_SECURE));
+ String multifactorauthfrontendurl = EPCommonSystemProperties.getProperty(EPCommonSystemProperties.MULTI_FACTOR_AUTH_FRONTEND_URL);
+ String domainName = EPCommonSystemProperties.getProperty(EPCommonSystemProperties.COOKIE_DOMAIN);
+ Cookie epCookie = getCookie(request, EP_SERVICE);
+ ObjectMapper objectMapper = new ObjectMapper();
+ if(epCookie != null) {
+ //If cookie already exist then add the current env and jsessionId to this
+ String jSessionId = getJessionId(request);
+ String jsonValue = URLDecoder.decode(epCookie.getValue(),"UTF-8");
+ Map<String,String> valueMap = null;
+ // if the value is encoded
+ if(jsonValue.startsWith("{")) {
+ valueMap = objectMapper.readValue(jsonValue, HashMap.class);
+ }else {
+ valueMap = new HashMap<>();
+ }
+ valueMap.put(multifactorauthfrontendurl, CipherUtil.encryptPKC(jSessionId));
+ saveOrUpdateEPServiceCookie(response, domainName, objectMapper, valueMap);
+ }else {
+ //If cookie does not exist create a cookie with current env and jsessionId
+ String jSessionId = getJessionId(request);
+ Map<String,String> valueMap = new HashMap<>();
+ valueMap.put(multifactorauthfrontendurl, CipherUtil.encryptPKC(jSessionId));
+ saveOrUpdateEPServiceCookie(response, domainName, objectMapper, valueMap);
+ }
+ }
+
+ private static void saveOrUpdateEPServiceCookie(HttpServletResponse response, String domainName,
+ ObjectMapper objectMapper, Map<String, String> valueMap)
+ throws UnsupportedEncodingException, JsonProcessingException {
+ Cookie cookie1 = new Cookie(EP_SERVICE, URLEncoder.encode(objectMapper.writeValueAsString(valueMap), "UTF-8"));
+ cookie1.setMaxAge(cookieMaxAge);
+ cookie1.setDomain(domainName);
+ cookie1.setPath("/");
+ cookie1.setSecure(EP_SERVICE_SECURE);
+ response.addCookie(cookie1);
+ }
+
+ //Get cookie from request object on the basis of cookie name
+ private static Cookie getCookie(HttpServletRequest request, String cookieName) {
+ Cookie[] cookies = request.getCookies();
+ if (cookies != null)
+ for (Cookie cookie : cookies)
+ if (cookie.getName().equals(cookieName))
+ return cookie;
+
+ return null;
+ }
+
+ protected static void initateSessionMgtHandler(HttpServletRequest request) {
+ String jSessionId = getJessionId(request);
+ storeMaxInactiveTime(request);
+ PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request));
+ }
+
+ protected static void storeMaxInactiveTime(HttpServletRequest request) {
+ HttpSession session = AppUtils.getSession(request);
+ if(session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME) == null)
+ session.setAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME,session.getMaxInactiveInterval());
+ }
+
+ public static void resetSessionMaxIdleTimeOut(HttpServletRequest request) {
+ try {
+ HttpSession session = AppUtils.getSession(request);
+ final Object maxIdleAttribute = session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME);
+ if(session != null && maxIdleAttribute != null) {
+ session.setMaxInactiveInterval(Integer.parseInt(maxIdleAttribute.toString()));
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "resetSessionMaxIdleTimeOut failed", e);
+ }
+
+ }
+
+ public static String getJessionId(HttpServletRequest request){
+ return request.getSession().getId();
+ }
+} \ No newline at end of file