From b54df0ddd0c6a0372327c5aa3668e5a6458fcd64 Mon Sep 17 00:00:00 2001 From: st782s Date: Thu, 4 May 2017 07:48:42 -0400 Subject: [PORTAL-7] Rebase This rebasing includes common libraries and common overlays projects abstraction of components Change-Id: I9a24a338665c7cd058978e8636bc412d9e2fdce8 Signed-off-by: st782s --- .../portalapp/authentication/LoginStrategy.java | 27 + .../authentication/OpenIdConnectLoginStrategy.java | 107 +++ .../authentication/SimpleLoginStrategy.java | 114 ++++ .../portalapp/conf/ExternalAppConfig.java | 316 +++++++++ .../portalapp/conf/ExternalAppInitializer.java | 60 ++ .../portalapp/conf/HibernateMappingLocations.java | 43 ++ .../controller/ECOMPLogoutController.java | 114 ++++ .../portalapp/controller/LoginController.java | 397 +++++++++++ .../portalapp/controller/LoginService.java | 36 + .../portalapp/controller/ONAPLoginController.java | 81 +++ .../controller/ONAPWelcomeController.java | 84 +++ .../controller/OpenCollaborationController.java | 23 + .../portalapp/controller/PeerBroadcastSocket.java | 106 +++ .../portal/controller/AppsOSController.java | 116 ++++ .../DashboardSearchResultController.java | 243 +++++++ .../controller/ExternalAppsRestfulController.java | 129 ++++ .../portal/controller/PortalAdminController.java | 117 ++++ .../interceptor/SessionTimeoutInterceptor.java | 101 +++ .../portal/logging/aop/EPEELFLoggerAspect.java | 204 ++++++ .../service/ApplicationsRestClientService.java | 28 + .../service/ApplicationsRestClientServiceImpl.java | 267 ++++++++ .../portalapp/portal/service/AppsCacheService.java | 40 ++ .../portal/service/AppsCacheServiceImple.java | 104 +++ .../portalapp/portal/service/EPAppServiceImpl.java | 71 ++ .../portalapp/portal/service/SearchService.java | 40 ++ .../portal/service/SearchServiceImpl.java | 192 ++++++ .../portalapp/portal/service/UserRolesService.java | 58 ++ .../portal/service/UserRolesServiceImpl.java | 726 +++++++++++++++++++++ .../portalapp/portal/service/UserService.java | 34 + .../portalapp/portal/service/UserServiceImpl.java | 260 ++++++++ .../portalapp/portal/transport/OnboardingApp.java | 83 +++ .../portalapp/portal/ueb/EPUebHelper.java | 218 +++++++ .../portalapp/portal/ueb/EPUebMsgTypes.java | 27 + .../portalapp/portal/utils/EPSystemProperties.java | 42 ++ .../org/openecomp/portalapp/scheduler/LogJob.java | 45 ++ .../openecomp/portalapp/scheduler/LogRegistry.java | 57 ++ .../openecomp/portalapp/scheduler/Register.java | 86 +++ .../portalapp/scheduler/RegistryAdapter.java | 100 +++ .../portalapp/scheduler/SessionMgtRegistry.java | 89 +++ .../service/RemoteWebServiceCallServiceImpl.java | 104 +++ .../uebhandler/FunctionalMenuHandler.java | 126 ++++ .../portalapp/uebhandler/InitUebHandler.java | 75 +++ .../portalapp/uebhandler/MainUebHandler.java | 115 ++++ .../uebhandler/WidgetNotificationHandler.java | 93 +++ ecomp-portal-BE-os/src/main/resources/cache.ccf | 30 + ecomp-portal-BE-os/src/main/resources/logback.xml | 285 ++++++++ .../src/main/resources/openid-connect.properties | 22 + .../src/main/resources/openid-keystore.jwks | 12 + .../src/main/resources/portal.properties | 44 ++ .../src/main/webapp/META-INF/MANIFEST.MF | 3 + .../src/main/webapp/WEB-INF/conf/cache.ccf | 30 + .../src/main/webapp/WEB-INF/conf/quartz.properties | 55 ++ .../src/main/webapp/WEB-INF/conf/raptor.properties | 185 ++++++ .../WEB-INF/conf/raptor_app_fusion.properties | 36 + .../WEB-INF/conf/raptor_db_fusion.properties | 19 + .../main/webapp/WEB-INF/conf/raptor_pdf.properties | 49 ++ .../src/main/webapp/WEB-INF/conf/sql.properties | 295 +++++++++ .../src/main/webapp/WEB-INF/conf/system.properties | 118 ++++ .../src/main/webapp/WEB-INF/defs/definitions.xml | 38 ++ .../webapp/WEB-INF/fusion/conf/fusion.properties | 83 +++ .../webapp/WEB-INF/fusion/defs/definitions.xml | 120 ++++ .../src/main/webapp/WEB-INF/jsp/error.jsp | 20 + .../src/main/webapp/WEB-INF/jsp/index.jsp | 21 + .../src/main/webapp/WEB-INF/jsp/login.jsp | 166 +++++ .../src/main/webapp/WEB-INF/jsp/oid-admin.jsp | 72 ++ .../src/main/webapp/WEB-INF/jsp/oid-home.jsp | 102 +++ .../src/main/webapp/WEB-INF/jsp/oid-login.jsp | 76 +++ .../src/main/webapp/WEB-INF/jsp/oid-user.jsp | 139 ++++ .../src/main/webapp/WEB-INF/jsp/welcome.jsp | 695 ++++++++++++++++++++ .../src/main/webapp/WEB-INF/oid-context.xml | 455 +++++++++++++ .../src/main/webapp/WEB-INF/tags/copyright.tag | 1 + .../src/main/webapp/WEB-INF/tags/footer.tag | 12 + .../src/main/webapp/WEB-INF/tags/header.tag | 59 ++ .../src/main/webapp/WEB-INF/tags/topbar.tag | 96 +++ ecomp-portal-BE-os/src/main/webapp/WEB-INF/web.xml | 87 +++ .../src/main/webapp/images/cache/README.txt | 1 + ecomp-portal-BE-os/src/main/webapp/index.jsp | 41 ++ .../portal/controller/SharedContextRestClient.java | 280 ++++++++ .../SharedContextRestControllerTest.java | 125 ++++ .../controller/SharedContextTestProperties.java | 81 +++ .../controller/shared-context-test.properties | 28 + .../portal/listener/HealthMonitorTest.java | 36 + .../portal/utils/EcompPortalUtilsTest.java | 33 + 83 files changed, 9548 insertions(+) create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/LoginStrategy.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/OpenIdConnectLoginStrategy.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/SimpleLoginStrategy.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ECOMPLogoutController.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/LoginController.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/LoginService.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ONAPLoginController.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ONAPWelcomeController.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/OpenCollaborationController.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/PeerBroadcastSocket.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/AppsOSController.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/DashboardSearchResultController.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/interceptor/SessionTimeoutInterceptor.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAspect.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientService.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientServiceImpl.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheService.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheServiceImple.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/EPAppServiceImpl.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/SearchService.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/SearchServiceImpl.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserRolesService.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserRolesServiceImpl.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserService.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserServiceImpl.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebMsgTypes.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/utils/EPSystemProperties.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/LogJob.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/LogRegistry.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/Register.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/RegistryAdapter.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/SessionMgtRegistry.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/service/RemoteWebServiceCallServiceImpl.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/FunctionalMenuHandler.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/InitUebHandler.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/MainUebHandler.java create mode 100644 ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/WidgetNotificationHandler.java create mode 100644 ecomp-portal-BE-os/src/main/resources/cache.ccf create mode 100644 ecomp-portal-BE-os/src/main/resources/logback.xml create mode 100644 ecomp-portal-BE-os/src/main/resources/openid-connect.properties create mode 100644 ecomp-portal-BE-os/src/main/resources/openid-keystore.jwks create mode 100644 ecomp-portal-BE-os/src/main/resources/portal.properties create mode 100644 ecomp-portal-BE-os/src/main/webapp/META-INF/MANIFEST.MF create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/cache.ccf create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/quartz.properties create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/raptor.properties create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/raptor_app_fusion.properties create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/raptor_db_fusion.properties create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/raptor_pdf.properties create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/sql.properties create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/system.properties create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/defs/definitions.xml create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/fusion/conf/fusion.properties create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/fusion/defs/definitions.xml create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/error.jsp create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/index.jsp create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/login.jsp create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/oid-admin.jsp create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/oid-home.jsp create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/oid-login.jsp create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/oid-user.jsp create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/welcome.jsp create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/oid-context.xml create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/tags/copyright.tag create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/tags/footer.tag create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/tags/header.tag create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/tags/topbar.tag create mode 100644 ecomp-portal-BE-os/src/main/webapp/WEB-INF/web.xml create mode 100644 ecomp-portal-BE-os/src/main/webapp/images/cache/README.txt create mode 100644 ecomp-portal-BE-os/src/main/webapp/index.jsp create mode 100644 ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/controller/SharedContextRestClient.java create mode 100644 ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/controller/SharedContextRestControllerTest.java create mode 100644 ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/controller/SharedContextTestProperties.java create mode 100644 ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/controller/shared-context-test.properties create mode 100644 ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/listener/HealthMonitorTest.java create mode 100644 ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/utils/EcompPortalUtilsTest.java (limited to 'ecomp-portal-BE-os/src') diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/LoginStrategy.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/LoginStrategy.java new file mode 100644 index 00000000..19637515 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/LoginStrategy.java @@ -0,0 +1,27 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.authentication; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public interface LoginStrategy { + public boolean login(HttpServletRequest request, HttpServletResponse response) throws Exception; +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/OpenIdConnectLoginStrategy.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/OpenIdConnectLoginStrategy.java new file mode 100644 index 00000000..8365ebc2 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/OpenIdConnectLoginStrategy.java @@ -0,0 +1,107 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.authentication; + +import java.util.HashSet; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.mitre.openid.connect.model.UserInfo; +import org.openecomp.portalapp.command.EPLoginBean; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalapp.util.SessionCookieUtil; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.util.StringUtils; +import org.springframework.web.servlet.ModelAndView; + +public class OpenIdConnectLoginStrategy extends org.openecomp.portalsdk.core.auth.LoginStrategy implements org.openecomp.portalapp.authentication.LoginStrategy { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(OpenIdConnectLoginStrategy.class); + + private static final String GLOBAL_LOCATION_KEY = "Location"; + + @SuppressWarnings("rawtypes") + public boolean login(HttpServletRequest request, HttpServletResponse response){ + + logger.info("Attempting Login"); + + //check both authentication cookie and authentication header + UserInfo userInfo = (UserInfo) request.getAttribute("userInfo"); + + if (userInfo != null && !StringUtils.isEmpty(userInfo.getPreferredUsername())) { + //package the userid in the login form for processing + EPLoginBean commandBean = new EPLoginBean(); + commandBean.setOrgUserId(userInfo.getPreferredUsername()); + + EPUser user = new EPUser(); + + user.setOrgUserId(userInfo.getPreferredUsername()); + user.setEmail(userInfo.getEmail()); + user.setFirstName(userInfo.getName()); + user.setLastName(userInfo.getFamilyName()); + + //store the currently logged in user's information in the session + EPUserUtils.setUserSession(request, user, new HashSet(), new HashSet(), SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM), null); + + logger.info(EELFLoggerDelegate.errorLogger, request.getContextPath()); + SessionCookieUtil.preSetUp(request, response); + return true; + } else { + // in case authentication cookie is missing, send 401 UNAUTHORIZED to client and it will redirect to Logon + + try { + String authentication = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM); + String loginUrl = SystemProperties.getProperty(EPSystemProperties.LOGIN_URL_NO_RET_VAL); + logger.info(EELFLoggerDelegate.errorLogger, "Authentication Mechanism: '" + authentication + "'."); + + if (authentication == null || authentication.equals("") || authentication.trim().equals("OIDC")) { + response.sendRedirect("oid-login"); + } else { + logger.info(EELFLoggerDelegate.errorLogger, "No cookies are found, redirecting the request to '" + loginUrl + "'."); + response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); + response.setHeader(GLOBAL_LOCATION_KEY, loginUrl); + } + } catch(Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in preHandle() while redirecting, Details: " + EcompPortalUtils.getStackTrace(e)); + } + } + return false; + } + + @Override + public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { + String message = "Method not implmented; Cannot be called"; + logger.error(EELFLoggerDelegate.errorLogger, message); + throw new Exception(message); + } + + @Override + public String getUserId(HttpServletRequest request) throws PortalAPIException { + String message = "Method not implmented; Cannot be called"; + logger.error(EELFLoggerDelegate.errorLogger, message); + throw new PortalAPIException(message); + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/SimpleLoginStrategy.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/SimpleLoginStrategy.java new file mode 100644 index 00000000..c1fee7f3 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/SimpleLoginStrategy.java @@ -0,0 +1,114 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.authentication; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.command.EPLoginBean; +import org.openecomp.portalapp.portal.service.EPLoginService; +import org.openecomp.portalapp.portal.service.EPRoleService; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalapp.util.SessionCookieUtil; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.menu.MenuProperties; +import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException; +import org.openecomp.portalsdk.core.onboarding.util.*; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.StringUtils; +import org.springframework.web.servlet.ModelAndView; + +public class SimpleLoginStrategy extends org.openecomp.portalsdk.core.auth.LoginStrategy implements LoginStrategy{ + + @Autowired + private EPLoginService loginService; + @Autowired + private EPRoleService roleService; + + private static final String GLOBAL_LOCATION_KEY = "Location"; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SimpleLoginStrategy.class); + + public boolean login(HttpServletRequest request, HttpServletResponse response) throws Exception{ + logger.info("Attempting 'Simple' Login"); + + //check both authentication cookie and authentication header + String orgUserId = SessionCookieUtil.getUserIdFromCookie(request, response); + + if (!StringUtils.isEmpty(orgUserId)) { + // package the userid in the login form for processing + EPLoginBean commandBean = new EPLoginBean(); + commandBean.setOrgUserId(orgUserId); + commandBean = loginService.findUser(commandBean, (String)request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), null); + + // in case authentication has passed but user is not in the ECOMP data base, return a Guest User to the home page. + if (commandBean.getUser() == null) { + } + else { + // store the currently logged in user's information in the session + EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), "", roleService.getRoleFunctions()); + logger.info(EELFLoggerDelegate.debugLogger, commandBean.getUser().getOrgUserId() + " exists in the the system."); + } + + logger.info(EELFLoggerDelegate.errorLogger, request.getContextPath()); + SessionCookieUtil.preSetUp(request, response); + return true; + } else { + // in case authentication cookie is missing, send 401 UNAUTHORIZED to client and it will redirect to Logon + try { + String authentication = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM); + String loginUrl = SystemProperties.getProperty(EPSystemProperties.LOGIN_URL_NO_RET_VAL); + logger.info(EELFLoggerDelegate.errorLogger, "Authentication Mechanism: '" + authentication + "'."); + if (authentication == null || authentication.equals("") || authentication.trim().equals("BOTH")) { + + logger.info(EELFLoggerDelegate.errorLogger, "No cookies are found, redirecting the request to '" + loginUrl + "'."); + response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); + response.setHeader(GLOBAL_LOCATION_KEY, loginUrl); //returnUrl + "/index.htm"); + }else { + logger.info(EELFLoggerDelegate.errorLogger, "No cookies are found, redirecting the request to '" + loginUrl + "'."); + response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); + response.setHeader(GLOBAL_LOCATION_KEY, loginUrl); //returnUrl + "/index.htm"); + } + } catch(Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in preHandle() while redirecting, Details: " + EcompPortalUtils.getStackTrace(e)); + } + } + + return false; + + } + + @Override + public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { + String message = "Method not implmented; Cannot be called"; + logger.error(EELFLoggerDelegate.errorLogger, message); + throw new Exception(message); + } + + @Override + public String getUserId(HttpServletRequest request) throws PortalAPIException { + String message = "Method not implmented; Cannot be called"; + logger.error(EELFLoggerDelegate.errorLogger, message); + throw new PortalAPIException(message); + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java new file mode 100644 index 00000000..971c671a --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java @@ -0,0 +1,316 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.conf; + +import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY; +import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID; +import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN; +import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS; +import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID; +import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME; + +import java.net.InetAddress; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + +import javax.annotation.PostConstruct; + +import org.openecomp.portalapp.authentication.LoginStrategy; +import org.openecomp.portalapp.authentication.OpenIdConnectLoginStrategy; +import org.openecomp.portalapp.authentication.SimpleLoginStrategy; +import org.openecomp.portalapp.controller.core.LogoutController; +import org.openecomp.portalapp.controller.core.SDKLoginController; +import org.openecomp.portalapp.portal.interceptor.PortalResourceInterceptor; +import org.openecomp.portalapp.portal.interceptor.SessionTimeoutInterceptor; +import org.openecomp.portalapp.portal.listener.HealthMonitor; +import org.openecomp.portalapp.portal.service.EPLoginService; +import org.openecomp.portalapp.portal.service.EPLoginServiceImpl; +import org.openecomp.portalapp.portal.ueb.EPUebHelper; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.scheduler.RegistryAdapter; +import org.openecomp.portalapp.uebhandler.FunctionalMenuHandler; +import org.openecomp.portalapp.uebhandler.InitUebHandler; +import org.openecomp.portalapp.uebhandler.MainUebHandler; +import org.openecomp.portalapp.uebhandler.WidgetNotificationHandler; +import org.openecomp.portalsdk.core.conf.AppConfig; +import org.openecomp.portalsdk.core.conf.Configurable; +import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.service.FnMenuService; +import org.openecomp.portalsdk.core.service.FnMenuServiceImpl; +import org.openecomp.portalsdk.core.util.CacheManager; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.ComponentScan.Filter; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.FilterType; +import org.springframework.context.annotation.Profile; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.quartz.SchedulerFactoryBean; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "org.openecomp" }, excludeFilters = { + @Filter(value = { LogoutController.class, SDKLoginController.class }, type = FilterType.ASSIGNABLE_TYPE) }) +@Profile("src") +@EnableAsync +@EnableScheduling +public class ExternalAppConfig extends AppConfig implements Configurable { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppConfig.class); + + private RegistryAdapter schedulerRegistryAdapter; + + public ViewResolver viewResolver() { + return super.viewResolver(); + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/static/**").addResourceLocations("/static/"); + registry.addResourceHandler("/images/**").addResourceLocations("/images/"); + registry.addResourceHandler("/**").addResourceLocations("/public/"); + } + + @PostConstruct + private void init() { + try { + // Loading defaults + MDC.put(MDC_SERVICE_NAME, EPSystemProperties.ECOMP_PORTAL_BE); + MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName()); + MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress()); + MDC.put(MDC_SERVICE_INSTANCE_ID, ""); + MDC.put(MDC_ALERT_SEVERITY, AlarmSeverityEnum.INFORMATIONAL.toString()); + MDC.put(MDC_INSTANCE_UUID, SystemProperties.getProperty(SystemProperties.INSTANCE_UUID)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } + } + + /* + * / + * + * @PostConstruct // file://${catalina.home}/conf/log4j.properties public + * void initLog4j() throws FileNotFoundException { try { URL[] classpathurls + * = ((URLClassLoader) + * (Thread.currentThread().getContextClassLoader())).getURLs(); for (URL url + * : classpathurls) { System.out.println(url.getFile().toString()); } + * Log4jConfigurer.initLogging( + * "file://${catalina.home}/conf/log4j.properties"); } catch + * (FileNotFoundException e) { ((URLClassLoader) + * (Thread.currentThread().getContextClassLoader())).getURLs(); + * Log4jConfigurer.initLogging("classpath:../conf/log4j.properties"); } } / + **/ + + public DataAccessService dataAccessService() { + return super.dataAccessService(); + } + + public String[] tileDefinitions() { + return super.tileDefinitions(); + } + + public List addTileDefinitions() { + List definitions = new ArrayList(); + definitions.add("/WEB-INF/defs/definitions.xml"); + return definitions; + } + + @Bean + public AbstractCacheManager cacheManager() { + return new CacheManager(); + } + + @Bean + public SessionTimeoutInterceptor sessionTimeoutInterceptor() { + return new SessionTimeoutInterceptor(); + } + + @Bean + public PortalResourceInterceptor portalResourceInterceptor() { + return new PortalResourceInterceptor(); + } + + @Bean + public EPLoginService eploginService() { + return new EPLoginServiceImpl(); + } + + @Bean + public org.openecomp.portalsdk.core.auth.LoginStrategy coreLoginStrategy() { + if (SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC")) + return new OpenIdConnectLoginStrategy(); + else + return new SimpleLoginStrategy(); + } + + @Bean + public LoginStrategy loginStrategy() { + + if (SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC")) + return new OpenIdConnectLoginStrategy(); + else + return new SimpleLoginStrategy(); + } + + public FnMenuService fnMenuService() { + return new FnMenuServiceImpl(); + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + // registry.addInterceptor(new + // StaticResourcesInterceptor()).addPathPatterns("/index.htm", + // "/applicationsHome", "/widgetsHome", "/admins", "/users", + // "/applications", "/widgets"); + // Excludes login/logout pages and REST endpoints used by other + // application servers. + + registry.addInterceptor(sessionTimeoutInterceptor()).excludePathPatterns("/oid-login", "/portalApi/healthCheck", + "/portalApi/healthCheck/", "/portalApi/healthCheckSuspend", "/portalApi/healthCheckSuspend/", + "/portalApi/healthCheckResume", "/portalApi/healthCheckResume/", "/login_external", + "/login_external.htm*", "login", "/login.htm*", "/auxapi/*", "/context/*", "/api*", + "/single_signon.htm", "/single_signon", "/dashboard", "/OpenSourceLogin.htm"); + + registry.addInterceptor(portalResourceInterceptor()); + + } + + /** + * Creates and returns a new instance of a {@link SchedulerFactoryBean} and + * populates it with triggers. + * + * @return New instance of {@link SchedulerFactoryBean} + */ + + @Bean + public EPUebHelper epUebHelper() { + return new EPUebHelper(); + } + + @Bean + public HealthMonitor healthMonitor() { + return new HealthMonitor(); + } + + /** + * Creates and returns a new instance of a {@link MainUebHandler}. + * + * @return New instance of {@link MainUebHandler}. + */ + @Bean + public MainUebHandler mainUebHandler() { + return new MainUebHandler(); + } + + /** + * Creates and returns a new instance of a {@link InitUebHandler}. + * + * @return New instance of {@link InitUebHandler}. + */ + @Bean + public InitUebHandler initUebHandler() { + return new InitUebHandler(); + } + + /** + * Creates and returns a new instance of a {@link WidgetNotificationHandler} + * . + * + * @return New instance of {@link WidgetNotificationHandler}. + */ + @Bean + public WidgetNotificationHandler widgetNotificationHandler() { + return new WidgetNotificationHandler(); + } + + /** + * Creates and returns a new instance of a {@link FunctionalMenuHandler} . + * + * @return New instance of {@link FunctionalMenuHandler}. + */ + @Bean + public FunctionalMenuHandler functionalMenuHandler() { + return new FunctionalMenuHandler(); + } + + /** + * Creates and returns a new instance of a {@link SchedulerFactoryBean} and + * populates it with triggers. + * + * @return New instance of {@link SchedulerFactoryBean} + * @throws Exception if dataSource fails + */ + // APPLICATIONS REQUIRING QUARTZ SHOULD RESTORE ANNOTATION + @Bean // ANNOTATION COMMENTED OUT + public SchedulerFactoryBean schedulerFactoryBean() throws Exception { + SchedulerFactoryBean scheduler = new SchedulerFactoryBean(); + scheduler.setConfigLocation(appApplicationContext.getResource("WEB-INF/conf/quartz.properties")); + scheduler.setDataSource(dataSource()); + scheduler.setTriggers(schedulerRegistryAdapter.getTriggers()); + scheduler.setSchedulerName(getScheduleName()); + return scheduler; + } + + protected String getScheduleName() { + final String CRON_SITE_NAME = "cron_site_name"; + String cronSiteVal = "Default"; + try { + cronSiteVal = SystemProperties.getProperty(CRON_SITE_NAME); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + logger.warn(EELFLoggerDelegate.errorLogger, + "Cron site name not added in property file, using Default value"); + } + + String cronSiteName = cronSiteVal != null ? cronSiteVal : ""; + + SimpleDateFormat dateFormat = new SimpleDateFormat(); + dateFormat.applyPattern("YYYYMMdd"); + String currentDateStr = dateFormat.format(Calendar.getInstance().getTime()); + + return "Scheduler" + "_" + currentDateStr + "_" + cronSiteName; + } + + /** + * Sets the scheduler registry adapter. + * + * @param schedulerRegistryAdapter + * Scheduler registry adapter + */ + @Autowired + public void setSchedulerRegistryAdapter(final RegistryAdapter schedulerRegistryAdapter) { + this.schedulerRegistryAdapter = schedulerRegistryAdapter; + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java new file mode 100644 index 00000000..1c9f43df --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java @@ -0,0 +1,60 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.conf; + +import java.util.Arrays; + +import org.openecomp.portalsdk.core.conf.AppInitializer; + +public class ExternalAppInitializer extends AppInitializer{ + + + @Override + protected Class[] getRootConfigClasses() { + return super.getRootConfigClasses(); + } + + @Override + protected Class[] getServletConfigClasses() { +// Class[] configClasses = super.getServletConfigClasses(); +// Class[] additionalConfigClasses = Arrays.copyOf(configClasses, configClasses.length); +// addConfigClass(additionalConfigClasses, ExternalAppConfig.class); +// return additionalConfigClasses; +// + return new Class[] {ExternalAppConfig.class}; + } + + static Class[] addConfigClass(Class[] a, Class e) { + a = Arrays.copyOf(a, a.length + 1); + a[a.length - 1] = e; + return a; + } + + /* + * URL request will direct to the Spring dispatcher for processing + */ + @Override + protected String[] getServletMappings() { + return super.getServletMappings(); + } + +} + + diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java new file mode 100644 index 00000000..0ebf4e38 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java @@ -0,0 +1,43 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.conf; + +import org.openecomp.portalsdk.core.conf.HibernateMappingLocatable; +import org.springframework.context.annotation.Profile; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.stereotype.Component; + +@Component +@Profile("src") +public class HibernateMappingLocations implements HibernateMappingLocatable { + + public Resource[] getMappingLocations() { + return new Resource[] { new ClassPathResource("../fusion/orm/Fusion.hbm.xml"), + new ClassPathResource("../fusion/orm/EP.hbm.xml"), + new ClassPathResource("../fusion/orm/Workflow.hbm.xml") }; + } + + @Override + public String[] getPackagesToScan() { + return new String[] { "org.openecomp" }; + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ECOMPLogoutController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ECOMPLogoutController.java new file mode 100644 index 00000000..b4e3bee9 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ECOMPLogoutController.java @@ -0,0 +1,114 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.controller; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.servlet.ModelAndView; + +@Controller +@RequestMapping("/") +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@Profile("src") +public class ECOMPLogoutController extends EPUnRestrictedBaseController{ + + private EPUser user; + private static final String EP_SERVICE = "EPService"; + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ECOMPLogoutController.class); + + @EPAuditLog + @RequestMapping(value = {"/logout.htm" }, method = RequestMethod.GET) + public ModelAndView logOut(HttpServletRequest request, + HttpServletResponse response) throws Exception { + + ModelAndView modelView = null; + + chatRoomLogout(request); + logger.debug(EELFLoggerDelegate.debugLogger, "ECOMPLogoutController.handleRequestInternal - Logout request received."); + + modelView = new ModelAndView("redirect:login.htm"); + + /** + if (UserUtils.isClientMobileDevice(request)){ + modelView.setViewName(modelView.getViewName().concat("?viewType=mobile")); + } + */ + String cookieDoamin = EPSystemProperties.getProperty(EPSystemProperties.COOKIE_DOMAIN); + Cookie epCookie = new Cookie(EP_SERVICE, ""); + epCookie.setMaxAge(0); + epCookie.setDomain(cookieDoamin); + epCookie.setPath("/"); + + Cookie appHeaderCookie = new Cookie("show_app_header", ""); + appHeaderCookie.setMaxAge(0); + appHeaderCookie.setDomain(cookieDoamin); + appHeaderCookie.setPath("/"); + + Cookie appTabCookie = new Cookie("cookieTabs", ""); + appTabCookie.setMaxAge(0); + appTabCookie.setDomain(cookieDoamin); + appTabCookie.setPath("/"); + + Cookie appVisInvisTabCookie = new Cookie("visInVisCookieTabs", ""); + appVisInvisTabCookie.setMaxAge(0); + appVisInvisTabCookie.setDomain(cookieDoamin); + appVisInvisTabCookie.setPath("/"); + + response.addCookie(epCookie); + response.addCookie(appHeaderCookie); + response.addCookie(appTabCookie); + response.addCookie(appVisInvisTabCookie); + request.getSession().invalidate(); + + logger.debug(EELFLoggerDelegate.debugLogger, "ECOMPLogoutController.handleRequestInternal - Successfully processed the logout request."); + + return modelView; + } + + @EPMetricsLog + public void chatRoomLogout(HttpServletRequest request){ + request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest(); + setUser(EPUserUtils.getUserSession(request)); + } + + public EPUser getUser() { + return user; + } + + public void setUser(EPUser user) { + this.user = user; + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/LoginController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/LoginController.java new file mode 100644 index 00000000..09e10e38 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/LoginController.java @@ -0,0 +1,397 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.controller; + +import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; + +import java.net.URLDecoder; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.portalapp.command.EPLoginBean; +import org.openecomp.portalapp.portal.domain.SharedContext; +import org.openecomp.portalapp.portal.service.EPLoginService; +import org.openecomp.portalapp.portal.service.EPRoleService; +import org.openecomp.portalapp.portal.service.SharedContextService; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.service.EPProfileService; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalapp.util.SessionCookieUtil; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.menu.MenuProperties; +import org.openecomp.portalsdk.core.onboarding.listener.PortalTimeoutHandler; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.AppUtils; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.util.StopWatch; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.util.WebUtils; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping("/") +public class LoginController extends EPUnRestrictedBaseController implements LoginService{ + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginController.class); + + public static final String DEFAULT_SUCCESS_VIEW = "applicationsHome"; + public static final String DEFAULT_FAILURE_VIEW = "login"; + public static final String ERROR_MESSAGE_KEY = "error"; + public static final String REDIRECT_URL = "redirectUrl"; + + @Autowired + EPProfileService service; + @Autowired + private EPLoginService loginService; + @Autowired + private SharedContextService sharedContextService; + + @Autowired + private EPRoleService roleService; + + String viewName = "login"; + private String welcomeView; + + public String getWelcomeView() { + return welcomeView; + } + + public void setWelcomeView(String welcomeView) { + this.welcomeView = welcomeView; + } + + @RequestMapping(value = {"/login.htm" }, method = RequestMethod.GET) + public ModelAndView login(HttpServletRequest request) { + Map model = new HashMap(); + + String authentication = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM); + + String loginPage; + + if (authentication == null || authentication.equals("") || authentication.trim().equals("OIDC")) + loginPage = "openIdLogin"; + else + loginPage = getViewName(); + + return new ModelAndView(loginPage,"model", model); + } + + @SuppressWarnings("rawtypes") + @RequestMapping(value = {"/open_source/login" }, method = RequestMethod.POST) + public @ResponseBody String loginValidate(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + + EPLoginBean commandBean = new EPLoginBean(); + String loginId = root.get("loginId").textValue(); + String password = root.get("password").textValue(); + commandBean.setLoginId(loginId); + commandBean.setLoginPwd(CipherUtil.encrypt(password)); + HashMap additionalParamsMap = new HashMap(); + StringBuilder sbAdditionalInfo = new StringBuilder(); + + commandBean = getLoginService().findUser(commandBean, (String)request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), + additionalParamsMap); + String fullURL = getFullURL(request); + if (commandBean.getUser() == null) { + String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) ? commandBean.getLoginErrorMessage() + : "login.error.external.invalid"; + + logger.info(EELFLoggerDelegate.debugLogger, "loginId = " + loginId + " does not exist in the the DB."); + logger.info(EELFLoggerDelegate.errorLogger, "loginId = " + loginId + " does not exist in the the DB."); + sbAdditionalInfo.append(String.format("But the Login-Id: %s doesn't exist in the Database. Request-URL: %s", + loginId, fullURL)); + return loginErrorMessage; + } + else { + // store the currently logged in user's information in the session + EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM), + roleService.getRoleFunctions()); + + try{ + logger.info(EELFLoggerDelegate.debugLogger, "******************* store user info into share context begins"); + String sessionId = request.getSession().getId(); + List existingSC = getSharedContextService().getSharedContexts(sessionId); + if(existingSC==null || existingSC.size()==0){ + getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_FIRST_NAME, commandBean.getUser().getFirstName()); + getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_LAST_NAME, commandBean.getUser().getLastName()); + getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_EMAIL, commandBean.getUser().getEmail()); + getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_ORG_USERID, commandBean.getLoginId()); + } + + }catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + logger.info(EELFLoggerDelegate.errorLogger, "failed the shared context adding process " + e.getMessage()); + logger.info(EELFLoggerDelegate.debugLogger, "********************** failed the shared context adding process " + e.getMessage()); + } + logger.info(EELFLoggerDelegate.debugLogger, "********************* PresetUp the EP service cookie and intial sessionManagement"); + + SessionCookieUtil.preSetUp(request, response); + SessionCookieUtil.setUpUserIdCookie(request, response, loginId); + + JSONObject j = new JSONObject("{success: success}"); + + return j.toString(); + + } + + } + + @RequestMapping(value = {"/processSingleSignOn" }, method = RequestMethod.GET) + public ModelAndView processSingelSignOn(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + Map model = new HashMap(); + HashMap additionalParamsMap = new HashMap(); + EPLoginBean commandBean = new EPLoginBean(); + MDC.put(MDC_KEY_REQUEST_ID, getRequestId(request)); + String orgUserId = ""; + //get userId from cookie + orgUserId = SessionCookieUtil.getUserIdFromCookie(request, response); + logger.info(EELFLoggerDelegate.debugLogger, "******************** process_singelSignOn process begins"); + logger.info(EELFLoggerDelegate.debugLogger, "******************* We get the orgUserId " + orgUserId); + + StringBuilder sbAdditionalInfo = new StringBuilder(); + if ((orgUserId == null || orgUserId.length() == 0)) { + model.put(ERROR_MESSAGE_KEY, SystemProperties.MESSAGE_KEY_LOGIN_ERROR_COOKIE_EMPTY); + if(request.getParameter("redirectUrl")!=null && request.getParameter("redirectUrl").length()!=0){ + return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm" + "?redirectUrl=" + request.getParameter("redirectUrl")); + }else{ + return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm"); + } + } + else { + + StopWatch stopWatch = new StopWatch("LoginController.Login"); + stopWatch.start(); + + try { + logger.info(EELFLoggerDelegate.metricsLogger, "Operation findUser is started to locate " + orgUserId + " in the database."); + logger.info(EELFLoggerDelegate.debugLogger, "Operation findUser is started to locate " + orgUserId + " in the database."); + commandBean.setLoginId(orgUserId); + commandBean.setOrgUserId(orgUserId); + commandBean = getLoginService().findUser(commandBean, (String)request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), additionalParamsMap); + + stopWatch.stop(); + MDC.put(EPSystemProperties.MDC_TIMER, stopWatch.getTotalTimeMillis() + "ms"); + logger.info(EELFLoggerDelegate.metricsLogger, "Operation findUser is completed."); + logger.info(EELFLoggerDelegate.debugLogger, "Operation findUser is completed."); + } catch(Exception e) { + stopWatch.stop(); + MDC.put(EPSystemProperties.MDC_TIMER, stopWatch.getTotalTimeMillis() + "ms"); + logger.info(EELFLoggerDelegate.errorLogger, "Exception occurred while performing findUser " + orgUserId + ". Details: " + EcompPortalUtils.getStackTrace(e)); + logger.info(EELFLoggerDelegate.debugLogger, "Exception occurred while performing findUser " + orgUserId + ". Details: " + EcompPortalUtils.getStackTrace(e)); + logger.info(EELFLoggerDelegate.metricsLogger, "Operation findUser is failed."); + } finally { + MDC.remove(EPSystemProperties.MDC_TIMER); + } + + sbAdditionalInfo.append("Login attempt is succeeded. "); + String fullURL = getFullURL(request); + if (commandBean.getUser() == null) { + logger.info(EELFLoggerDelegate.debugLogger, "loginId = " + orgUserId + " does not exist in the the DB."); + logger.info(EELFLoggerDelegate.errorLogger, "loginId = " + orgUserId + " does not exist in the the DB."); + logger.info(EELFLoggerDelegate.debugLogger, "loginId = " + orgUserId + " does not exist in the the DB."); + + sbAdditionalInfo.append(String.format("But the Login-Id: %s doesn't exist in the Database. Created a Guest Session. Request-URL: %s", + orgUserId, fullURL)); + if(request.getParameter("redirectUrl")!=null && request.getParameter("redirectUrl").length()!=0){ + return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm" + "?redirectUrl=" + request.getParameter("redirectUrl")); + }else{ + return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm"); + } + } + else { + + sbAdditionalInfo.append(String.format("Login-Id: %s, Login-Method: %s, Request-URL: %s", orgUserId, "", fullURL)); + logger.info(EELFLoggerDelegate.debugLogger, "*********************** now set up user session for " + orgUserId); + + EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM), roleService.getRoleFunctions()); + logger.info(EELFLoggerDelegate.debugLogger, "*********************** now set up user session for " + orgUserId + " finished"); + + //Store user's information into share context + try{ + logger.info(EELFLoggerDelegate.debugLogger, "******************* store user info into share context begins"); + + String sessionId = request.getSession().getId(); + List existingSC = getSharedContextService().getSharedContexts(sessionId); + if(existingSC==null || existingSC.size()==0){ + getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_FIRST_NAME, commandBean.getUser().getFirstName()); + getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_LAST_NAME, commandBean.getUser().getLastName()); + getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_EMAIL, commandBean.getUser().getEmail()); + getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_ORG_USERID, commandBean.getLoginId()); + } + + }catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + logger.info(EELFLoggerDelegate.errorLogger, "failed the shared context adding process " + e.getMessage()); + logger.info(EELFLoggerDelegate.debugLogger, "********************** failed the shared context adding process " + e.getMessage()); + + } + + logger.info(EELFLoggerDelegate.debugLogger, "********************* PresetUp the EP service cookie and intial sessionManagement"); + + SessionCookieUtil.preSetUp(request, response); + SessionCookieUtil.setUpUserIdCookie(request, response, orgUserId); + logger.info(EELFLoggerDelegate.debugLogger, "********************* PresetUp the EP service cookie and intial sessionManagement completed"); + logger.info(EELFLoggerDelegate.errorLogger, commandBean.getUser().getOrgUserId() + " exists in the the system."); + logger.info(EELFLoggerDelegate.debugLogger, commandBean.getUser().getOrgUserId() + " exists in the the system."); + + String redirect = "redirectUrl"; + + //get redirectUrl from URL parameter + if(request.getParameter(redirect)!=null && request.getParameter(redirect).length()!=0){ + String forwardUrl = URLDecoder.decode(request.getParameter(redirect),"UTF-8"); + //clean cookie + Cookie cookie2 = new Cookie(redirect, ""); + cookie2.setMaxAge(0); + cookie2.setDomain(EPSystemProperties.getProperty(EPSystemProperties.COOKIE_DOMAIN)); + cookie2.setPath("/"); + response.addCookie(cookie2); + return new ModelAndView("redirect:" + forwardUrl); + } + + //first check if redirectUrl exists or not + if(WebUtils.getCookie(request, redirect)!=null){ + String forwardUrl = WebUtils.getCookie(request, redirect).getValue(); + //clean cookie + Cookie cookie2 = new Cookie(redirect, ""); + cookie2.setMaxAge(0); + cookie2.setDomain(EPSystemProperties.getProperty(EPSystemProperties.COOKIE_DOMAIN)); + cookie2.setPath("/"); + response.addCookie(cookie2); + + return new ModelAndView("redirect:" + forwardUrl); + } + } + } + + // if user has been authenticated, now take them to the welcome page. + //return new ModelAndView("redirect:" + DEFAULT_SUCCESS_VIEW + ".htm"); + logger.info(EELFLoggerDelegate.debugLogger, "********************** Now return to application home page"); + + return new ModelAndView("redirect:" + SystemProperties.getProperty(EPSystemProperties.FE_URL)); + + // + // Re-enable for BE/FE separation. For 1607, at last minute we decided to go out + // without BE/FE separation. + // + //return new ModelAndView("redirect:" + SystemProperties.getProperty(EPSystemProperties.FE_URL)); + + } + + public String getFullURL(HttpServletRequest request) { + if (request != null) { + StringBuffer requestURL = request.getRequestURL(); + String queryString = request.getQueryString(); + + if (queryString == null) { + return requestURL.toString(); + } else { + return requestURL.append('?').append(queryString).toString(); + } + } + return ""; + } + + public String getRequestId(HttpServletRequest request) { + Enumeration headerNames = request.getHeaderNames(); + + String requestId = ""; + try { + while (headerNames.hasMoreElements()) { + String headerName = (String) headerNames.nextElement(); + logger.debug(EELFLoggerDelegate.debugLogger, + "One header is " + headerName + " : " + request.getHeader(headerName)); + if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) { + requestId = request.getHeader(headerName); + break; + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "HEADER!!!! Exception : " + EcompPortalUtils.getStackTrace(e)); + } + + return (requestId.isEmpty() ? UUID.randomUUID().toString() : requestId); + } + + public String getJessionId(HttpServletRequest request){ + + return request.getSession().getId(); + /* + Cookie ep = WebUtils.getCookie(request, JSESSIONID); + if(ep==null){ + return request.getSession().getId(); + } + return ep.getValue(); + */ + } + + + protected void initateSessionMgtHandler(HttpServletRequest request) { + String jSessionId = getJessionId(request); + PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request)); + } + + + public String getViewName() { + return viewName; + } + public void setViewName(String viewName) { + this.viewName = viewName; + } + public EPLoginService getLoginService() { + return loginService; + } + + public void setLoginService(EPLoginService loginService) { + this.loginService = loginService; + } + + public SharedContextService getSharedContextService() { + return sharedContextService; + } + + public void setSharedContextService(SharedContextService sharedContextService) { + this.sharedContextService = sharedContextService; + } + + + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/LoginService.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/LoginService.java new file mode 100644 index 00000000..7d2e4518 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/LoginService.java @@ -0,0 +1,36 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.ModelAndView; + +public interface LoginService { + + public ModelAndView login(HttpServletRequest request); + + public @ResponseBody String loginValidate(HttpServletRequest request, HttpServletResponse response) throws Exception; + + public ModelAndView processSingelSignOn(HttpServletRequest request, HttpServletResponse response) throws Exception; + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ONAPLoginController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ONAPLoginController.java new file mode 100644 index 00000000..1f45d982 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ONAPLoginController.java @@ -0,0 +1,81 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.controller; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalsdk.core.auth.LoginStrategy; +import org.openecomp.portalsdk.core.controller.UnRestrictedBaseController; +import org.openecomp.portalsdk.core.onboarding.listener.PortalTimeoutHandler; +import org.openecomp.portalsdk.core.service.LoginService; +import org.openecomp.portalsdk.core.service.ProfileService; +import org.openecomp.portalsdk.core.web.support.AppUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +@Controller +@RequestMapping("/") +public class ONAPLoginController extends UnRestrictedBaseController { + @Autowired + ProfileService service; + @Autowired + private LoginService loginService; + @Autowired + private LoginStrategy loginStrategy; + String viewName; + + @RequestMapping(value = { "/doLogin" }, method = RequestMethod.GET) + public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { + return loginStrategy.doLogin(request, response); + } + + public String getJessionId(HttpServletRequest request) { + return request.getSession().getId(); + } + + protected void initateSessionMgtHandler(HttpServletRequest request) { + String jSessionId = getJessionId(request); + PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request)); + } + + public String getViewName() { + return viewName; + } + + public void setViewName(String viewName) { + this.viewName = viewName; + } + + public LoginService getLoginService() { + return loginService; + } + + public void setLoginService(LoginService loginService) { + this.loginService = loginService; + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ONAPWelcomeController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ONAPWelcomeController.java new file mode 100644 index 00000000..52473102 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/ONAPWelcomeController.java @@ -0,0 +1,84 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.controller; + +import java.security.Principal; +import java.util.Set; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.mitre.openid.connect.client.SubjectIssuerGrantedAuthority; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +@Controller +@RequestMapping("/") +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class ONAPWelcomeController extends EPRestrictedBaseController{ + String viewName; + + @RequestMapping(value = "/index.htm", method = RequestMethod.GET) + public String getIndexPage(HttpServletRequest request) { + return "/index"; + } + + @RequestMapping(value = {"/applicationsHome", "/dashboard", "/widgetsHome", "/kpidash*", "/admins", "/users", "/portalAdmins", "/applications", "/widgets", "/functionalMenu", "/contactUs", "/getAccess","/appCatalog" }, method = RequestMethod.GET) + public String getEcompSinglePage(HttpServletRequest request, HttpServletResponse response) { + return "forward:/index.html"; + } + + protected String getViewName() { + return viewName; + } + + protected void setViewName(String viewName) { + this.viewName = viewName; + } + + + @Resource(name = "namedAdmins") + private Set admins; + + @RequestMapping("/user") + public String user(Principal p) { + return "oid-user"; + } + + @RequestMapping("/admin") + public String admin(Model model, Principal p) { + + model.addAttribute("admins", admins); + + return "oid-admin"; + } + @RequestMapping("/oid-login") + public ModelAndView login(Principal p) { + return new ModelAndView("openIdLogin"); + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/OpenCollaborationController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/OpenCollaborationController.java new file mode 100644 index 00000000..18c89a66 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/OpenCollaborationController.java @@ -0,0 +1,23 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.controller; + +import java.util.HashMap; +import java.util.Map; diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/PeerBroadcastSocket.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/PeerBroadcastSocket.java new file mode 100644 index 00000000..086b69a9 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/PeerBroadcastSocket.java @@ -0,0 +1,106 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.controller; + +import java.io.IOException; +import java.util.Hashtable; +import java.util.Map; + +import javax.websocket.OnClose; +import javax.websocket.OnMessage; +import javax.websocket.OnOpen; +import javax.websocket.Session; +import javax.websocket.server.ServerEndpoint; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import com.fasterxml.jackson.databind.ObjectMapper; + +@ServerEndpoint("/opencontact") +public class PeerBroadcastSocket { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PeerBroadcastSocket.class); + + public static Map channelMap = new Hashtable(); + public Map sessionMap = new Hashtable(); + ObjectMapper mapper = new ObjectMapper(); + + @OnMessage + public void message(String message, Session session) { + try { + // JSONObject jsonObject = new JSONObject(message); + @SuppressWarnings("unchecked") + Map jsonObject = mapper.readValue(message, Map.class); + try { + Object from = jsonObject.get("from"); + if (from != null) { + if(channelMap.get(from.toString()) == null) { + channelMap.put(from.toString(), session); + sessionMap.put(session.getId(), from.toString()); + } + } + } catch (Exception je) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to read value" + je.getMessage()); + } + + try { + Object to = jsonObject.get("to"); + if (to == null) + return; + Object toSessionObj = channelMap.get(to); + if (toSessionObj != null) { + Session toSession = null; + toSession = (Session) toSessionObj; + toSession.getBasicRemote().sendText(message); + } + + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to send text" + ex.getMessage()); + } + + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed" + ex.getMessage()); + } + + } + + @OnOpen + public void open(Session session) { + logger.info(EELFLoggerDelegate.debugLogger, "Channel opened"); + } + + @OnClose + public void close(Session session) { + String channel = sessionMap.get(session.getId()); + if (channel != null) { + Object sessObj = channelMap.get(channel); + if (sessObj != null) { + try { + ((Session) sessObj).close(); + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to close" + e.getMessage()); + } + } + channelMap.remove(channel); + } + logger.info(EELFLoggerDelegate.debugLogger, "Channel closed"); + } + +} + diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/AppsOSController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/AppsOSController.java new file mode 100644 index 00000000..89f9fe58 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/AppsOSController.java @@ -0,0 +1,116 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.json.JSONObject; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.EPAppService; +import org.openecomp.portalapp.portal.service.PersUserAppService; +import org.openecomp.portalapp.portal.service.UserService; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class AppsOSController extends AppsController { + + static final String FAILURE = "failure"; + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsOSController.class); + + @Autowired + AdminRolesService adminRolesService; + @Autowired + EPAppService appService; + @Autowired + PersUserAppService persUserAppService; + @Autowired + UserService userService; + + + + /** + * Create new application's contact us details. + * + * @param contactUs + * @return + */ + @RequestMapping(value = "/portalApi/saveNewUser", method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse saveNewUser(HttpServletRequest request,@RequestBody EPUser newUser) { + EPUser user = EPUserUtils.getUserSession(request); + if (newUser == null) + return new PortalRestResponse(PortalRestStatusEnum.ERROR, FAILURE, + "New User cannot be null or empty"); + + if (!(adminRolesService.isSuperAdmin(user) || adminRolesService.isAccountAdmin(user))){ + if(!user.getLoginId().equalsIgnoreCase(newUser.getLoginId())) + return new PortalRestResponse(PortalRestStatusEnum.ERROR, FAILURE, + "UnAuthorized"); + } + + String checkDuplicate = request.getParameter("isCheck"); + String saveNewUser = FAILURE; + try { + saveNewUser = userService.saveNewUser(newUser,checkDuplicate); + } catch (Exception e) { + return new PortalRestResponse(PortalRestStatusEnum.ERROR, saveNewUser, e.getMessage()); + } + return new PortalRestResponse(PortalRestStatusEnum.OK, saveNewUser, ""); + } + + @RequestMapping(value = { "/portalApi/currentUserProfile/{loginId}" }, method = RequestMethod.GET, produces = "application/json") + public String getCurrentUserProfile(HttpServletRequest request, @PathVariable("loginId") String loginId) { + + Map map = new HashMap(); + EPUser user = null; + try { + user = (EPUser) userService.getUserByUserId(loginId).get(0); + map.put("firstName", user.getFirstName()); + map.put("lastName", user.getLastName()); + map.put("email", user.getEmail()); + map.put("loginId", user.getLoginId()); + map.put("loginPwd",user.getLoginPwd()); + map.put("middleInitial",user.getMiddleInitial()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to get user info", e); + } + + JSONObject j = new JSONObject(map);; + return j.toString(); + } + +} \ No newline at end of file diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/DashboardSearchResultController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/DashboardSearchResultController.java new file mode 100644 index 00000000..fe31066d --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/DashboardSearchResultController.java @@ -0,0 +1,243 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalapp.controller.EPRestrictedBaseController; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem; +import org.openecomp.portalapp.portal.service.DashboardSearchService; +import org.openecomp.portalapp.portal.transport.CommonWidget; +import org.openecomp.portalapp.portal.transport.CommonWidgetMeta; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.domain.support.CollaborateList; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/portalApi/search") +public class DashboardSearchResultController extends EPRestrictedBaseController { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardSearchResultController.class); + + @Autowired + private DashboardSearchService searchService; + + /** + * Gets all widgets by type: NEW or RESOURCE + * + * @param request + * @param resourceType + * Request parameter. + * @return Rest response wrapped around a CommonWidgetMeta object. + */ + @RequestMapping(value = "/widgetData", method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse getWidgetData(HttpServletRequest request, + @RequestParam String resourceType) { + return new PortalRestResponse(PortalRestStatusEnum.OK, "success", + searchService.getWidgetData(resourceType)); + } + + /** + * Saves all: news and resources + * + * @param commonWidgetMeta + * read from POST body. + * @return Rest response wrapped around a String; e.g., "success" or "ERROR" + */ + @RequestMapping(value = "/widgetDataBulk", method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse saveWidgetDataBulk(@RequestBody CommonWidgetMeta commonWidgetMeta) { + logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetDataBulk: argument is {}", commonWidgetMeta); + if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals("")) + return new PortalRestResponse(PortalRestStatusEnum.ERROR, "ERROR", + "Category cannot be null or empty"); + // validate dates + for (CommonWidget cw : commonWidgetMeta.getItems()) { + String err = validateCommonWidget(cw); + if (err != null) + return new PortalRestResponse(PortalRestStatusEnum.ERROR, err, null); + } + return new PortalRestResponse(PortalRestStatusEnum.OK, "success", + searchService.saveWidgetDataBulk(commonWidgetMeta)); + } + + /** + * Saves one: news or resource + * + * @param commonWidget + * read from POST body + * @return Rest response wrapped around a String; e.g., "success" or "ERROR" + */ + @RequestMapping(value = "/widgetData", method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse saveWidgetData(@RequestBody CommonWidget commonWidget) { + logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget); + if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().equals("")) + return new PortalRestResponse(PortalRestStatusEnum.ERROR, "ERROR", + "Cateogry cannot be null or empty"); + String err = validateCommonWidget(commonWidget); + if (err != null) + return new PortalRestResponse(PortalRestStatusEnum.ERROR, err, null); + return new PortalRestResponse(PortalRestStatusEnum.OK, "success", + searchService.saveWidgetData(commonWidget)); + } + + /** + * Used by the validate function + */ + private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd"); + + /** + * Validates the content of a common widget. + * + * @param cw + * @return null on success; an error message if validation fails. + * @throws Exception + */ + private String validateCommonWidget(CommonWidget cw) { + try { + if (cw.getEventDate() != null && cw.getEventDate().trim().length() > 0) + yearMonthDayFormat.parse(cw.getEventDate()); + } catch (ParseException ex) { + return ex.toString(); + } + return null; + } + + /** + * Deletes one: news or resource + * + * @param commonWidget + * read from POST body + * @return Rest response wrapped around a String; e.g., "success" or "ERROR" + */ + @RequestMapping(value = "/deleteData", method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse deleteWidgetData(@RequestBody CommonWidget commonWidget) { + logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget); + return new PortalRestResponse(PortalRestStatusEnum.OK, "success", + searchService.deleteWidgetData(commonWidget)); + } + + /** + * Searches all portal for the input string. + * + * @param request + * @param searchString + * @return Rest response wrapped around a Map of String to List of Search + * Result Item. + */ + @RequestMapping(value = "/allPortal", method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse>> searchPortal(HttpServletRequest request, + @RequestParam String searchString) { + + EPUser user = EPUserUtils.getUserSession(request); + try { + if (user == null) { + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, + "searchPortal: User object is null? - check logs", + new HashMap>()); + } else if (searchString == null || searchString.trim().length() == 0) { + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null", + new HashMap>()); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'", + user.getLoginId(), searchString); + Map> results = searchService.searchResults(user.getLoginId(), + searchString); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.", + new HashMap>()); + } + } + + /** + * Gets all active users. + * + * TODO: should only the superuser be allowed to use this API? + * + * @param request + * @return Rest response wrapped around a list of String + */ + @RequestMapping(value = "/activeUsers", method = RequestMethod.GET, produces = "application/json") + public List getActiveUsers(HttpServletRequest request) { + List activeUsers = null; + List onlineUsers = new ArrayList<>(); + try { + EPUser user = EPUserUtils.getUserSession(request); + String userId = user.getOrgUserId(); + + activeUsers = searchService.getRelatedUsers(userId); + HashSet usersSet = CollaborateList.getInstance().getAllUserName(); + for (String users : activeUsers) { + if (usersSet.contains(users)) { + onlineUsers.add(users); + } + } + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e); + } + return onlineUsers; + } + + /** + * Gets only those users that are 'related' to the currently logged-in user. + * + * @param request + * @return Rest response wrapped around a List of String + */ + @RequestMapping(value = "/relatedUsers", method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse> activeUsers(HttpServletRequest request) { + EPUser user = EPUserUtils.getUserSession(request); + try { + if (user == null) { + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs", + new ArrayList<>()); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId()); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", + searchService.getRelatedUsers(user.getLoginId())); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.", + new ArrayList<>()); + } + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java new file mode 100644 index 00000000..1d6b59ef --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java @@ -0,0 +1,129 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.io.IOException; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.controller.EPRestrictedRESTfulBaseController; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.EPLoginService; +import org.openecomp.portalapp.portal.service.FunctionalMenuService; +import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItem; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.portal.utils.PortalConstants; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(PortalConstants.REST_AUX_API) +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class ExternalAppsRestfulController extends EPRestrictedRESTfulBaseController { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppsRestfulController.class); + + @Autowired + FunctionalMenuService functionalMenuService; + + @Autowired + EPLoginService epLoginService; + + @Autowired + AdminRolesService adminRolesService; + + @RequestMapping(value={"/getFavorites"}, method = RequestMethod.GET,produces = "application/json") + public List getFavoritesForUser(HttpServletRequest request, HttpServletResponse response) throws Exception { + String loginId = ""; + String userAgent = ""; + List favorites = null; + + loginId = request.getHeader(EPSystemProperties.MDC_LOGIN_ID); + userAgent = MDC.get(EPSystemProperties.PARTNER_NAME); + + EPUser epUser = epLoginService.findUserWithoutPwd(loginId); + logger.info(EELFLoggerDelegate.errorLogger, "getFavorites request was received from " + userAgent + " for the user " + loginId + "."); + if (epUser==null || epUser.getId()==null) { + logger.error(EELFLoggerDelegate.errorLogger, "No User record found for the LoginId '" + loginId + "' in the database."); + throw new Exception("Received null for Login-Id."); + } else { + favorites = functionalMenuService.getFavoriteItems(epUser.getId()); + FieldsValidator fieldsValidator = new FieldsValidator(); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + + EcompPortalUtils.logAndSerializeObject("/auxapi/getFavorites", "result = ", favorites); + } + + return favorites; + } + + @RequestMapping(value={"/functionalMenuItemsForUser"}, method = RequestMethod.GET,produces = "application/json") + public List getFunctionalMenuItemsForUser(HttpServletRequest request, HttpServletResponse response) throws Exception { + String loginId = ""; + String userAgent = ""; + List fnMenuItems = null; + + loginId = request.getHeader("LoginId"); + userAgent = MDC.get(EPSystemProperties.PARTNER_NAME); + + EPUser epUser = epLoginService.findUserWithoutPwd(loginId); + logger.info(EELFLoggerDelegate.errorLogger, "getFunctionalMenuItemsForUser request was received from " + userAgent + " for the user " + loginId + "."); + if (epUser==null || epUser.getId()==null) { + logger.error(EELFLoggerDelegate.errorLogger, "No User record found for the LoginId '" + loginId + "' in the database."); + throw new Exception("Received null for Login-Id."); + } else if (adminRolesService.isSuperAdmin(epUser)) { + logger.debug(EELFLoggerDelegate.debugLogger, "FunctionalMenuHandler: SuperUser, about to call getFunctionalMenuItems()"); + fnMenuItems = functionalMenuService.getFunctionalMenuItems(); + } + else { + logger.debug(EELFLoggerDelegate.debugLogger, "getMenuItemsForAuthUser: about to call getFunctionalMenuItemsForUser()"); + fnMenuItems = functionalMenuService.getFunctionalMenuItemsForUser(epUser.getOrgUserId()); + } + + FieldsValidator fieldsValidator = new FieldsValidator(); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + + EcompPortalUtils.logAndSerializeObject("/auxapi/functionalMenuItemsForUser", "result = ", fnMenuItems); + + return fnMenuItems; + } + + @ExceptionHandler(Exception.class) + protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException { + logger.warn(EELFLoggerDelegate.errorLogger, "Handling bad request", e); + response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage()); + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java new file mode 100644 index 00000000..76a9b40f --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java @@ -0,0 +1,117 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.controller.EPRestrictedBaseController; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.PortalAdminService; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.PortalAdmin; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class PortalAdminController extends EPRestrictedBaseController { + @Autowired + PortalAdminService portalAdminService; + @Autowired + AdminRolesService adminRolesService; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalAdminController.class); + + @RequestMapping(value = { "/portalApi/portalAdmins" }, method = RequestMethod.GET, produces = "application/json") + public List getPortalAdmins(HttpServletRequest request, HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + List portalAdmins = null; + if (user == null) { + logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.getPortalAdmins, null user"); + EcompPortalUtils.setBadPermissions(user, response, "getPortalAdmins"); + } else if (!adminRolesService.isSuperAdmin(user)) { + logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.getPortalAdmins, bad permissions"); + EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin"); + } else { + // return the list of portal admins + portalAdmins = portalAdminService.getPortalAdmins(); + logger.debug(EELFLoggerDelegate.debugLogger, "portalAdmins: called getPortalAdmins()"); + EcompPortalUtils.logAndSerializeObject("/portalApi/getPortalAdmins", "result =", portalAdmins); + } + + return portalAdmins; + } + + /** + * RESTful service method to create a new portal admin. Requirement: you + * must be the Ecomp portal super admin user. + */ + + @RequestMapping(value = { "/portalApi/portalAdmin" }, method = RequestMethod.POST) + public FieldsValidator createPortalAdmin(HttpServletRequest request, @RequestBody String userid, + HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + FieldsValidator fieldsValidator = null; + if (user == null) { + logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin, null user"); + EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin"); + } else if (!adminRolesService.isSuperAdmin(user)) { + logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin bad permissions"); + EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin"); + } else { + fieldsValidator = portalAdminService.createPortalAdmin(userid); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + } + EcompPortalUtils.logAndSerializeObject("/portalAdmin", "POST result =", response.getStatus()); + + return fieldsValidator; + } + + @RequestMapping(value = { "/portalApi/portalAdmin/{orgUserId}" }, method = RequestMethod.DELETE) + public FieldsValidator deletePortalAdmin(HttpServletRequest request, @PathVariable("orgUserId") Long orgUserId, + HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); + FieldsValidator fieldsValidator = null; + if (!adminRolesService.isSuperAdmin(user)) { + EcompPortalUtils.setBadPermissions(user, response, "deletePortalAdmin"); + } else { + fieldsValidator = portalAdminService.deletePortalAdmin(orgUserId); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + } + EcompPortalUtils.logAndSerializeObject("/portalAdmin", "DELETE result =", response.getStatus()); + + return fieldsValidator; + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/interceptor/SessionTimeoutInterceptor.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/interceptor/SessionTimeoutInterceptor.java new file mode 100644 index 00000000..dc18f1ff --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/interceptor/SessionTimeoutInterceptor.java @@ -0,0 +1,101 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.interceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.authentication.LoginStrategy; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalapp.util.SessionCookieUtil; +import org.openecomp.portalsdk.core.controller.FusionBaseController; +import org.openecomp.portalsdk.core.domain.support.CollaborateList; +import org.openecomp.portalsdk.core.exception.SessionExpiredException; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +public class SessionTimeoutInterceptor extends HandlerInterceptorAdapter { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SessionTimeoutInterceptor.class); + + @Autowired + private LoginStrategy loginStrategy; + + public SessionTimeoutInterceptor() { + } + + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + + if (!isHandlerMethod(handler)) + return false; + + HandlerMethod method = (HandlerMethod) handler; + + if (!isFusionController(method.getBean())) + return false; + + if (method.getBean() instanceof FusionBaseController) { + FusionBaseController controller = (FusionBaseController) method.getBean(); + + if (!controller.isAccessible()) { + try { + EPUser user = EPUserUtils.getUserSession(request); + + if (request.getRequestURI().indexOf("logout.htm") > -1) { + CollaborateList.delUserName(user.getOrgUserId()); + throw new SessionExpiredException(); + } else { + resetSessionMaxIdleTimeOut(request); + CollaborateList.addUserName(user.getOrgUserId()); + } + } catch (Exception see) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(see)); + // return loginStrategy.login(request, response); + return false; + } + + } + + } + + return true; + } + + private void resetSessionMaxIdleTimeOut(HttpServletRequest request) { + SessionCookieUtil.resetSessionMaxIdleTimeOut(request); + + } + + private boolean isFusionController(Object controller) { + if (controller instanceof FusionBaseController) + return true; + return false; + } + + private boolean isHandlerMethod(Object controller) { + if (controller instanceof HandlerMethod) + return true; + return false; + } +} \ No newline at end of file diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAspect.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAspect.java new file mode 100644 index 00000000..974272d0 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAspect.java @@ -0,0 +1,204 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.logging.aop; + +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum; +import org.springframework.beans.factory.annotation.Autowired; + +@Aspect +@org.springframework.context.annotation.Configuration +public class EPEELFLoggerAspect { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPEELFLoggerAspect.class); + + @Autowired + EPEELFLoggerAdvice epAdvice; + + /* + * Point-cut expression to handle all INCOMING_REST_MESSAGES + */ + @Pointcut("execution(public * org.openecomp.portalapp.portal.controller.*.*(..))") + public void incomingAuditMessages() {} + + /* + * Handles all INCOMING_REST_MESSAGES from kpiDashboard + */ + @Pointcut("execution(public * org.openecomp.portalapp.kpidash.controller.*.*(..))") + public void kpiDashboardAuditMessages() {} + + /* + * Point-cut expression to handle all session management INCOMING_REST_MESSAGES + */ + @Pointcut("execution(public * org.openecomp.portalapp.controller.sessionmgt.*.*(..))") + public void sessionMgtIncomingAuditMessages() {} + + /* + * Point-cut expression to handle UserProfileController INCOMING_REST_MESSAGES + */ + @Pointcut("execution(public * org.openecomp.portalapp.controller.core.UserProfileController.*(..))") + public void userProfileIncomingAuditMessages() {} + + /* + * Point-cut expression to handle UserProfileController INCOMING_REST_MESSAGES + */ + @Pointcut("execution(public * org.openecomp.portalapp.controller.ONAPWelcomeController.*(..))") + public void welcomeIncomingAuditMessages() {} + + /* + * Point-cut expression to handle INCOMING Logout Rest Messages + */ + @Pointcut("execution(public * org.openecomp.portalapp.controller.ECOMPLogoutController.*(..))") + public void logoutAuditMessages() {} + + + /* + * Point-cut expression which handles all the OUTGOING_REST_MESSAGES. + */ + @Pointcut("execution(public * org.openecomp.portalapp.portal.service.ApplicationsRestClientServiceImpl.*(..))") + public void outgoingAuditMessages() {} + + /* + * Point-cut expression to handle all the session management OUTGOING_REST_MESSAGES. + */ + @Pointcut("execution(public * org.openecomp.portalapp.service.sessionmgt.SessionCommunication.*(..))") + public void sessionMgtOutgoingAuditMessages() {} + + /* + * Point-cut expression which handles all the LDAP_PHONEBOOK_USER_SEARCH calls. + */ + @Pointcut("execution(public * org.openecomp.portalapp.portal.service.EPLdapServiceImpl.*(..))") + public void phoneBookSearchAuditMessages() {} + + /* + * Handles Audit, Metrics & Debug logging for the point-cut + * expression defined at class-level + */ + @Around("(incomingAuditMessages() || kpiDashboardAuditMessages() || sessionMgtIncomingAuditMessages() || " + + "userProfileIncomingAuditMessages() || welcomeIncomingAuditMessages()) && @within(epAuditLog)") + public Object incomingAuditMessagesAroundClass(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.INCOMING_REST_MESSAGE); + } + + /* + * Handles Audit, Metrics & Debug logging for the point-cut + * expression defined at class-level + */ + @Around("(outgoingAuditMessages() || sessionMgtOutgoingAuditMessages()) && @within(epAuditLog)") + public Object outgoingAuditMessagesAroundClass(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.OUTGOING_REST_MESSAGE); + } + + + /* + * Handles Audit, Metrics & Debug logging for the point-cut + * expression defined at method-level + */ + @Around("(outgoingAuditMessages() || sessionMgtOutgoingAuditMessages()) && @annotation(epAuditLog)") + public Object outgoingAuditMessagesAroundMethod(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.OUTGOING_REST_MESSAGE); + } + + /* + * Handles Audit, Metrics & Debug logging for the point-cut + * expression defined at method-level + */ + @Around("(incomingAuditMessages() || kpiDashboardAuditMessages() || sessionMgtIncomingAuditMessages() ||" + + "userProfileIncomingAuditMessages() || welcomeIncomingAuditMessages()) && @annotation(epAuditLog)") + public Object incomingAuditMessagesAroundMethod(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.INCOMING_REST_MESSAGE); + } + + @Around("@annotation(epAuditLog)") + public Object loginAuditMessagesAroundMethod(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.FE_LOGIN_ATTEMPT); + } + + @Around("logoutAuditMessages() && @annotation(epAuditLog)") + public Object logoutAuditMessagesAroundMethod(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.FE_LOGOUT); + } + + @Around("phoneBookSearchAuditMessages() && @annotation(epAuditLog)") + public Object phonebookSearchAuditMessagesAroundMethod(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable { + return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH); + } + + private Object logAroundMethod(ProceedingJoinPoint joinPoint, SecurityEventTypeEnum securityEventType) throws Throwable { + //Before + Object[] passOnArgs = new Object[] {joinPoint.getSignature().getDeclaringType().getName(), joinPoint.getSignature().getName()}; + Object[] returnArgs = epAdvice.before(securityEventType, joinPoint.getArgs(), passOnArgs); + + //Call the actual method + Object result = null; + String statusCode = "COMPLETE"; + String responseCode = "200"; + try { + result = joinPoint.proceed(); + } catch(Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + statusCode = "ERROR"; + responseCode = "500"; //Internal server error + } + + //Check the result + if (securityEventType!=null) { + if (result==null) { + statusCode = "ERROR"; + //Check if there is an internal response code + //and use it if the caller function has configured it. + responseCode = epAdvice.getInternalResponseCode(); + if (responseCode==null||responseCode=="") { + responseCode = "500"; //Internal server error + } + } else if (result instanceof FieldsValidator) { + FieldsValidator fieldsValidator = (FieldsValidator) result; + if (fieldsValidator!=null && fieldsValidator.httpStatusCode!=null) { + responseCode = fieldsValidator.httpStatusCode.toString(); + } + } + } + + //After + epAdvice.after(securityEventType, statusCode, responseCode, joinPoint.getArgs(), returnArgs, passOnArgs); + + return result; + } + + //Metrics Logging + @Pointcut("execution(* *(..))") + public void performMetricsLogging() {} + + @Around("performMetricsLogging() && @within(epMetricsLog)") + public Object metricsLoggingAroundClass(ProceedingJoinPoint joinPoint, EPMetricsLog epMetricsLog) throws Throwable { + return this.logAroundMethod(joinPoint, null); + } + + @Around("performMetricsLogging() && @annotation(epMetricsLog)") + public Object metricsLoggingAroundMethod(ProceedingJoinPoint joinPoint, EPMetricsLog epMetricsLog) throws Throwable { + return this.logAroundMethod(joinPoint, null); + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientService.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientService.java new file mode 100644 index 00000000..71542268 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientService.java @@ -0,0 +1,28 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import org.apache.cxf.transport.http.HTTPException; + +public interface ApplicationsRestClientService { + public T get(Class clazz, long app, String restPath) throws HTTPException; + public T post(Class clazz, long appId, Object payload, String restPath) throws HTTPException ; + public T put(Class clazz, long appId, Object payload, String restPath) throws HTTPException ; +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientServiceImpl.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientServiceImpl.java new file mode 100644 index 00000000..4626b17b --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientServiceImpl.java @@ -0,0 +1,267 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; + +import java.lang.reflect.Type; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Date; + +import javax.annotation.PostConstruct; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.apache.cxf.jaxrs.client.WebClient; +import org.apache.cxf.transport.http.HTTPException; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; + +@Service("applicationsRestClientService") +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class ApplicationsRestClientServiceImpl implements ApplicationsRestClientService{ + + private static final String PASSWORD_HEADER = "password"; + + private static final String APP_USERNAME_HEADER = "username"; + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ApplicationsRestClientServiceImpl.class); + + @Autowired + private AppsCacheService appsCacheService; + Gson gson = null; + + @PostConstruct + private void init(){ + logger.debug(EELFLoggerDelegate.debugLogger, "initializing"); + GsonBuilder builder = new GsonBuilder(); + + // Register an adapter to manage the date types as long values + builder.registerTypeAdapter(Date.class, new JsonDeserializer() { + public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + return new Date(json.getAsJsonPrimitive().getAsLong()); + } + }); + + gson = builder.create(); + } + + // TODO: do we need to do additional logging for remote API calls? + private static WebClient createClientForPath(String baseUri, String path) { + logger.info(EELFLoggerDelegate.debugLogger, "Creating web client for " + baseUri + " + " + path); + WebClient client = WebClient.create(baseUri); + client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON); + client.path(path); + return client; + } + + @EPMetricsLog + private void verifyResponse(Response response) throws HTTPException { + int status = response.getStatus(); + logger.debug(EELFLoggerDelegate.debugLogger, "http response status=" + status); + MDC.put(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(status)); + if (!isHttpSuccess(status)) { + String errMsg = "Failed. Status=" + status + "; [" + response.getStatusInfo().getReasonPhrase().toString() + "]"; + URL url = null; + try { + // must not be null to avoid NPE in HTTPException constructor + url = new URL("http://null"); + if (response.getLocation() != null) + url = response.getLocation().toURL(); + } catch (MalformedURLException e) { + // never mind. it is only for the debug message. + logger.warn(EELFLoggerDelegate.errorLogger, "Failed to build URL", e); + } + logger.error(EELFLoggerDelegate.errorLogger, "http response failed. " + errMsg + "; url=" + url); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeIncorrectHttpStatusError); + throw new HTTPException(status, errMsg, url); + } + } + + private static boolean isHttpSuccess(int status){ + return status / 100 == 2; + } + + @EPMetricsLog + private WebClient createClientForApp(long appId, String restPath) { + logger.debug(EELFLoggerDelegate.debugLogger, "creating client for appId=" + appId + "; restPath=" + restPath); + EPApp externalApp = appsCacheService.getApp(appId); + if(externalApp != null){ + String appBaseUri = externalApp.getAppRestEndpoint(); + String username = externalApp.getUsername(); + String encriptedPwd = externalApp.getAppPassword(); + String decreptedAppPwd = ""; + + //Set local context + MDC.put(EPSystemProperties.PROTOCOL, EPSystemProperties.HTTP); + if (appBaseUri!=null && appBaseUri.contains("https")) { + MDC.put(EPSystemProperties.PROTOCOL, EPSystemProperties.HTTPS); + } + MDC.put(EPSystemProperties.FULL_URL, appBaseUri + restPath); + MDC.put(EPSystemProperties.TARGET_ENTITY, externalApp.getName()); + MDC.put(EPSystemProperties.TARGET_SERVICE_NAME, restPath); + + try { + decreptedAppPwd = CipherUtil.decrypt(encriptedPwd, SystemProperties.getProperty(SystemProperties.Decryption_Key)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Unable to decrypt App name = " + externalApp, EcompPortalUtils.getStackTrace(e)); + logger.error(EELFLoggerDelegate.errorLogger, "Unable to decrypt App name = " + externalApp, EcompPortalUtils.getStackTrace(e)); + } + logger.debug(EELFLoggerDelegate.debugLogger, String.format("App %d found, baseUri=[%s], Headers: [%s=%s, %s=%s]", appId, appBaseUri, APP_USERNAME_HEADER, username, PASSWORD_HEADER, encriptedPwd)); + WebClient client = createClientForPath(appBaseUri, restPath); + client.header(APP_USERNAME_HEADER, username); + client.header(PASSWORD_HEADER, decreptedAppPwd); + client.header(SystemProperties.ECOMP_REQUEST_ID, MDC.get(MDC_KEY_REQUEST_ID)); + client.header(SystemProperties.USERAGENT_NAME, EPSystemProperties.ECOMP_PORTAL_BE); + + return client; + } + return null; + } + + @Override + public T get(Class clazz, long appId, String restPath) throws HTTPException { + + WebClient webClient = null; + Response response = null; + T t = null; + + webClient = createClientForApp(appId, restPath); + EcompPortalUtils.logAndSerializeObject(restPath, "GET request =", "no-payload"); + + try { + if (webClient!=null) { + response = webClient.get(); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Unable to create the Webclient to make the '" + restPath + "' API call."); + } + } catch (Exception e) { + MDC.put(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeRestApiGeneralError); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while making the GET REST API call, Details: " + EcompPortalUtils.getStackTrace(e)); + } + + if (response!=null) { + verifyResponse(response); + String str = response.readEntity(String.class); + EcompPortalUtils.logAndSerializeObject(restPath, "GET result =", str); + try { t = gson.fromJson(str, clazz); } catch(Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput); + } + } + + return t; + } + + @Override + public T post(Class clazz, long appId, Object payload, String restPath) throws HTTPException { + WebClient client = null; + Response response = null; + T t = null; + + client = createClientForApp(appId, restPath); + EcompPortalUtils.logAndSerializeObject(restPath, "POST request =", payload); + + + try { + if (client!=null) { + response = client.post(payload); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Unable to create the Webclient to make the '" + restPath + "' API call."); + } + } catch (Exception e) { + MDC.put(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeRestApiGeneralError); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while making the POST REST API call, Details: " + EcompPortalUtils.getStackTrace(e)); + } + + if (response!=null) { + verifyResponse(response); + + //String contentType = response.getHeaderString("Content-Type"); + if(clazz != null) { + String str = response.readEntity(String.class); + EcompPortalUtils.logAndSerializeObject(restPath, "POST result =", str); + try { t = gson.fromJson(str, clazz); } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput); + } + } + } + return t; + } + + @Override + public T put(Class clazz, long appId, Object payload, String restPath) throws HTTPException { + WebClient client = null; + Response response = null; + T t = null; + + client = createClientForApp(appId, restPath); + EcompPortalUtils.logAndSerializeObject(restPath, "PUT request =", payload); + + try { + if (client!=null) { + response = client.put(payload); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Unable to create the Webclient to make the '" + restPath + "' API call."); + } + } catch(Exception e) { + MDC.put(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeRestApiGeneralError); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while making the PUT REST API call, Details: " + EcompPortalUtils.getStackTrace(e)); + } + + if (response!=null) { + verifyResponse(response); + String str = response.readEntity(String.class); + EcompPortalUtils.logAndSerializeObject(restPath, "PUT result =", str); + try { t = gson.fromJson(str, clazz); } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput); + } + } + return t; + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheService.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheService.java new file mode 100644 index 00000000..20939a9a --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheService.java @@ -0,0 +1,40 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ + +package org.openecomp.portalapp.portal.service; + +import org.openecomp.portalapp.portal.domain.EPApp; + +public interface AppsCacheService { + + /** + * returns an app by id from the cache + * @param appId + * @return corresponding App + */ + EPApp getApp(Long appId); + + /** + * returns the corresponding application endpoint + * @param appId + * @return if appId exists in cache, then return corresponding application endpoint, null otherwise. + */ + String getAppEndpoint(Long appId); +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheServiceImple.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheServiceImple.java new file mode 100644 index 00000000..683017b1 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheServiceImple.java @@ -0,0 +1,104 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.annotation.PostConstruct; + +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; + +@Service("appsCacheService") +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class AppsCacheServiceImple implements AppsCacheService { + @Autowired + EPAppService appsService; + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsCacheServiceImple.class); + + private static long updateTime = 0; + private static final int cacheUpdateIntervalInSeconds = 10; + + private static volatile Map appsMap; + + @PostConstruct + public void init() { + this.refreshAppsMap(); + } + + private Map refreshAppsMap() { + long now = System.currentTimeMillis(); + + if(noNeedToUpdate(now)) + return null; + + synchronized (this) { + if(noNeedToUpdate(now)) + return null; + List allApps = appsService.getAppsFullList(); + Map newAppsMap = new HashMap(); + for (EPApp app : allApps) { + newAppsMap.put(app.getId(), app); + } + // Switch cache with the new one. + appsMap = newAppsMap; + updateTime = now; + } + + return appsMap; + } + + private boolean noNeedToUpdate(long now) { + long secondsPassed = (now - updateTime)/1000; + if(secondsPassed < cacheUpdateIntervalInSeconds){ + logger.debug(EELFLoggerDelegate.debugLogger, "no need to refresh yet, seconds since last refresh: " + secondsPassed + ", refresh interval (sec) = " + cacheUpdateIntervalInSeconds); + return true; // no need to update cache + } + return false; // its time to update + } + + @Override + public String getAppEndpoint(Long appId) { + refreshAppsMap(); + EPApp app = appsMap.get(appId); + if(app != null) + return app.getAppRestEndpoint(); + return null; + } + + @Override + public EPApp getApp(Long appId) { + refreshAppsMap(); + EPApp app = appsMap.get(appId); + if(app != null) + return app; + return null; + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/EPAppServiceImpl.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/EPAppServiceImpl.java new file mode 100644 index 00000000..074821f6 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/EPAppServiceImpl.java @@ -0,0 +1,71 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + + +import java.util.ArrayList; +import java.util.List; +import java.util.TreeSet; + +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service("epAppService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class EPAppServiceImpl extends EPAppCommonServiceImpl implements EPAppService { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPAppServiceImpl.class); + + @Autowired + private DataAccessService dataAccessService; + + @Override + public List getUserRemoteApps(String id) { + + StringBuilder query = new StringBuilder(); + + query.append("SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = FN_APP.APP_ID where "); + query.append( + "FN_USER_ROLE.USER_ID = " + id + " AND FN_USER_ROLE.ROLE_ID != " + SUPER_ADMIN_ROLE_ID); + query.append(" AND FN_APP.ENABLED = 'Y'"); + + TreeSet distinctApps = new TreeSet(); + + @SuppressWarnings("unchecked") + List adminApps = dataAccessService.executeSQLQuery(query.toString(), EPApp.class, null); + for (EPApp app : adminApps) { + distinctApps.add(app); + } + + List userApps = new ArrayList(); + userApps.addAll(distinctApps); + return userApps; + + } +} \ No newline at end of file diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/SearchService.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/SearchService.java new file mode 100644 index 00000000..94937dc4 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/SearchService.java @@ -0,0 +1,40 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.transport.UserWithNameSurnameTitle; + +public interface SearchService { + + + public String searchUsersInPhoneBook(String searchString); + + public String searchUsersInFnTable(String searchString); + + public List searchUsersByName(EPUser attrUser); + + public List searchUsersByUserId(EPUser attrUser); + + public EPUser searchUserByUserId(String orgUserId); + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/SearchServiceImpl.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/SearchServiceImpl.java new file mode 100644 index 00000000..35fc00bd --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/SearchServiceImpl.java @@ -0,0 +1,192 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.transport.UserWithNameSurnameTitle; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Service("searchService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class SearchServiceImpl implements SearchService { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SearchServiceImpl.class); + + // TODO: the values below should be defined in other place + private static final int maxSizeOfSearchResult = 100; + + @Autowired + UserService userService; + + @Override + public String searchUsersInPhoneBook(String searchString) { + return searchUsersInFnTable(searchString); + } + + @Override + public String searchUsersInFnTable(String searchString) { + String orgUserId = null; + List tokens = EcompPortalUtils.parsingByRegularExpression(searchString, " "); + for (int i = 0; i < tokens.size(); i++) { // find userid if possible and remove it from tokens + if (tokens.get(i).matches(".*\\d+.*")) { + orgUserId = tokens.get(i); + tokens.remove(i); + } + } + while (tokens.size() > 2) { // we use no more then first 2 tokens (userId is removed, see above) + tokens.remove(tokens.size() - 1); + } + EPUser attrUser = new EPUser(); + attrUser.setOrgUserId(orgUserId); + List resultOfSearch = new ArrayList(), resultOfAdditionalSearch = null; + if (tokens.size() == 2) { + attrUser.setFirstName(tokens.get(0)); + attrUser.setLastName(tokens.get(1)); + resultOfSearch = this.searchUsersByName(attrUser); + resultOfSearch = this.removeWrongFirstNames(resultOfSearch, tokens.get(0)); + resultOfSearch = this.removeWrongLastNames(resultOfSearch, tokens.get(1)); + if (resultOfSearch.size() < maxSizeOfSearchResult) { + attrUser.setFirstName(tokens.get(1)); + attrUser.setLastName(tokens.get(0)); + resultOfAdditionalSearch = this.searchUsersByName(attrUser); + resultOfAdditionalSearch = this.removeWrongFirstNames(resultOfAdditionalSearch, tokens.get(1)); + resultOfAdditionalSearch = this.removeWrongLastNames(resultOfAdditionalSearch, tokens.get(0)); + } + } else if (tokens.size() == 1) { + attrUser.setFirstName(tokens.get(0)); + resultOfSearch = this.searchUsersByName(attrUser); + resultOfSearch = this.removeWrongFirstNames(resultOfSearch, tokens.get(0)); + if (resultOfSearch.size() < maxSizeOfSearchResult) { + attrUser.setFirstName(null); + attrUser.setLastName(tokens.get(0)); + resultOfAdditionalSearch = this.searchUsersByName(attrUser); + resultOfAdditionalSearch = this.removeWrongLastNames(resultOfAdditionalSearch, tokens.get(0)); + } + } else if (orgUserId != null) { + resultOfSearch = this.searchUsersByUserId(attrUser); + } + if (resultOfAdditionalSearch != null) { + resultOfSearch.addAll(resultOfAdditionalSearch); + } + resultOfSearch = this.cutSearchResultToMaximumSize(resultOfSearch); + ObjectMapper mapper = new ObjectMapper(); + String result = "[]"; + try { + result = mapper.writeValueAsString(resultOfSearch); + } catch (JsonProcessingException e) { + logger.error(EELFLoggerDelegate.errorLogger, "searchUsersInPhoneBook Exception = " + EcompPortalUtils.getStackTrace(e)); + } + return result; + } + + + @SuppressWarnings("rawtypes") + public List searchUsersByUserId(EPUser attrUser) { + List foundUsers = new ArrayList(); + try { + List searchResult = this.userService.getUserByUserId(attrUser.getOrgUserId()); + for (Object obj : searchResult) { + EPUser user = (EPUser) obj; + UserWithNameSurnameTitle foundUser = new UserWithNameSurnameTitle(user.getOrgUserId(), user.getFirstName(), user.getLastName(), user.getJobTitle()); + foundUsers.add(foundUser); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "searchInPhoneBookWithToken Exception = " + EcompPortalUtils.getStackTrace(e)); + } + return foundUsers; + } + + @SuppressWarnings("rawtypes") + public List searchUsersByName(EPUser attrUser) { + List foundUsers = new ArrayList(); + try { + List searchResult = this.userService.getUserByFirstLastName(attrUser.getFirstName(),attrUser.getLastName()); + for (Object obj : searchResult) { + EPUser user = (EPUser) obj; + UserWithNameSurnameTitle foundUser = new UserWithNameSurnameTitle(user.getOrgUserId(), user.getFirstName(), user.getLastName(), user.getJobTitle()); + foundUsers.add(foundUser); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "searchInPhoneBookWithToken Exception = " + EcompPortalUtils.getStackTrace(e)); + } + return foundUsers; + } + + private List removeWrongFirstNames(List resultOfSearch, String firstName) { + firstName = firstName.toUpperCase(); + for (int i = resultOfSearch.size() - 1; i >= 0; i--) { + UserWithNameSurnameTitle user = resultOfSearch.get(i); + if ((user.firstName == null) || !user.firstName.toUpperCase().startsWith(firstName)) { + resultOfSearch.remove(i); + } + } + return resultOfSearch; + } + + private List removeWrongLastNames(List resultOfSearch, String lastName) { + lastName = lastName.toUpperCase(); + for (int i = resultOfSearch.size() - 1; i >= 0; i--) { + UserWithNameSurnameTitle user = resultOfSearch.get(i); + if ((user.lastName == null) || !user.lastName.toUpperCase().startsWith(lastName)) { + resultOfSearch.remove(i); + } + } + return resultOfSearch; + } + + private List cutSearchResultToMaximumSize(List resultOfSearch) { + for (int i = resultOfSearch.size() - 1; i >= maxSizeOfSearchResult; i--) { + resultOfSearch.remove(i); + } + return resultOfSearch; + } + + + @SuppressWarnings("rawtypes") + @Override + public EPUser searchUserByUserId(String orgUserId) { + List foundUsers = new ArrayList(); + try { + List searchResult = this.userService.getUserByUserId(orgUserId); + for (Object obj : searchResult) { + EPUser user = (EPUser) obj; + foundUsers.add(user); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "searchInPhoneBookWithToken Exception = " + EcompPortalUtils.getStackTrace(e)); + } + return foundUsers.get(0); + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserRolesService.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserRolesService.java new file mode 100644 index 00000000..b285051c --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserRolesService.java @@ -0,0 +1,58 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.apache.cxf.transport.http.HTTPException; +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EPUserApp; +import org.openecomp.portalapp.portal.transport.AppWithRolesForUser; +import org.openecomp.portalapp.portal.transport.RoleInAppForUser; +import org.openecomp.portalapp.portal.transport.UserApplicationRoles; + +public interface UserRolesService { + + public List getAppRolesForUser(Long appId, String userId); + + public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser); + + public List getUsersFromAppEndpoint(Long appId) throws HTTPException; + + public List importRolesFromRemoteApplication(Long appId) throws HTTPException; + + + /** + * Gets entries from the local fn_user_role table for the specified user and + * app. + * + * @param appId + * ID of row in fn_app + * @param userid + * ID of row in fn_user + * @return List of EPRole; empty if none found. + */ + public List getCachedAppRolesForUser(Long appId, Long userId); + + public String updateRemoteUserProfile(String orgUserId, Long appId); + + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserRolesServiceImpl.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserRolesServiceImpl.java new file mode 100644 index 00000000..a0aac922 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserRolesServiceImpl.java @@ -0,0 +1,726 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import javax.annotation.PostConstruct; + +import org.apache.commons.lang.StringUtils; +import org.apache.cxf.transport.http.HTTPException; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EPUserApp; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalapp.portal.transport.AppWithRolesForUser; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItem; +import org.openecomp.portalapp.portal.transport.FunctionalMenuRole; +import org.openecomp.portalapp.portal.transport.RemoteUserWithRoles; +import org.openecomp.portalapp.portal.transport.RoleInAppForUser; +import org.openecomp.portalapp.portal.transport.RolesInAppForUser; +import org.openecomp.portalapp.portal.transport.UserApplicationRoles; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.restful.domain.EcompRole; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.service.UserProfileService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Service("userRolesService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class UserRolesServiceImpl implements UserRolesService { + private static Long ACCOUNT_ADMIN_ROLE_ID = 999L; + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesServiceImpl.class); + + @Autowired + private SessionFactory sessionFactory; + @Autowired + private DataAccessService dataAccessService; + @Autowired + SearchService searchService; + @Autowired + EPAppService appsService; + @Autowired + EPLdapService ldapService; + @Autowired + ApplicationsRestClientService applicationsRestClientService; + @Autowired + EPRoleService epRoleService; + @Autowired + UserProfileService userProfileService; + + @PostConstruct + private void init() { + try { + ACCOUNT_ADMIN_ROLE_ID = Long + .valueOf(SystemProperties.getProperty(EPSystemProperties.ACCOUNT_ADMIN_ROLE_ID)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } + } + + private static HashMap hashMapFromEcompRoles(EcompRole[] ecompRoles) { + HashMap result = new HashMap(); + if (ecompRoles != null) { + for (int i = 0; i < ecompRoles.length; i++) { + if (ecompRoles[i].getId() != null) { + result.put(ecompRoles[i].getId(), ecompRoles[i]); + } + } + } + return result; + } + + private void createLocalUserIfNecessary(String orgUserId) { + if (StringUtils.isEmpty(orgUserId)) { + logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty orgUserId!"); + return; + } + Session localSession = null; + Transaction transaction = null; + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + @SuppressWarnings("unchecked") + List userList = localSession + .createQuery("from " + EPUser.class.getName() + " where org_user_id='" + orgUserId + "'").list(); + if (userList.size() == 0) { + EPUser client = searchService.searchUserByUserId(orgUserId); + if (client == null) { + String msg = "cannot create user " + orgUserId + ", because he cannot be found in phonebook"; + logger.error(EELFLoggerDelegate.errorLogger, msg); + } else { + client.setLoginId(orgUserId); + client.setActive(true); + localSession.save(client); + } + } + transaction.commit(); + } catch (Exception e) { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError); + EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e); + } finally { + EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser"); + } + } + + private static void syncUserRoles(SessionFactory sessionFactory, String orgUserId, Long appId, + EcompRole[] userAppRoles) throws Exception { + HashMap newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles); + boolean result = false; + Session localSession = null; + Transaction transaction = null; + + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + @SuppressWarnings("unchecked") + List userList = localSession + .createQuery("from " + EPUser.class.getName() + " where org_user_id='" + orgUserId + "'").list(); + if (userList.size() > 0) { + EPUser client = userList.get(0); + @SuppressWarnings("unchecked") + List userRoles = localSession.createQuery("from " + EPUserApp.class.getName() + + " where app.id=" + appId + " and userId=" + client.getId()).list(); + for (EPUserApp userRole : userRoles) { + if (!userRole.getRoleId().equals(ACCOUNT_ADMIN_ROLE_ID)) { + + Long userAppRoleId = userRole.getAppRoleId(); + if (!newUserAppRolesMap.containsKey(userAppRoleId)) { + localSession.delete(userRole); + } else { + newUserAppRolesMap.remove(userAppRoleId); + } + } + } + Collection newRolesToAdd = newUserAppRolesMap.values(); + if (newRolesToAdd.size() > 0) { + EPApp app = (EPApp) localSession.get(EPApp.class, appId); + @SuppressWarnings("unchecked") + List roles = localSession + .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list(); + HashMap rolesMap = new HashMap(); + for (EPRole role : roles) { + rolesMap.put(role.getAppRoleId(), role); + } + for (EcompRole userRole : newRolesToAdd) { + EPUserApp userApp = new EPUserApp(); + userApp.setUserId(client.getId()); + userApp.setApp(app); + userApp.setRole(rolesMap.get(userRole.getId())); + localSession.save(userApp); + } + } + } + transaction.commit(); + result = true; + } catch (Exception e) { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError); + EcompPortalUtils.rollbackTransaction(transaction, + "Exception occurred in syncUserRoles, Details: " + EcompPortalUtils.getStackTrace(e)); + } finally { + localSession.close(); + if (!result) { + throw new Exception( + "Exception occurred in syncUserRoles while closing database session for app: '" + appId + "'."); + } + } + } + + // Called when getting the list of roles for the user + private List constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) { + List rolesInAppForUser = new ArrayList(); + + Set userAppRolesMap = new HashSet(); + if (userAppRoles != null) { + for (EcompRole ecompRole : userAppRoles) { + userAppRolesMap.add(ecompRole.getId()); + } + } else { + String message = String + .format("UserRolesServiceImpl.constructRolesInAppForUserGet has received userAppRoles list empty."); + logger.info(EELFLoggerDelegate.errorLogger, message); + } + + if (appRoles != null) { + for (EcompRole ecompRole : appRoles) { + RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName()); + roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId()); + rolesInAppForUser.add(roleForUser); + } + } else { + String message = String + .format("UserRolesServiceImpl.constructRolesInAppForUser has received appRoles list empty."); + logger.info(EELFLoggerDelegate.errorLogger, message); + } + return rolesInAppForUser; + } + + public List getAppRolesForUser(Long appId, String orgUserId) { + List rolesInAppForUser = null; + try { + EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles"); + + // Test this error case, for generating an internal Ecomp Portal + // error + // EcompRole[] appRoles = null; + // If there is an exception in the rest client api, then null will + // be returned. + if (appRoles != null) { + syncAppRoles(sessionFactory, appId, appRoles); + EcompRole[] userAppRoles; + try { + userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId, + String.format("/user/%s/roles", orgUserId)); + if (userAppRoles == null) { + if (EcompPortalUtils.getExternalAppResponseCode() == 400) { + EcompPortalUtils.setExternalAppResponseCode(200); + logger.error(EELFLoggerDelegate.errorLogger, + "400 returned from /user/{userid}/roles, assuming user doesn't exist, app is framework SDK based, and things are ok. Overriding to 200 until framework SDK returns a useful response."); + logger.debug(EELFLoggerDelegate.debugLogger, + "400 returned from /user/{userid}/roles, assuming user doesn't exist, app is framework SDK based, and things are ok. Overriding to 200 until framework SDK returns a useful response."); + } + } + // If the remote application isn't down we MUST to sync user + // roles here in case we have this user here! + syncUserRoles(sessionFactory, orgUserId, appId, userAppRoles); + } catch (Exception e) { + // TODO: we may need to check if user exists, maybe remote + // app is down. + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + logger.error(EELFLoggerDelegate.errorLogger, + "LR: user " + orgUserId + " does not exist in remote application: " + appId + "."); + userAppRoles = new EcompRole[0]; + } + rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles); + // Test this error case, for generating an external app error + // EcompPortalUtils.setResponseCode(404); + } + } catch (Exception e) { + String message = String.format( + "Received an exception while performing getAppRolesForUser for the User %s, and for the AppId %s, Details: %s", + orgUserId, Long.toString(appId), EcompPortalUtils.getStackTrace(e)); + logger.error(EELFLoggerDelegate.errorLogger, message); + } + return rolesInAppForUser; + + } + + // copies of methods in GetAppsWithUserRoleState + private void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception { + logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: " + appId); + HashMap newRolesMap = hashMapFromEcompRoles(appRoles); + boolean result = false; + Session localSession = null; + Transaction transaction = null; + + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + // Attention! All roles from remote application supposed to be + // active! + @SuppressWarnings("unchecked") + List currentAppRoles = localSession + .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list(); + List obsoleteRoles = new ArrayList(); + for (int i = 0; i < currentAppRoles.size(); i++) { + EPRole oldAppRole = currentAppRoles.get(i); + if (oldAppRole.getAppRoleId() != null) { + EcompRole role = null; + role = newRolesMap.get(oldAppRole.getAppRoleId()); + if (role != null) { + if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) { + oldAppRole.setName(role.getName()); + localSession.update(oldAppRole); + } + newRolesMap.remove(oldAppRole.getAppRoleId()); + } else { + obsoleteRoles.add(oldAppRole); + } + } else { + obsoleteRoles.add(oldAppRole); + } + } + Collection newRolesToAdd = newRolesMap.values(); + for (EcompRole role : newRolesToAdd) { + logger.debug(EELFLoggerDelegate.debugLogger, "about to add missing role: " + role.toString()); + EPRole newRole = new EPRole(); + // Attention! All roles from remote application supposed to be + // active! + newRole.setActive(true); + newRole.setName(role.getName()); + newRole.setAppId(appId); + newRole.setAppRoleId(role.getId()); + localSession.save(newRole); + } + if (obsoleteRoles.size() > 0) { + logger.debug(EELFLoggerDelegate.debugLogger, "we have obsolete roles to delete"); + for (EPRole role : obsoleteRoles) { + logger.debug(EELFLoggerDelegate.debugLogger, "obsolete role: " + role.toString()); + Long roleId = role.getId(); + // delete obsolete roles here + // Must delete all records with foreign key constraints on + // fn_role: + // fn_user_role, fn_role_composite, fn_role_function, + // fn_user_pseudo_role, fn_menu_functional_roles. + // And for fn_menu_functional, if no other roles for that + // menu item, remove the url. + + // Delete from fn_user_role + @SuppressWarnings("unchecked") + List userRoles = localSession.createQuery( + "from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId) + .list(); + + logger.debug(EELFLoggerDelegate.debugLogger, "number of userRoles to delete: " + userRoles.size()); + for (EPUserApp userRole : userRoles) { + logger.debug(EELFLoggerDelegate.debugLogger, + "about to delete userRole: " + userRole.toString()); + localSession.delete(userRole); + logger.debug(EELFLoggerDelegate.debugLogger, + "finished deleting userRole: " + userRole.toString()); + } + + // Delete from fn_menu_functional_roles + @SuppressWarnings("unchecked") + List funcMenuRoles = localSession + .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId) + .list(); + int numMenuRoles = funcMenuRoles.size(); + logger.debug(EELFLoggerDelegate.debugLogger, + "number of funcMenuRoles for roleId: " + roleId + ": " + numMenuRoles); + for (FunctionalMenuRole funcMenuRole : funcMenuRoles) { + Long menuId = funcMenuRole.menuId; + // If this is the only role for this menu item, then the + // app and roles will be gone, + // so must null out the url too, to be consistent + @SuppressWarnings("unchecked") + List funcMenuRoles2 = localSession + .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId) + .list(); + int numMenuRoles2 = funcMenuRoles2.size(); + logger.debug(EELFLoggerDelegate.debugLogger, + "number of funcMenuRoles for menuId: " + menuId + ": " + numMenuRoles2); + localSession.delete(funcMenuRole); + if (numMenuRoles2 == 1) { + // If this is the only role for this menu item, then + // the app and roles will be gone, + // so must null out the url too, to be consistent + logger.debug(EELFLoggerDelegate.debugLogger, + "There is exactly 1 menu item for this role, so emptying the url"); + @SuppressWarnings("unchecked") + List funcMenuItems = localSession + .createQuery( + "from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId) + .list(); + if (funcMenuItems.size() > 0) { + logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item"); + FunctionalMenuItem funcMenuItem = funcMenuItems.get(0); + funcMenuItem.url = ""; + localSession.update(funcMenuItem); + } + } + } + + // Delete from fn_role_function + String sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + Query query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Delete from fn_role_composite + sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Delete from fn_user_pseudo_role + sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + logger.debug(EELFLoggerDelegate.debugLogger, "about to delete the role: " + role.toString()); + localSession.delete(role); + logger.debug(EELFLoggerDelegate.debugLogger, "deleted the role"); + } + } + logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction"); + transaction.commit(); + logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction"); + result = true; + } catch (Exception e) { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError); + EcompPortalUtils.rollbackTransaction(transaction, + "Exception occurred in syncAppRoles, Details: " + EcompPortalUtils.getStackTrace(e)); + } finally { + localSession.close(); + if (!result) { + throw new Exception( + "Exception occurred in syncAppRoles while closing database session for app: '" + appId + "'."); + } + } + } + + // Called when updating the list of roles for the user + private RolesInAppForUser constructRolesInAppForUserUpdate(String orgUserId, Long appId, + Set userRolesInRemoteApp) { + RolesInAppForUser result; + result = new RolesInAppForUser(); + result.appId = appId; + result.orgUserId = orgUserId; + for (EcompRole role : userRolesInRemoteApp) { + RoleInAppForUser roleInAppForUser = new RoleInAppForUser(); + roleInAppForUser.roleId = role.getId(); + roleInAppForUser.roleName = role.getName(); + roleInAppForUser.isApplied = new Boolean(true); + result.roles.add(roleInAppForUser); + } + return result; + } + + private EPUser getUserFromRemoteApp(String orgUserId, EPApp app, + ApplicationsRestClientService applicationsRestClientService) throws HTTPException { + EPUser user = applicationsRestClientService.get(EPUser.class, app.getId(), + String.format("/user/%s", orgUserId)); + return user; + } + + private boolean remoteUserShouldBeCreated(List roleInAppForUserList) { + for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { + if (roleInAppForUser.isApplied.booleanValue()) { + return true; + } + } + return false; + } + + private Set postUsersRolesToRemoteApp(List roleInAppForUserList, ObjectMapper mapper, + ApplicationsRestClientService applicationsRestClientService, Long appId, String orgUserId) + throws JsonProcessingException, HTTPException { + Set updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList); + String userRolesAsString = mapper.writeValueAsString(updatedUserRoles); + applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString, + String.format("/user/%s/roles", orgUserId)); + // TODO: We should add code that verifies that the post operation did + // succeed. Because the SDK may still return 200 OK with an html page + // even when it fails! + return updatedUserRoles; + } + + private Set constructUsersEcompRoles(List roleInAppForUserList) { + Set existingUserRoles = new TreeSet(); + for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) { + if (roleInAppForUser.isApplied) { + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(roleInAppForUser.roleId); + ecompRole.setName(roleInAppForUser.roleName); + existingUserRoles.add(ecompRole); + } + } + return existingUserRoles; + } + + private static void createNewUserOnRemoteApp(String orgUserId, EPApp app, + ApplicationsRestClientService applicationsRestClientService, SearchService searchService, + ObjectMapper mapper) throws Exception { + EPUser client = searchService.searchUserByUserId(orgUserId); + if (client == null) { + String msg = "cannot create user " + orgUserId + ", because he/she cannot be found in phonebook."; + logger.error(EELFLoggerDelegate.errorLogger, msg); + throw new Exception(msg); + } + client.setLoginId(orgUserId); + client.setActive(true); + // The remote doesn't care about other apps, and this has caused + // serialization problems - infinite recursion. + client.getEPUserApps().clear(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + String userAsString = mapper.writeValueAsString(client); + logger.debug(EELFLoggerDelegate.debugLogger, + "about to post new client to remote application, users json = " + userAsString); + applicationsRestClientService.post(EPUser.class, app.getId(), userAsString, String.format("/user", orgUserId)); + } + + public String updateRemoteUserProfile(String orgUserId, Long appId) { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + EPUser client = searchService.searchUserByUserId(orgUserId); + EPUser newUser = new EPUser(); + newUser.setActive(client.getActive()); + newUser.setFirstName(client.getFirstName()); + newUser.setLastName(client.getLastName()); + newUser.setLoginId(client.getLoginId()); + newUser.setLoginPwd(client.getLoginPwd()); + newUser.setMiddleInitial(client.getMiddleInitial()); + newUser.setEmail(client.getEmail()); + newUser.setOrgUserId(client.getLoginId()); + try { + String userAsString = mapper.writeValueAsString(newUser); + List appList = appsService.getUserRemoteApps(client.getId().toString()); + // applicationsRestClientService.post(EPUser.class, appId, + // userAsString, String.format("/user", orgUserId)); + for (EPApp eachApp : appList) { + try { + applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString, + String.format("/user/%s", orgUserId)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId() + + " in remote app. appId = " + eachApp.getId()); + } + } + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return "failure"; + } + + return "success"; + + } + + private static final Object syncRests = new Object(); + + @Override + public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) { + boolean result = false; + String orgUserId = ""; + if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) { + orgUserId = newAppRolesForUser.orgUserId.trim(); + } + Long appId = newAppRolesForUser.appId; + List roleInAppForUserList = newAppRolesForUser.appRoles; + if (orgUserId.length() > 0) { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + try { + EPApp app = appsService.getApp(appId); + EPUser remoteAppUser = getUserFromRemoteApp(orgUserId, app, applicationsRestClientService); + if (remoteAppUser == null) { + if (remoteUserShouldBeCreated(roleInAppForUserList)) { + createNewUserOnRemoteApp(orgUserId, app, applicationsRestClientService, searchService, mapper); + // If we succeed, we know that the new user was + // persisted on remote app. + remoteAppUser = getUserFromRemoteApp(orgUserId, app, applicationsRestClientService); + if (remoteAppUser == null) { + logger.error(EELFLoggerDelegate.errorLogger, + "Failed to persist new user: " + orgUserId + " in remote app. appId = " + appId); + // return null; + } + } + } + if (remoteAppUser != null) { + Set userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper, + applicationsRestClientService, appId, orgUserId); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, appId, + userRolesInRemoteApp); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser); + } + } catch (Exception e) { + String message = String.format( + "Failed to create user or update user roles for the User %s, and for the AppId %s, Details: %s", + orgUserId, Long.toString(appId), EcompPortalUtils.getStackTrace(e)); + logger.error(EELFLoggerDelegate.errorLogger, message); + result = false; + } + + } + return result; + } + + // This is for a single app + private boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser) { + boolean result = false; + String orgUserId = rolesInAppForUser.orgUserId; + Long appId = rolesInAppForUser.appId; + synchronized (syncRests) { + if (rolesInAppForUser != null) { + createLocalUserIfNecessary(orgUserId); + } + + if (rolesInAppForUser != null) { + EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.size()]; + for (int i = 0; i < rolesInAppForUser.roles.size(); i++) { + RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i); + EcompRole role = new EcompRole(); + role.setId(roleInAppForUser.roleId); + role.setName(roleInAppForUser.roleName); + userAppRoles[i] = role; + } + try { + syncUserRoles(sessionFactory, orgUserId, appId, userAppRoles); + result = true; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "applyChangesInUserRolesForAppToEcompDB syncUserRoles, orgUserId = " + orgUserId); + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } + } + } + return result; + } + + @Override + public List getUsersFromAppEndpoint(Long appId) throws HTTPException { + RemoteUserWithRoles[] remoteUsers = applicationsRestClientService.get(RemoteUserWithRoles[].class, appId, + "/users"); + ArrayList userApplicationRoles = new ArrayList(); + for (RemoteUserWithRoles remoteUser : remoteUsers) { + UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser); + if(userWithRemoteAppRoles.getRoles()!=null && userWithRemoteAppRoles.getRoles().size()>0) { + userApplicationRoles.add(userWithRemoteAppRoles); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "User " + userWithRemoteAppRoles.getOrgUserId() + + " doesn't have any roles assigned to any app."); + + } + } + + return userApplicationRoles; + } + + private UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) { + UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles(); + userWithRemoteAppRoles.setAppId(appId); + userWithRemoteAppRoles.setOrgUserId(remoteUser.getLoginId()); + userWithRemoteAppRoles.setFirstName(remoteUser.getFirstName()); + userWithRemoteAppRoles.setLastName(remoteUser.getLastName()); + userWithRemoteAppRoles.setRoles(remoteUser.getRoles()); + return userWithRemoteAppRoles; + } + + public static void persistExternalRoleInEcompDb(EPRole externalAppRole, Long appId, EPRoleService roleService) { + externalAppRole.setAppId(appId); + externalAppRole.setAppRoleId(externalAppRole.getId()); + externalAppRole.setId(null); // We will persist a new role, with ecomp + // role id which will be different than + // external app role id. + + roleService.saveRole(externalAppRole); + logger.debug(EELFLoggerDelegate.debugLogger, + String.format("ECOMP persists role from app:%d, app roleId: %d, roleName: %s", appId, + externalAppRole.getAppRoleId(), externalAppRole.getName())); + } + + @Override + public List importRolesFromRemoteApplication(Long appId) throws HTTPException { + EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull"); + List rolesList = Arrays.asList(appRolesFull); + for (EPRole externalAppRole : rolesList) { + + // Try to find an existing extern role for the app in the local + // ecomp DB. If so, then use its id to update the existing external + // application role record. + Long externAppId = externalAppRole.getId(); + EPRole existingAppRole = epRoleService.getRole(appId, externAppId); + if (existingAppRole != null) { + logger.debug(EELFLoggerDelegate.debugLogger, + String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.", + appId, externAppId)); + continue; + } + // persistExternalRoleInEcompDb(externalAppRole, appId, + // roleService); + } + + return rolesList; + } + + @Override + public List getCachedAppRolesForUser(Long appId, Long userId) { + // Find the records for this user-app combo, if any + String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId); + @SuppressWarnings("unchecked") + List roleList = dataAccessService.getList(EPUserApp.class, filter, null, null); + logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}", roleList.size()); + return roleList; + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserService.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserService.java new file mode 100644 index 00000000..bd8949f3 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserService.java @@ -0,0 +1,34 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.openecomp.portalapp.portal.domain.EPUser; + +public interface UserService { + + List getUserByUserId(String orgUserId); + + List getUserByFirstLastName(String firstName, String lastName); + + public String saveNewUser(EPUser newUser, String checkDuplicate) throws Exception; + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserServiceImpl.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserServiceImpl.java new file mode 100644 index 00000000..225f3a7a --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/service/UserServiceImpl.java @@ -0,0 +1,260 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.FusionObject.Utilities; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service("userService") +@Transactional +public class UserServiceImpl implements UserService { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserServiceImpl.class); + + @Autowired + private DataAccessService dataAccessService; + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + @SuppressWarnings("rawtypes") + @Override + public List getUserByUserId(String userId) { + + + if(SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC")){ + List users=new ArrayList(); + List filterdUsers=new ArrayList(); + BufferedReader in = null; + HttpURLConnection con = null; + try{ + String url = EPSystemProperties.getProperty(EPSystemProperties.AUTH_USER_SERVER); + URL obj = new URL(url); + + con = (HttpURLConnection) obj.openConnection(); + + // optional default is GET + con.setRequestMethod("GET"); + con.setConnectTimeout(3000); + con.setReadTimeout(8000); + + StringBuffer response = new StringBuffer(); + + in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); + String inputLine; + while ((inputLine = in.readLine()) != null) + response.append(inputLine); + JSONObject jObject = new JSONObject(response.toString()); // json + JSONArray jsonUsers = jObject.getJSONArray("response"); // get data object + for (int i = 0; i < jsonUsers.length(); i++) { + JSONObject eachObject = jsonUsers.getJSONObject(i); + EPUser eachUser = new EPUser(); + eachUser.setOrgUserId(eachObject.get("id").toString());// getString("id")); + eachUser.setFirstName(eachObject.get("givenName").toString()); + eachUser.setLastName(eachObject.get("familyName").toString()); + eachUser.setEmail(eachObject.get("email").toString()); + users.add(eachUser); + } + + for(int i = 0 ; i < users.size(); i ++){ + + if(Utilities.nvl(userId).length() > 0){ + if(!userId.equalsIgnoreCase(users.get(i).getOrgUserId())){ + continue; + } + } + filterdUsers.add(users.get(i)); + + } + + }catch (Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + }finally{ + try { + in.close(); + con.disconnect(); + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } + } + + return filterdUsers; + + }else{ + + List list = null; + StringBuffer criteria = new StringBuffer(); + criteria.append(" where org_user_id = '").append(userId).append("'"); + list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null); + return (list == null || list.size() == 0) ? null : list; + + } + + } + + @SuppressWarnings("rawtypes") + @Override + public List getUserByFirstLastName(String firstName, String lastName) { + + if(!SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC")){ + + List list = null; + StringBuffer criteria = new StringBuffer(); + if(firstName!=null) + criteria.append(" where first_name = '").append(firstName).append("'"); + if(lastName!=null) + criteria.append(" where last_name = '").append(lastName).append("'"); + list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null); + return (list == null || list.size() == 0) ? null : list; + + }else{ + + List users=new ArrayList(); + List filterdUsers=new ArrayList(); + BufferedReader in = null; + HttpURLConnection con = null; + try{ + String url = EPSystemProperties.getProperty(EPSystemProperties.AUTH_USER_SERVER); + URL obj = new URL(url); + + con = (HttpURLConnection) obj.openConnection(); + + // optional default is GET + con.setRequestMethod("GET"); + con.setConnectTimeout(3000); + con.setReadTimeout(8000); + + StringBuffer response = new StringBuffer(); + + in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); + String inputLine; + while ((inputLine = in.readLine()) != null) + response.append(inputLine); + JSONObject jObject = new JSONObject(response.toString()); // json + JSONArray jsonUsers = jObject.getJSONArray("response"); // get data object + for (int i = 0; i < jsonUsers.length(); i++) { + JSONObject eachObject = jsonUsers.getJSONObject(i); + EPUser eachUser = new EPUser(); + eachUser.setOrgUserId(eachObject.get("id").toString());// getString("id")); + eachUser.setFirstName(eachObject.get("givenName").toString()); + eachUser.setLastName(eachObject.get("familyName").toString()); + eachUser.setEmail(eachObject.get("email").toString()); + users.add(eachUser); + } + + for(int i = 0 ; i < users.size(); i ++){ + + if(Utilities.nvl(firstName).length() > 0){ + if(!firstName.equalsIgnoreCase(users.get(i).getFirstName())){ + continue; + } + } + if(Utilities.nvl(lastName).length() > 0){ + if(!lastName.equalsIgnoreCase(users.get(i).getLastName())){ + continue; + } + } + + + filterdUsers.add(users.get(i)); + + } + + }catch (Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + }finally{ + try { + in.close(); + con.disconnect(); + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + } + } + + return filterdUsers; + } + + } + + public String saveNewUser(EPUser newUser, String checkDuplicate) throws Exception{ + + try{ + + List list = null; + StringBuffer criteria = new StringBuffer(); + criteria.append(" where org_user_id = '").append(newUser.getLoginId()).append("'"); + list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null); + if(list == null || list.size()==0){ + newUser.setActive(true); + newUser.setOrgUserId(newUser.getLoginId()); + newUser.setLoginPwd(CipherUtil.encrypt(newUser.getLoginPwd())); + getDataAccessService().saveDomainObject(newUser, null); + }else{ + if(checkDuplicate.equals("Yes")){ + // userId already exist in database + return "Record already exist"; + }else{ + + EPUser oldUser = (EPUser) list.get(0); + oldUser.setFirstName(newUser.getFirstName()); + oldUser.setLastName(newUser.getLastName()); + oldUser.setMiddleInitial(newUser.getMiddleInitial()); + if(!oldUser.getLoginPwd().equals(newUser.getLoginPwd())) + oldUser.setLoginPwd(CipherUtil.encrypt(newUser.getLoginPwd())); + else + oldUser.setLoginPwd(newUser.getLoginPwd()); + getDataAccessService().saveDomainObject(oldUser, null); + + } + + } + + }catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "", e); + throw new Exception(e); + } + return "success"; + }; + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java new file mode 100644 index 00000000..4c97a52d --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java @@ -0,0 +1,83 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.transport; + +public class OnboardingApp { + + public Long id; + + public String name; + + public String imageUrl; + + public String description; + + public String notes; + + public String url; + + public String alternateUrl; + + public String restUrl; + + public Boolean isOpen; + + public Boolean isEnabled; + + public String username; + + public String appPassword; + + public String thumbnail; + + public String uebTopicName; + + public String uebKey; + + public String uebSecret; + + public Boolean restrictedApp; + + public void normalize() { + this.name = (this.name == null) ? "" : this.name.trim(); + this.username = (this.username == null) ? "" : this.username.trim(); + this.appPassword = (this.appPassword == null) ? "" : this.appPassword.trim(); + } + + public void setUebTopicName(String topicName) { + this.uebTopicName = topicName; + } + + public void setUebKey(String key) { + this.uebKey = key; + } + + public void setUebSecret(String secret) { + this.uebSecret = secret; + } + + // Hide the implementation of restricted and normal app from the front end. + // The json sent and received will include restrictedApp but not appType. + + public void setRestrictedApp(Boolean restrictedApp) { + this.restrictedApp = restrictedApp; + } +} + diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java new file mode 100644 index 00000000..1162cf20 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java @@ -0,0 +1,218 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.ueb; + +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.LinkedList; +import java.util.List; + +import javax.annotation.PostConstruct; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EcompApp; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; +import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; +import org.openecomp.portalapp.portal.service.EPAppService; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties; +import org.openecomp.portalsdk.core.onboarding.ueb.Helper; +import org.openecomp.portalsdk.core.onboarding.ueb.Publisher; +import org.openecomp.portalsdk.core.onboarding.ueb.UebException; +import org.openecomp.portalsdk.core.onboarding.ueb.UebManager; +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +@Component +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +public class EPUebHelper { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUebHelper.class); + + @Autowired + EPAppService appsService; + + + @Autowired + private SessionFactory sessionFactory; + + @SuppressWarnings("unused") + private Publisher epPublisher; + + public EPUebHelper() { + + } + // + // This should only be called by the ECOMP Portal App, other Apps have just one publisher and use appPublisher + // + @SuppressWarnings("unused") + @EPMetricsLog + public void refreshPublisherList() + { + Session localSession = null; + boolean addedPublisher = false; + + try { + localSession = sessionFactory.openSession(); + + List apps = appsService.getEcompAppAppsFullList(); + for (int i = 0; i < apps.size(); i++) + { + if ((apps.get(i).isEnabled()) && + (apps.get(i).getUebTopicName() != null) && + !(apps.get(i).getUebTopicName().toUpperCase().contains("ECOMP-PORTAL-INBOX"))) + { + logger.debug(EELFLoggerDelegate.debugLogger, "UEBManager adding publisher for " + apps.get(i).getUebTopicName()); + UebManager.getInstance().addPublisher(apps.get(i).getUebTopicName()); + addedPublisher = true; + } + else if ((apps.get(i).getId() != 1) && // App may have been disabled, remove the publisher + !(apps.get(i).isEnabled())) + { + if(apps.get(i).getUebTopicName()!=null){ + UebManager.getInstance().removePublisher(apps.get(i).getUebTopicName()); + } + } + } + } + catch (Exception e) + { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeUebSystemError, "add/remove Publisher"); + String stackTrace = EcompPortalUtils.getStackTrace(e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while refreshing the publisher list. Details: " + stackTrace); + } + + //publisherList.print(); + + if (addedPublisher == true) // Give publishers time to initialize + { + Helper.sleep(400); + } + } + + //@PostConstruct + //@EPMetricsLog + public void initUeb() { + try { + epPublisher = new Publisher(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY), + PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME)); + } catch (Exception e) { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeUebConnectionError, e.getMessage()); + String stackTrace = EcompPortalUtils.getStackTrace(e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while initializing the publisher. Details: " + stackTrace); + } + + Thread thread = new Thread("EPUebManager: postConstructMethod - refreshPublisherList") { + public void run(){ + refreshPublisherList(); + } + }; + if (thread != null) { + thread.start(); + } + } + + @EPMetricsLog + public void addPublisher(EPApp app) { + // TODO Auto-generated method stub + try { + UebManager.getInstance().addPublisher(app.getUebTopicName()); + } catch (UebException e) { + String stackTrace = EcompPortalUtils.getStackTrace(e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception while adding a publisher. Details: " + stackTrace); + } + } + + public boolean checkAvailability() { + + // + // Test existence of topic at UEB url + // + // + // + boolean available = true; + LinkedList urlList = Helper.uebUrlList(); + if (!urlList.isEmpty()) { + String url = "http://" + urlList.getFirst() + ":3904/topics/" + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME); + if (!url.isEmpty()) { + try { + URL siteURL = new URL(url); + HttpURLConnection connection = (HttpURLConnection) siteURL.openConnection(); + connection.setRequestMethod("GET"); + connection.connect(); + + int code = connection.getResponseCode(); + if (code == 200) { + available = true; + } + else { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeUebConnectionError, url); + available = false; + logger.warn(EELFLoggerDelegate.errorLogger, "Warning! UEB topic existence check failed, topic = " + url ); + logger.debug(EELFLoggerDelegate.debugLogger, "Warning! UEB topic existence check failed, topic = " + url ); + } + } + catch (Exception e) { + available = false; + String stackTrace = EcompPortalUtils.getStackTrace(e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing the UEB Healthcheck. Details: " + stackTrace); + } + } + } + return available; + } + + public boolean MessageCanBeSentToTopic() { + + boolean sentMsgSuccessfully = false; + + UebMsg msg = new UebMsg(); + msg.putSourceTopicName(PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME)); + msg.putPayload("Pinging topic for health check"); + msg.putMsgType(EPUebMsgTypes.UEB_MSG_TYPE_HEALTH_CHECK); + + try { + // epPublisher.send(msg); + sentMsgSuccessfully = true; + } + catch (Exception e) { + EPLogUtil.logEcompError(EPAppMessagesEnum.BeHealthCheckUebClusterError); + String stackTrace = EcompPortalUtils.getStackTrace(e); + sentMsgSuccessfully = false; + logger.warn(EELFLoggerDelegate.errorLogger, "Warning! could not successfully publish a UEB msg to " + + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME) + " exception : " + stackTrace); + } + + return sentMsgSuccessfully; + } + +} + + diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebMsgTypes.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebMsgTypes.java new file mode 100644 index 00000000..d6eb9eb9 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebMsgTypes.java @@ -0,0 +1,27 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.ueb; + +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsgTypes; + +public interface EPUebMsgTypes extends UebMsgTypes { + + public static final String UEB_MSG_TYPE_HEALTH_CHECK = "uebHealthCheckPing"; +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/utils/EPSystemProperties.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/utils/EPSystemProperties.java new file mode 100644 index 00000000..b187c010 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/utils/EPSystemProperties.java @@ -0,0 +1,42 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.utils; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.context.annotation.PropertySources; + +@Configuration +@PropertySources({ + @PropertySource ("/WEB-INF/conf/system.properties"), + @PropertySource ("/WEB-INF/conf/sql.properties"), + @PropertySource ("/WEB-INF/fusion/conf/fusion.properties"), + @PropertySource (value = "file:${catalina.home}/conf/system.properties", ignoreResourceNotFound = true), + @PropertySource (value = "file:${catalina.home}/conf/fusion.properties", ignoreResourceNotFound = true) + }) + +/** + * Contains properties specific to the ONAP version of the ECOMP Portal. + */ +public class EPSystemProperties extends EPCommonSystemProperties { + public static final String CONTACT_US_URL = "contact_us_link"; + public static final String ECOMP_CONTEXT_ROOT = "context_root"; + +} \ No newline at end of file diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/LogJob.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/LogJob.java new file mode 100644 index 00000000..5b1aa159 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/LogJob.java @@ -0,0 +1,45 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.scheduler; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.quartz.DisallowConcurrentExecution; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; +import org.quartz.PersistJobDataAfterExecution; +import org.springframework.scheduling.quartz.QuartzJobBean; + +@PersistJobDataAfterExecution +@DisallowConcurrentExecution +public class LogJob extends QuartzJobBean { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LogJob.class); + + @Override + protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException { + // JobDataMap dataMap = ctx.getJobDetail().getJobDataMap(); + // int cnt = dataMap.getInt(""); + // JobKey jobKey = ctx.getJobDetail().getKey(); + logger.info(EELFLoggerDelegate.debugLogger, + (Runtime.getRuntime().maxMemory() + " " + Runtime.getRuntime().maxMemory())); + + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/LogRegistry.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/LogRegistry.java new file mode 100644 index 00000000..8d717110 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/LogRegistry.java @@ -0,0 +1,57 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.scheduler; + +import java.text.ParseException; +import java.util.HashMap; +import java.util.Map; + +import org.openecomp.portalsdk.core.scheduler.CronRegistry; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.context.annotation.DependsOn; +import org.springframework.scheduling.quartz.CronTriggerFactoryBean; +import org.springframework.scheduling.quartz.JobDetailFactoryBean; +import org.springframework.stereotype.Component; + +@Component +@DependsOn({ "systemProperties" }) +public class LogRegistry extends CronRegistry { + + private static final String groupName = "AppGroup"; + private static final String jobName = "LogJob"; + private static final String triggerName = "LogTrigger"; + + // @Autowired + // private SystemProperties systemProperties; + + // @Bean + public JobDetailFactoryBean jobDetailFactoryBean() { + Map map = new HashMap(); + map.put("units", "bytes"); + return jobDetailFactoryBean(groupName, jobName, LogJob.class, map); + } + + // @Bean + public CronTriggerFactoryBean cronTriggerFactoryBean() throws ParseException { + // "0 * * * * ? * + return cronTriggerFactoryBean(groupName, triggerName, SystemProperties.getProperty(SystemProperties.LOG_CRON)); + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/Register.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/Register.java new file mode 100644 index 00000000..43e0d818 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/Register.java @@ -0,0 +1,86 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.scheduler; + +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.scheduler.Registerable; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.quartz.Trigger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.DependsOn; +import org.springframework.stereotype.Component; + +@Component +@DependsOn({"logRegistry", "sessionMgtRegistry", "systemProperties"}) +public class Register implements Registerable { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(Register.class); + + private List scheduleTriggers = new ArrayList(); + Trigger trigger[] = new Trigger[0]; + + @Autowired + private LogRegistry logRegistry; + + @Autowired + private SessionMgtRegistry sessionMgtRegistry; + + @Override + public Trigger[] getTriggers() { + return getScheduleTriggers().toArray(trigger); + } + + @Override + public void registerTriggers() { + // if the property value is not available; the cron will not be added + // and can be ignored. its safe to ignore the exceptions + try { + if (SystemProperties.getProperty(SystemProperties.LOG_CRON) != null) + getScheduleTriggers().add(logRegistry.getTrigger()); + + } catch (IllegalStateException ies) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(ies)); + logger.info(EELFLoggerDelegate.debugLogger, ("Log Cron not available")); + } + + try { + if(SystemProperties.getProperty(SystemProperties.SESSIONTIMEOUT_FEED_CRON) != null) + getScheduleTriggers().add(sessionMgtRegistry.getTrigger()); + + } catch(IllegalStateException ies) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(ies)); + logger.info(EELFLoggerDelegate.debugLogger, ("Session Cron not available")); + } + + } + + public List getScheduleTriggers() { + return scheduleTriggers; + } + + public void setScheduleTriggers(List scheduleTriggers) { + this.scheduleTriggers = scheduleTriggers; + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/RegistryAdapter.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/RegistryAdapter.java new file mode 100644 index 00000000..1d2d8071 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/RegistryAdapter.java @@ -0,0 +1,100 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.scheduler; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.openecomp.portalsdk.core.scheduler.Registerable; +import org.openecomp.portalsdk.workflow.services.WorkflowScheduleService; +import org.quartz.Trigger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.quartz.SchedulerFactoryBean; +import org.springframework.stereotype.Component; + +/** + * TODO REFACTOR moved from org.openecomp.portalsdk.core.scheduler to + * org.openecomp.portalapp.scheduler + * + */ +@Component +public class RegistryAdapter { + + @Autowired + private Registerable registry; + + @Autowired + private WorkflowScheduleService workflowScheduleService; + + private SchedulerFactoryBean schedulerBean; + + Trigger trigger[] = new Trigger[0]; + + public Trigger[] getTriggers() { + + registry.registerTriggers(); + + List allTriggers = new ArrayList(); + + List coreTriggers = addCoreTriggers(); + final Trigger[] extTriggerArray = registry.getTriggers(); + + allTriggers.addAll(Arrays.asList(extTriggerArray)); + allTriggers.addAll(coreTriggers); + + return allTriggers.toArray(trigger); + + } + + public List addCoreTriggers() { + // On startup of the application after crash recovery, invoke workflow + // schedule trigger + List triggers = getWorkflowScheduleService().triggerWorkflowScheduling(); + return triggers; + } + + public void setSchedulerBean(SchedulerFactoryBean _schedulerBean) { + schedulerBean = _schedulerBean; + + } + + public SchedulerFactoryBean getSchedulerBean() { + return schedulerBean; + + } + + public Registerable getRegistry() { + return registry; + } + + public void setRegistry(Registerable registry) { + this.registry = registry; + } + + public WorkflowScheduleService getWorkflowScheduleService() { + return workflowScheduleService; + } + + public void setWorkflowScheduleService(WorkflowScheduleService workflowScheduleService) { + this.workflowScheduleService = workflowScheduleService; + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/SessionMgtRegistry.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/SessionMgtRegistry.java new file mode 100644 index 00000000..315618e9 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/scheduler/SessionMgtRegistry.java @@ -0,0 +1,89 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.scheduler; + +import java.text.ParseException; +import java.util.HashMap; +import java.util.Map; + +import org.openecomp.portalapp.portal.listener.UserSessionListener; +import org.openecomp.portalapp.service.sessionmgt.TimeoutHandler; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.scheduler.CronRegistry; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.annotation.DependsOn; +import org.springframework.scheduling.quartz.CronTriggerFactoryBean; +import org.springframework.scheduling.quartz.JobDetailFactoryBean; +import org.springframework.stereotype.Component; + +/** + * Extra depends-on annotation tells Spring that the system properties object + * will be used in the constructor. + */ +@Component +// @DependsOn({ "manageService", "epAppService", "systemProperties" }) +@DependsOn({ "systemProperties" }) +public class SessionMgtRegistry extends CronRegistry implements ApplicationContextAware { + + EELFLoggerDelegate logger = null; + + private static final String groupName = "AppGroup"; + private static final String jobName = "PortalSessionTimeoutFeedJob"; + private static final String triggerName = "PortalSessionTimeoutFeedTrigger"; + + // Not strictly necessary, but preparing for the day + // when the getProperty method is not static. + @Autowired + private SystemProperties systemProperties; + + private ApplicationContext applicationContext; + + public JobDetailFactoryBean jobDetailFactoryBean() { + logger = EELFLoggerDelegate.getLogger(SessionMgtRegistry.class); + Map map = new HashMap(); + return jobDetailFactoryBean(groupName, jobName, TimeoutHandler.class, map); + } + + @SuppressWarnings("static-access") + public CronTriggerFactoryBean cronTriggerFactoryBean() throws ParseException { + logger = EELFLoggerDelegate.getLogger(SessionMgtRegistry.class); + String property = "* * * * * ? 2099"; + try { + property = systemProperties.getProperty(SystemProperties.SESSIONTIMEOUT_FEED_CRON); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "Failed to retrieve " + SystemProperties.SESSIONTIMEOUT_FEED_CRON + ", defaulting to " + property, + e); + } + return cronTriggerFactoryBean(groupName, triggerName, property); + } + + @Override + public void setApplicationContext(ApplicationContext _applicationContext) throws BeansException { + applicationContext = _applicationContext; + TimeoutHandler.setApplicationContext(applicationContext); + UserSessionListener.setApplicationContext(_applicationContext); + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/service/RemoteWebServiceCallServiceImpl.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/service/RemoteWebServiceCallServiceImpl.java new file mode 100644 index 00000000..c07d1093 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/service/RemoteWebServiceCallServiceImpl.java @@ -0,0 +1,104 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.service; + +import java.util.List; + +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.service.AppsCacheService; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.service.WebServiceCallServiceImpl; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service("remoteWebServiceCallService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +public class RemoteWebServiceCallServiceImpl extends WebServiceCallServiceImpl implements RemoteWebServiceCallService { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RemoteWebServiceCallServiceImpl.class); + @Autowired + AppsCacheService appCacheService; + + /* + * (non-Javadoc) + * @see org.openecomp.portalapp.service.sessionmgt.RemoteWebServiceCallService#verifyRESTCredential(java.lang.String, java.lang.String, java.lang.String, java.lang.String) + */ + public boolean verifyRESTCredential(String secretKey, String requestUebKey, String requestAppName, + String requestPassword) throws Exception { + EPApp appRecord = findEpApp(requestUebKey); + if (appRecord == null) { + logger.warn(EELFLoggerDelegate.errorLogger, "Failed to find application with UEB key " + requestUebKey); + return false; + } + + String encryptedPwdDB = appRecord.getAppPassword(); + String appUserName = appRecord.getUsername(); + String decryptedPwd = CipherUtil.decrypt(encryptedPwdDB, + secretKey == null ? SystemProperties.getProperty(SystemProperties.Decryption_Key) : secretKey); + if (decryptedPwd.equals(requestPassword) && appUserName.equals(requestAppName)) + return true; + else + return false; + } + + /** + * currently this method only validates the application key to fetch the application + */ + public boolean verifyAppKeyCredential(String requestUebKey) throws Exception { + String failMessage = "Failed to find application with UEB key " + requestUebKey; + if(requestUebKey == null || requestUebKey.equals("")) { + logger.warn(EELFLoggerDelegate.errorLogger, failMessage); + return false; + } + + EPApp appRecord = findEpApp(requestUebKey); + if (appRecord == null) { + logger.warn(EELFLoggerDelegate.errorLogger, failMessage); + return false; + } + + return true; + } + + /** + * Searches the FN_APP table for the specified UEB key. + * + * @return EPApp object if the key is found; else null. + */ + public EPApp findEpApp(String uebKey) { + List list = null; + StringBuffer criteria = new StringBuffer(); + criteria.append(" where ueb_key = '" + uebKey + "'"); + list = getDataAccessService().getList(EPApp.class, criteria.toString(), null, null); + return (list == null || list.size() == 0) ? null : (EPApp) list.get(0); + } + + public static void main(String args[]) throws Exception { + String decryptedPwd = CipherUtil.decrypt("okYTaDrhzibcbGVq5mjkVQ==", "AGLDdG4D04BKm2IxIWEr8o=="); + System.out.print(decryptedPwd); + } + +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/FunctionalMenuHandler.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/FunctionalMenuHandler.java new file mode 100644 index 00000000..0a360500 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/FunctionalMenuHandler.java @@ -0,0 +1,126 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.uebhandler; + +import java.util.List; + +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.FunctionalMenuService; +import org.openecomp.portalapp.portal.service.SearchService; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItem; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.ueb.UebException; +import org.openecomp.portalsdk.core.onboarding.ueb.UebManager; +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import com.google.gson.Gson; + +@Component +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class FunctionalMenuHandler { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FunctionalMenuHandler.class); + + @Autowired + AdminRolesService adminRolesService; + + @Autowired + FunctionalMenuService functionalMenuService; + + @Autowired + SearchService searchSvc; + + @Autowired + DataAccessService dataAccessService; + + @Async + public Boolean getFunctionalMenu(UebMsg requestMsg) + { + UebMsg returnMsg = new UebMsg(); + + if (requestMsg == null) + { + logger.error(EELFLoggerDelegate.errorLogger, "handleMenuRequest received null message"); + return false; + } + else if (requestMsg.getSourceTopicName() == null) + { + logger.error(EELFLoggerDelegate.errorLogger, "A source topic name is required and not found in this msg:" + requestMsg.toString()); + return false; + } + else if (requestMsg.getUserId() == null) + { + logger.debug(EELFLoggerDelegate.debugLogger, "Error getting functional menu. A userId is required and not found in this msg: " + requestMsg.toString()); + returnMsg.putMsgId(requestMsg.getMsgId()); // echo tells requester this is a response + returnMsg.putPayload("Error: A userId is required. Call msg.putUserId() with an userId"); + } + else + { + logger.debug(EELFLoggerDelegate.debugLogger, "Getting functional menu for user = " + requestMsg.getUserId()); + EPUser user = searchSvc.searchUserByUserId(requestMsg.getUserId()); + + List menuItems = null; + if (user == null) + { + logger.debug(EELFLoggerDelegate.debugLogger, "Error getting functional menu. userId not found in directory or is guest: " + requestMsg.toString()); + } + else if (adminRolesService.isSuperAdmin(user)) + { + logger.debug(EELFLoggerDelegate.debugLogger, "FunctionalMenuHandler: SuperUser, about to call getFunctionalMenuItems()"); + menuItems = functionalMenuService.getFunctionalMenuItems(); + } + else + { + logger.debug(EELFLoggerDelegate.debugLogger, "getMenuItemsForAuthUser: about to call getFunctionalMenuItemsForUser()"); + menuItems = functionalMenuService.getFunctionalMenuItemsForUser(requestMsg.getUserId()); + } + + if ( menuItems != null ) + { + String functionalMenuJsonString = new Gson().toJson(menuItems); + logger.debug(EELFLoggerDelegate.debugLogger, "returning functional menu : " + functionalMenuJsonString); + returnMsg.putMsgId(requestMsg.getMsgId()); // echo tells requester this is a response + returnMsg.putPayload(functionalMenuJsonString); + } else { + returnMsg.putMsgId(requestMsg.getMsgId()); // echo tells requester this is a response + returnMsg.putPayload("Error: Not found for userId = " + requestMsg.getUserId()); + } + } + + try { + UebManager.getInstance().publishReplyEP(returnMsg, requestMsg.getSourceTopicName()); + } catch (UebException e) { + logger.error(EELFLoggerDelegate.errorLogger, "UebException occurred while responding to the Ueb message, Details:" + EcompPortalUtils.getStackTrace(e)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while responding to the Ueb message, Details:" + EcompPortalUtils.getStackTrace(e)); + } + + return true; + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/InitUebHandler.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/InitUebHandler.java new file mode 100644 index 00000000..2ba27549 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/InitUebHandler.java @@ -0,0 +1,75 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.uebhandler; + +import java.util.concurrent.ConcurrentLinkedQueue; + +import javax.annotation.PostConstruct; + +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties; +import org.openecomp.portalsdk.core.onboarding.ueb.UebManager; +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; + +// +// Adding this class for the sole purpose of insuring that the MainUebHandler really +// honors @Async and kicks off a thread. For more info google @Async and read about +// @Async only working if called from different class. +// +//@Configuration +//@EnableAspectJAutoProxy +//@EPMetricsLog +public class InitUebHandler { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(InitUebHandler.class); + + //@Autowired + MainUebHandler mainUebHandler; + + public InitUebHandler() { + + } + + //@PostConstruct + public void initUeb() { + + try { + String enableListenerThread = PortalApiProperties.getProperty(PortalApiConstants.UEB_LISTENERS_ENABLE); + if (enableListenerThread.equalsIgnoreCase("true")) { + ConcurrentLinkedQueue inboxQueue = new ConcurrentLinkedQueue(); + UebManager.getInstance().initListener(inboxQueue); + mainUebHandler.runHandler(inboxQueue); + logger.info(EELFLoggerDelegate.errorLogger, "Returned from initiating mainUebHandler..."); + } + else { + logger.info(EELFLoggerDelegate.errorLogger, "Not starting UEB listening thread because ueb_listeners_enable is not set to true in the properties file."); + } + } + catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + logger.info(EELFLoggerDelegate.errorLogger, "Not starting UEB listening thread because property could not be read " + PortalApiConstants.UEB_LISTENERS_ENABLE + e.getMessage()); + } + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/MainUebHandler.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/MainUebHandler.java new file mode 100644 index 00000000..5edf04b4 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/MainUebHandler.java @@ -0,0 +1,115 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.uebhandler; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.concurrent.ConcurrentLinkedQueue; + +import org.openecomp.portalapp.portal.ueb.EPUebMsgTypes; +import org.openecomp.portalapp.portal.utils.EPSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg; +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsgTypes; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import com.att.eelf.configuration.Configuration; + + +//------------------------------------------------------------------------- +// Listens for received UEB messages and handles the messages +// +// Note: To implement a synchronous reply call getMsgId on the request +// and putMsgId on the reply (echoing the request MsgId). +// +//------------------------------------------------------------------------- +@Component("MainUebHandler") +public class MainUebHandler +{ + final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MainUebHandler.class); + + ConcurrentLinkedQueue inboxQueue = null; + + @Autowired + FunctionalMenuHandler funcMenuHandler; + + @Autowired + WidgetNotificationHandler widgetNotificationHandler; + + @Async + public void runHandler(ConcurrentLinkedQueue queue) + { + inboxQueue = queue; + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "==> MainUebHandler started"); + while (true) + { + UebMsg msg = null; + while ((msg = inboxQueue.poll()) != null) + { + if ((msg.getMsgType() != null) && (!msg.getMsgType().equalsIgnoreCase(EPUebMsgTypes.UEB_MSG_TYPE_HEALTH_CHECK))) + { + // TODO: switch this back to debug + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== Received UEB message : " + msg.toString()); + logger.info(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== Received UEB message : " + msg.toString()); + MDC.put(EPSystemProperties.PARTNER_NAME, msg.getSourceTopicName()); + MDC.put(Configuration.MDC_SERVICE_NAME, msg.getMsgType().toString()); + switch(msg.getMsgType()) + { + case UebMsgTypes.UEB_MSG_TYPE_GET_FUNC_MENU: + { + funcMenuHandler.getFunctionalMenu(msg); + break; + } + case UebMsgTypes.UEB_MSG_TYPE_WIDGET_NOTIFICATION: + { + widgetNotificationHandler.handleWidgetNotification(msg); + break; + } + default: + { + logger.info(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "Unknown UEB message type " + msg.toString()); + break; + } + } + } + } + + if (Thread.interrupted()) + { + logger.info(EELFLoggerDelegate.errorLogger, "==> UebMainHandler exiting"); + break; + } + + try { + Thread.sleep(10); + } catch (InterruptedException e) { + logger.error(EELFLoggerDelegate.errorLogger, "UebMainHandler interrupted during sleep" + EcompPortalUtils.getStackTrace(e)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred during sleep" + EcompPortalUtils.getStackTrace(e)); + } + } + } +} diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/WidgetNotificationHandler.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/WidgetNotificationHandler.java new file mode 100644 index 00000000..e6f3089c --- /dev/null +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/uebhandler/WidgetNotificationHandler.java @@ -0,0 +1,93 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.uebhandler; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.service.EPAppService; +import org.openecomp.portalapp.portal.service.SearchService; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.ueb.UebException; +import org.openecomp.portalsdk.core.onboarding.ueb.UebManager; +import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +@Component +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPMetricsLog +public class WidgetNotificationHandler { + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetNotificationHandler.class); + + final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + @Autowired + EPAppService appSvc; + + @Autowired + SearchService searchSvc; + + + public WidgetNotificationHandler() + { + } + + @Async + public void handleWidgetNotification(UebMsg requestMsg) + { + if (requestMsg.getUserId() != null) { + logger.debug(EELFLoggerDelegate.debugLogger, "handleWidgetNotification: getting widgets/apps for user = " + requestMsg.getUserId()); + EPUser user = searchSvc.searchUserByUserId(requestMsg.getUserId()); + if (user != null && (appSvc != null)) { + logger.debug(EELFLoggerDelegate.debugLogger, "Debug mytag: " + appSvc); + List apps = appSvc.getUserApps(user); + for (EPApp app : apps) { + if (app.getUebTopicName() != null) { + UebMsg widgetMsg = new UebMsg(); + widgetMsg.putSourceTopicName(app.getUebTopicName()); + logger.debug(EELFLoggerDelegate.debugLogger, "app.getUebTopicName was invoked"); + widgetMsg.putPayload(requestMsg.getPayload()); + try { + logger.debug(EELFLoggerDelegate.debugLogger, "Sending widget notification from " + requestMsg.getSourceTopicName() + " to " + app.getUebTopicName()); + UebManager.getInstance().publishEP(widgetMsg, app.getUebTopicName()); + } catch (UebException e) { + logger.error(EELFLoggerDelegate.errorLogger, "handleWidgetNotification publishEP exception" + EcompPortalUtils.getStackTrace(e)); + } + } + } + } else { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "handleWidgetNotification: user " + + requestMsg.getUserId() + " not found" + " source = " + requestMsg.getSourceTopicName() + + ". This widget notification cannot be posted to other widgets"); + } + } + } + +} diff --git a/ecomp-portal-BE-os/src/main/resources/cache.ccf b/ecomp-portal-BE-os/src/main/resources/cache.ccf new file mode 100644 index 00000000..6f5c6f92 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/resources/cache.ccf @@ -0,0 +1,30 @@ +# DEFAULT CACHE REGION +jcs.default=DC +jcs.default.cacheattributes=org.apache.jcs.engine.CompositeCacheAttributes +jcs.default.cacheattributes.MaxObjects=1000 +jcs.default.cacheattributes.MemoryCacheName=org.apache.jcs.engine.memory.lru.LRUMemoryCache +jcs.default.elementattributes=org.apache.jcs.engine.ElementAttributes +jcs.default.elementattributes.IsEternal=true +jcs.default.elementattributes.IsSpool=true + + +# MEMORY SHRINKING CONFIGURATION (Commented) +#jcs.default.cacheattributes.UseMemoryShrinker=true +#jcs.default.cacheattributes.MaxMemoryIdleTimeSeconds=3600 +#jcs.default.cacheattributes.ShrinkerIntervalSeconds=60 +#jcs.default.cacheattributes.MaxSpoolPerRun=500 +#jcs.default.elementattributes=org.apache.jcs.engine.ElementAttributes +#jcs.default.elementattributes.IsEternal=false + + +# AUXILLARY CACHE CONFIGURATION +jcs.auxiliary.DC=org.apache.jcs.auxiliary.disk.indexed.IndexedDiskCacheFactory +jcs.auxiliary.DC.attributes=org.apache.jcs.auxiliary.disk.indexed.IndexedDiskCacheAttributes +jcs.auxiliary.DC.attributes.DiskPath=c:/projects/fusion/war/WEB-INF/cache + + +# PRE-DEFINED REGION FOR LOOKUP DATA +jcs.region.lookUpObjectCache=DC +jcs.region.lookUpObjectCache.cacheattributes=org.apache.jcs.engine.CompositeCacheAttributes +jcs.region.lookUpObjectCache.cacheattributes.MaxObjects=4000 +jcs.region.lookUpObjectCache.cacheattributes.MemoryCacheName=org.apache.jcs.engine.memory.lru.LRUMemoryCache diff --git a/ecomp-portal-BE-os/src/main/resources/logback.xml b/ecomp-portal-BE-os/src/main/resources/logback.xml new file mode 100644 index 00000000..0c0d7647 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/resources/logback.xml @@ -0,0 +1,285 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ${applicationLoggerPattern} + + + + + + + + + + + + ${logDirectory}/${generalLogName}.log + + + ${logDirectory}/${generalLogName}.log.%d{yyyy-MM-dd}.zip + + 30 + + + ${applicationLoggerPattern} + + + + + + 256 + + true + + + + + + + + + + + + + + + + + + + ${logDirectory}/${auditLogName}.log + + + ${logDirectory}/${auditLogName}.log.%d{yyyy-MM-dd}.zip + + 30 + + + ${auditLoggerPattern} + + + + 256 + + + + + ${logDirectory}/${metricsLogName}.log + + + ${logDirectory}/${metricsLogName}.log.%d{yyyy-MM-dd}.zip + + 30 + + + ${metricsLoggerPattern} + + + + + + 256 + + + + + ${logDirectory}/${errorLogName}.log + + + ${logDirectory}/${errorLogName}.log.%d{yyyy-MM-dd}.zip + + 30 + + + ${errorLoggerPattern} + + + + + 256 + + + + + ${debugLogDirectory}/${debugLogName}.log + + + ${logDirectory}/${debugLogName}.log.%d{yyyy-MM-dd}.zip + + 30 + + + ${defaultLoggerPattern} + + + + + 256 + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ecomp-portal-BE-os/src/main/resources/openid-connect.properties b/ecomp-portal-BE-os/src/main/resources/openid-connect.properties new file mode 100644 index 00000000..79d3b9b4 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/resources/openid-connect.properties @@ -0,0 +1,22 @@ +### +# ================================================================================ +# eCOMP Portal +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file 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. +# ================================================================================ +### +authentication_server_url = http://localhost:8383/openid-connect-server-webapp/ +ecomp_openid_connect_client = http://localhost:8080/ecompportal/openid_connect_login +ecomp_redirect_uri = http://localhost:8080/ecompportal/welcome.htm diff --git a/ecomp-portal-BE-os/src/main/resources/openid-keystore.jwks b/ecomp-portal-BE-os/src/main/resources/openid-keystore.jwks new file mode 100644 index 00000000..caad4aaa --- /dev/null +++ b/ecomp-portal-BE-os/src/main/resources/openid-keystore.jwks @@ -0,0 +1,12 @@ +{ + "keys": [ + { + "alg": "RSA256", + "d": "GIW2b3-ig8rk-Pm3cD5VqRSxtKBJfNhuBCSNe1N6-_kGrk3M5MWgqEbJCzdoZz8M8fclE8sV11b9_-iQx2iVjaw77gHsGe-IUucSNEeW2VtvbpvgCklw-B3CathBMOuHzqCbafj-J6zJ9uxGUFhgUKkLWZJ1iSuIw7WfKoBx_jU", + "e": "AQAB", + "n": "qYJqXTXsDroPYyQBBmSolK3bJtrSerEm-nrmbSpfn8Rz3y3oXLydvUqj8869PkcEzoJIY5Xf7xDN1Co_qyT9qge-3C6DEwGVHXOwRoXRGQ_h50Vsh60MB5MIuDN188EeZnQ30dtCTBB9KDTSEA2DunplhwLCq4xphnMNUaeHdEk", + "kty": "RSA", + "kid": "rsa1" + } + ] +} diff --git a/ecomp-portal-BE-os/src/main/resources/portal.properties b/ecomp-portal-BE-os/src/main/resources/portal.properties new file mode 100644 index 00000000..a1982632 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/resources/portal.properties @@ -0,0 +1,44 @@ +### +# ================================================================================ +# eCOMP Portal +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file 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. +# ================================================================================ +### +portal.api.impl.class = org.openecomp.portalsdk.core.onboarding.client.OnBoardingApiServiceImpl +portal.api.prefix = /api +max.idle.time = 5 +user.attribute.name = user_attribute + +# Global Log On for single sign on +ecomp_redirect_url = https://localhost:8080/ecompportal/login.htm + +testing=testing + +# URL of the ECOMP Portal REST API +ecomp_rest_url = http://localhost:8080/ecompportal/auxapi + +ueb_listeners_enable = true + +ueb_app_key = EkrqsjQqZt4ZrPh6 +ueb_app_secret = KDwJDKdiVVkaz6gIBlRbyxbk +ueb_app_mailbox_name = ECOMP-PORTAL-INBOX-DEV-LOCAL + +ueb_url_list = todo_ueb_url +ecomp_portal_inbox_name = ECOMP-PORTAL-INBOX-DEV-LOCAL + +# Consumer group name for UEB topic. +# Use the special tag to generate a unique one for each sdk-app server. +ueb_app_consumer_group_name = {UUID} diff --git a/ecomp-portal-BE-os/src/main/webapp/META-INF/MANIFEST.MF b/ecomp-portal-BE-os/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 00000000..254272e1 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/cache.ccf b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/cache.ccf new file mode 100644 index 00000000..b8a2363d --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/cache.ccf @@ -0,0 +1,30 @@ +# DEFAULT CACHE REGION +jcs.default=DC +jcs.default.cacheattributes=org.apache.jcs.engine.CompositeCacheAttributes +jcs.default.cacheattributes.MaxObjects=1000 +jcs.default.cacheattributes.MemoryCacheName=org.apache.jcs.engine.memory.lru.LRUMemoryCache +jcs.default.elementattributes=org.apache.jcs.engine.ElementAttributes +jcs.default.elementattributes.IsEternal=true +jcs.default.elementattributes.IsSpool=true + + +# MEMORY SHRINKING CONFIGURATION (Commented) +#jcs.default.cacheattributes.UseMemoryShrinker=true +#jcs.default.cacheattributes.MaxMemoryIdleTimeSeconds=3600 +#jcs.default.cacheattributes.ShrinkerIntervalSeconds=60 +#jcs.default.cacheattributes.MaxSpoolPerRun=500 +#jcs.default.elementattributes=org.apache.jcs.engine.ElementAttributes +#jcs.default.elementattributes.IsEternal=false + + +# AUXILLARY CACHE CONFIGURATION +jcs.auxiliary.DC=org.apache.jcs.auxiliary.disk.indexed.IndexedDiskCacheFactory +jcs.auxiliary.DC.attributes=org.apache.jcs.auxiliary.disk.indexed.IndexedDiskCacheAttributes +jcs.auxiliary.DC.attributes.DiskPath=fusion/cache + + +# PRE-DEFINED REGION FOR LOOKUP DATA +jcs.region.lookUpObjectCache=DC +jcs.region.lookUpObjectCache.cacheattributes=org.apache.jcs.engine.CompositeCacheAttributes +jcs.region.lookUpObjectCache.cacheattributes.MaxObjects=4000 +jcs.region.lookUpObjectCache.cacheattributes.MemoryCacheName=org.apache.jcs.engine.memory.lru.LRUMemoryCache diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/quartz.properties b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/quartz.properties new file mode 100644 index 00000000..f95f469f --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/quartz.properties @@ -0,0 +1,55 @@ +### +# ================================================================================ +# eCOMP Portal +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file 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. +# ================================================================================ +### +################################################################################# +# Quartz configurations for Quantum Work Flow # +################################################################################# + +org.quartz.scheduler.instanceId = AUTO + +################################################################################# +# Main configurations +org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool +org.quartz.threadPool.threadCount = 30 + +============================================================================ +# Configure JobStore +#============================================================================ + +org.quartz.jobStore.misfireThreshold = 60000 + +org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX +org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate +org.quartz.jobStore.useProperties = false +#org.quartz.jobStore.dataSource = myDS +org.quartz.jobStore.tablePrefix = FN_QZ_ + +org.quartz.jobStore.isClustered = true +org.quartz.jobStore.clusterCheckinInterval = 20000 + +#============================================================================ +# Configure Datasources +#============================================================================ + +#org.quartz.dataSource.myDS.driver = com.mysql.jdbc.Driver +#org.quartz.dataSource.myDS.URL = jdbc:mysql://localhost:3306/portal +#org.quartz.dataSource.myDS.user = todo +#org.quartz.dataSource.myDS.password = todo +#org.quartz.dataSource.myDS.maxConnections = 5 +#org.quartz.dataSource.myDS.validationQuery=select 0 from dual diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/raptor.properties b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/raptor.properties new file mode 100644 index 00000000..0c32ef65 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/raptor.properties @@ -0,0 +1,185 @@ +### +# ================================================================================ +# eCOMP Portal +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file 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. +# ================================================================================ +### +##C## Mention the name of the framework. At present RAPTOR supports FUSION +system=fusion +##C## Determines the priority for the debug message. +debug_level=5 +##C## Determines the number of records can be downloaded in excel when you select "download all" option. +download_limit=65000 +csv_download_limit=10 +##C## Determines the number of records to be displayed in a single page. +default_page_size=50 +##C## Determines the list size in the form field. +form_fields_list_size=99000 +##C## Determines the scheduler interval +#scheduler_interval=0 => disabled +scheduler_interval=0 +##C## System Name +system_name=RAPTOR +##C## This is used for Bread crumbs. +base_title=ANALYSIS +##C## whether to allow SQL-based report definition (security risk); super users are always allowed to create SQL-based reports +allow_sql_based_reports=no +##C## Determines whether to include disclaimer page at the bottom of each screen +show_disclaimer=yes +disclaimer_positioned_top_in_csvexcel=yes +##C## Determines whether to display the form page as a separate page before running the report +display_form_before_run=yes +##C## Determines whether to include the form page on the report data page +include_form_with_data=yes +##C## Determines whether to cache chart data in the session => faster re-display if the data volume does not get too large +cache_chart_data=yes +##C## Determines whether to cache report data for the currently displayed page in the session => faster re-display + ##C## if the data volume does not get too large +cache_cur_page_data=yes +##C## Determines Chart width +default_chart_width=700 +##C## Determines Chart height +default_chart_height=420 +##C## Determines whether to permit report deletion only by report owner or by everyone with "write" access +delete_only_by_owner=yes +##C## Determines whether to log each report execution and update time and user ID +enable_report_log=yes +##C## Determines whether to cache user roles info in memory (saves many DB reads, but does not account for roles + ##C## assigned after the cache was loaded) +cache_user_roles=yes +##C## Determines whether to convert month formats (e.g. MM/YYYY) to the last day of the month (true) or + ##C## first day (false) - like 12/2003 is converted to either 12/31/2003 or 12/01/2003 +month_format_use_last_day=no +##C## Determines whether to print the report title in the download files +print_title_in_download=yes +##C## Determines whether to show report description when the report is run and in the quick links +show_descr_at_runtime=no +##C## Determines whether to skip labels on the Line chart axis when they overlap +#DEPRECATED skip_chart_labels_to_fit=no +##C## Determines whether to show chart types that are purpose and/or data specific +show_nonstandard_charts=yes +##C## Determines whether to allow the user to change the chart type at runtime +allow_runtime_chart_sel=yes +##C## Determines whether to display the report title as chart title as well +display_chart_title=yes +##C## Determines whether to merge/blank multi-level row headings in cross-tab report +merge_crosstab_row_headings=yes +##C## Determines whether to display chart when displaying the report at first or just a "Show Chart" button +display_chart_by_default=yes +##C## Determines whether to print the form field values in the download files +print_params_in_download=yes +##C## Determines the limitation to the characters in chart label. +skip_chart_labels_limit=30 +##C## Determines whether to users with read-only rights for a report can copy it +can_copy_on_read_only=yes +##C## Determines the no of decimals to be displayed in Totals column +#max_decimals_on_totals=-1 => don't truncate, display all decimal digits +max_decimals_on_totals=2 +##C## Determines which JFreeChart to use. +jfree_version=latest +#jfree_version=0.9.11 +# Added this restriction so that heavily used system which contain +# more than 1000 users can enable this feature not to display whole +# users in the drop down menu +display_all_users=yes +##Sheet name +sheet_name=raptor +#shell_script_name=/home/sundar/test.sh +#download_query_folder=/titan/PROJECT3/RAPTOR/raptor/dwnld/query/ +## this directory is mentioned if the flat file is downloaded using shell script +shell_script_dir=/titan/PROJECT3/RAPTOR/raptor/dwnld/ +flat_file_lower_limit=1 +flat_file_upper_limit=200000 +## whatever request mentioned here would be parsed in sql and request parameter would be filled +request_get_params=c_master,isEmbedded +print_footer_in_download=yes +## footer mentioned here appears in downloaded excel +footer_first_line=AT&T Proprietary +footer_second_line=Use Pursuant to Company Instructions +## to run report in popup window +report_in_popup_window=yes +## to run each report in new popup window if the above is selected +popup_in_new_window=yes +## "Yes" allows the request param to be passed to the drill down report +pass_request_param_in_drilldown=yes +## Show PDF download icon +show_pdf_download=yes +# Show Folder Tree +show_folder_tree=no +#Show folder tree only for Admin Users +show_folder_tree_only_to_admin_users=no +#folder tree should be minimized +folder_tree_minimized=yes +## whatever session mentioned here would be parsed in sql and session parameter would be filled +session_params=login_id +display_formfield_info=yes +customize_formfield_info=yes +#schedule limit for end users +schedule_limit=10 +# customized query if you need any restrictions for schedule and security tab for fusion +#schedule_custom_query_for_users=getAllUsersByCustomer +#schedule_custom_query_for_roles=getAllRolesByCustomer +# customized query if you need any restrictions for schedule and security tab for prisms example +#schedule_custom_query_for_users=SELECT au.user_id, au.first_name||' '||au.last_name user_name FROM app_user au order by 2 +schedule_custom_query_for_users=SELECT au.user_id id, au.first_name||' '||au.last_name name FROM app_user au where user_id = 1 order by 2 +#schedule_custom_query_for_roles=SELECT ar.role_id, ar.descr role_name FROM app_role ar order by 2 +schedule_date_pattern=MM/dd/yyyy hh:mm:ss a +## This is used to display in right format in chart timestamp axis as we give in the sql +#chart_yearly_format=yyyy +#chart_monthly_format=MMM-yyyy +#chart_daily_format=MM-dd-yyyy +chart_hourly_format=MM/dd HH +#chart_minute_format=HH:mm +chart_minute_format=MM-dd-yyyy-HH:mm +#chart_second_format=HH:mm:ss +chart_second_format=MM-dd-yyyy +#chart_millisecond_format=HH:mm:ss.S +schedule_help_text=This form is used to schedule a specific Reporting Platform report to be delivered to one or more email addresses associated with your Company's Business Direct user logins. Note that report output delivered via email does not include the capability to drill down/back up to additional data levels. So, select the appropriate data level report for the scheduled report. View the status of scheduled report requests in the My Schedules menu item. +use_loginid_in_schedYN=Y +session_params_for_scheduling=login_id +session_date_formfield_auto_incr=yes +display_session_param_pdfexcel=login_id;Login Id +session_params_for_displaying_in_scheduling=login_id;Login Id +application_server=tomcat +#gmap properties +gmap_key=ABQIAAAAToJSSetKBMjBJx8MiRw4ghQiU0SbbKnm8C5eu25cpyLwgkLzyRShrQTbgZtqnKAqZU9JwcSq1bKwiA +PROJECT-FOLDER=/Users/sundar/git/st_quantum/quantum/target/quantum-1.0 +# +MARKET-SHAPEFILE-FOLDER=resources/files +# output folder for files generated on server side +OUTPUT-FOLDER=resources/temp +# tile size in pixel +TILE-SIZE=256 +#check if map is disabled or not +map_allowed=Y +max_drilldown_level=2 +admin_role_equiv_to_super_role=N +show_loading_during_formfield_chain=Y +show_print_icon=N +globally_nowrap=N +calendar_output_date_format=MM/dd/yyyy +memory_threshold_percentage=99 +print_params_in_csv_download=yes +notitle_in_dashboard=yes +generate_store_sched_reports=yes +show_excel_2007_download=yes +print_excel_in_landscape=yes +show_animated_chart_option=yes +show_animated_chart_only=no +adjust_content_based_on_height=yes +custom_submit_button_text=Run Button +customize_formfield_layout=yes +db_type=postgresql diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/raptor_app_fusion.properties b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/raptor_app_fusion.properties new file mode 100644 index 00000000..09fe0cec --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/raptor_app_fusion.properties @@ -0,0 +1,36 @@ +### +# ================================================================================ +# eCOMP Portal +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file 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. +# ================================================================================ +### +temp_folder_path=/Users/sundar/git/st_quantum/quantum/target/quantum-1.0/temp/ +upload_folder_path=/Users/sundar/git/st_quantum/quantum/target/quantum-1.0/files/ +excel_template_path=/Users/sundar/git/st_quantum/quantum/target/quantum-1.0/files/raptor_template/ +temp_folder_url=temp/ +upload_folder_url=upload/ +smtp_server=todo_url +default_email_sender=dev-local@email.com +error_page=error_page.jsp +jsp_context_path=raptor/ +img_folder_url=static/fusion/raptor/images/ +base_folder_url=static/fusion/raptor/ +direct_access_url=http://localhost:8080/quantum/raptor_email_attachment.htm?action=raptor&source_page=report_run&display_content=y +base_action_url=raptor.htm?action= +base_action_param=c_master= +super_role_id=1 +admin_role_ids=1 +quick_links_menu_ids=HOME,CUSTOMER,REPORTS diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/raptor_db_fusion.properties b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/raptor_db_fusion.properties new file mode 100644 index 00000000..497fa16d --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/raptor_db_fusion.properties @@ -0,0 +1,19 @@ +### +# ================================================================================ +# eCOMP Portal +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file 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. +# ================================================================================ +### diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/raptor_pdf.properties b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/raptor_pdf.properties new file mode 100644 index 00000000..548cf3bf --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/raptor_pdf.properties @@ -0,0 +1,49 @@ +### +# ================================================================================ +# eCOMP Portal +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file 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. +# ================================================================================ +### +## pdf file specific properties +pdf_data_font_size=9 +pdf_data_font_family=Arial +#reduce the font size from html config +pdf_data_font_size_offset=2 +pdf_data_alternate_color=true +#data row background(white), alternate(light light blue/gray) +pdf_data_background_alternate_hex_code=#EDEDED +pdf_data_default_background_hex_code=#FFFFFF +#header font (white) background (gray) +pdf_data_table_header_font_hex_code=#FFFFFF +pdf_data_table_header_background_hex_code=#8A9BB3 +#footer header +pdf_footer_font_size=9 +pdf_footer_font_family=Arial +pdf_att_proprietary=xxxx +pdf_att_proprierary_font_size=7 +pdf_date_timezone=GMT +pdf_date_pattern=MM/dd/yyyy hh:mm:ss a +##page number position at 1 - footer middle, 0 -- header right, 2 - both +pdf_page_number_position=1 +pdf_word_before_page_number=Page +pdf_word_after_page_number= +pdf_coverpage_firstcolumn_size=0.3 +pdf_image_auto_rotate=false +display_create_owner_info=true +#session_info=customer,customerId +display_loginid_for_downloaded_by=false +# please use false if you want landscape to be default. +is_default_orientation_portrait=true diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/sql.properties b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/sql.properties new file mode 100644 index 00000000..954330d3 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/sql.properties @@ -0,0 +1,295 @@ +### +# ================================================================================ +# eCOMP Portal +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file 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. +# ================================================================================ +### +#SQL Statements for PostgreSQL + +#ReportLoader.java + +load.custom.report.xml = SELECT cr.report_xml FROM cr_report cr WHERE rep_id=?::int + +db.update.report.xml = SELECT cr.rep_id, cr.report_xml FROM cr_report cr WHERE rep_id=? FOR UPDATE + +update.custom.report.rec = UPDATE cr_report SET title='[Utils.oracleSafe(rw.getReportName())]', descr='[Utils.oracleSafe(rw.getReportDescr())]', public_yn='[(rw.isPublic()]', menu_id='[rw.getMenuID()]', menu_approved_yn='[(rw.isMenuApproved()]', owner_id=[rw.getOwnerID()], maint_id=[rw.getUpdateID()], maint_date=TO_DATE('[rw.getUpdateDate()]', '[Globals.getOracleTimeFormat()]'), dashboard_type_yn='[(rw.isDashboardType()]', dashboard_yn= '[(rw.getReportType().equals(AppConstants.RT_DASHBOARD)]' WHERE rep_id = [rw.getReportID()] + +is.report.already.scheduled = select rep_id from cr_report_schedule where rep_id = ?::int + +create.custom.report.rec = INSERT INTO cr_report(rep_id, title, descr, public_yn, menu_id, menu_approved_yn, report_xml, owner_id, create_id, create_date, maint_id, maint_date, dashboard_type_yn, dashboard_yn, folder_id) VALUES([rw.getReportID()], '[Utils.oracleSafe(rw.getReportName())]', '[Utils.oracleSafe(rw.getReportDescr())]', '[rw.isPublic()]', '[rw.getMenuID()]', '[rw.isMenuApproved()]', '', [rw.getOwnerID()], [rw.getCreateID()], TO_DATE('[rw.getCreateDate()]', '[Globals.getOracleTimeFormat()]'), [rw.getUpdateID()], TO_DATE('[rw.getUpdateDate()]', '[Globals.getOracleTimeFormat()]'), '[rw.isDashboardType()]', '[rw.getReportType().equals(AppConstants.RT_DASHBOARD)]',[rw.getFolderId()]) + +get.user.report.names = SELECT cr.rep_id, cr.title FROM cr_report cr WHERE coalesce(cr.owner_id, cr.create_id) = [userID] + +get.report.owner.id = SELECT coalesce(cr.owner_id, cr.create_id) AS owner FROM cr_report cr WHERE rep_id = ?::int + +delete.report.record.log = DELETE FROM cr_report_log WHERE rep_id = [reportID] + +delete.report.record.users = DELETE FROM cr_report_schedule_users WHERE rep_id = [reportID] + +delete.report.record.schedule = DELETE FROM cr_report_schedule WHERE rep_id = [reportID] + +delete.report.record.access = DELETE FROM cr_report_access WHERE rep_id = [reportID] + +delete.report.record.email = DELETE FROM cr_report_email_sent_log WHERE rep_id = [reportID] + +delete.report.record.favorite = DELETE FROM cr_favorite_reports WHERE rep_id = [reportID] + +delete.report.record.report = DELETE FROM cr_report WHERE rep_id = [reportID] + +load.quick.links = SELECT cr.rep_id, cr.title, cr.descr FROM (SELECT rep_id, MIN(read_only_yn) read_only_yn FROM ((SELECT ua.rep_id, ua.read_only_yn FROM cr_report_access ua WHERE ua.user_id = [userID]) UNION ALL (SELECT ra.rep_id, ra.read_only_yn FROM cr_report_access ra WHERE ra.role_id IN ([roleList.toString()]))) report_access GROUP BY rep_id) ra LEFT JOIN cr_report cr ON cr.rep_id = ra.rep_id WHERE cr.menu_id LIKE '%[nvls(menuId)]%' AND cr.menu_approved_yn = 'Y' AND (coalesce(cr.owner_id, cr.create_id) = [userID] OR cr.public_yn = 'Y' OR ra.read_only_yn IS NOT NULL) ORDER BY cr.title + +load.folder.reports = SELECT cr.rep_id, cr.rep_id report_id, [rep_title_sql] || CASE WHEN cr.public_yn = 'Y' THEN '' ELSE '[PRIVATE_ICON]' END||cr.title||'' title, cr.descr, au.first_name||' '||au.last_name owner_name, TO_CHAR(cr.create_date, 'MM/DD/YYYY') create_date, CASE WHEN coalesce(cr.owner_id, cr.create_id) = [userID] THEN 'N' ELSE coalesce(ra.read_only_yn, 'Y') END read_only_yn, CASE WHEN coalesce(cr.owner_id, cr.create_id) = [userID] THEN 'Y' ELSE 'N' END user_is_owner_yn FROM cr_report cr JOIN app_user au ON coalesce(cr.owner_id, cr.create_id) = au.user_id AND cr.folder_id= '[folderId]' LEFT JOIN (SELECT rep_id, MIN(read_only_yn) read_only_yn FROM ((SELECT ua.rep_id, ua.read_only_yn FROM cr_report_access ua WHERE ua.user_id = [userID]) UNION ALL(SELECT ra.rep_id, ra.read_only_yn FROM cr_report_access ra WHERE ra.role_id IN ([roleList.toString()]))) report_access GROUP BY rep_id) ra ON cr.rep_id = ra.rep_id +#If roleList.toString() is '' PostgreSQL returns an error - needs to be null instead of empty + +load.folder.reports.user = AND coalesce(cr.owner_id, cr.create_id) = [userID] + +load.folder.reports.publicsql = AND (coalesce(cr.owner_id, cr.create_id) = [userID] OR cr.public_yn = 'Y' OR ra.read_only_yn IS NOT NULL) + +load.quick.download.links = SELECT a.file_name, b.title,to_char(a.dwnld_start_time, 'Dy DD-Mon-YYYY HH24:MI:SS') as time, a.dwnld_start_time FROM cr_report_dwnld_log a, cr_report b where a.user_id = [userID] and a.rep_id = b.rep_id and (a.dwnld_start_time) >= to_date(to_char(now()- interval '1 day', 'mm/dd/yyyy'), 'mm/dd/yyyy') and a.record_ready_time is not null order by a.dwnld_start_time + +load.reports.to.schedule = SELECT cr.rep_id, Initcap(cr.title), cr.descr FROM cr_report cr LEFT OUTER JOIN (SELECT rep_id, MIN(read_only_yn) read_only_yn FROM ((SELECT ua.rep_id, ua.read_only_yn FROM cr_report_access ua WHERE ua.user_id = [userID]) UNION ALL (SELECT ra.rep_id, ra.read_only_yn FROM cr_report_access ra WHERE ra.role_id IN ([roleList.toString()]))) report_access GROUP BY rep_id) ra ON cr.rep_id = ra.rep_id AND (cr.public_yn = 'Y' OR ra.read_only_yn IS NOT NULL or cr.owner_id = [userID] )ORDER BY Initcap(cr.title) + +load.reports.to.add.in.dashboard = SELECT cr.rep_id, cr.title, cr.descr FROM cr_report cr LEFT OUTER JOIN (SELECT rep_id, MIN(read_only_yn) read_only_yn FROM ((SELECT ua.rep_id, ua.read_only_yn FROM cr_report_access ua WHERE ua.user_id = [userID]) UNION ALL (SELECT ra.rep_id, ra.read_only_yn FROM cr_report_access ra WHERE ra.role_id IN ([roleList.toString()]))) report_access GROUP BY rep_id) ra ON cr.rep_id = ra.rep_id AND (coalesce(cr.owner_id, cr.create_id) = [userID] OR cr.public_yn = 'Y' OR ra.read_only_yn IS NOT NULL) AND (cr.dashboard_yn = 'N' or cr.dashboard_yn is null) ORDER BY cr.title + +load.my.recent.links = select rep_id, title, descr, form_fields from ( select row_number() OVER () AS rnum, rep_id, title, descr, form_fields from (select cr.rep_id, cr.title, a.form_fields, cr.descr, a.log_time, a.user_id, a.action, a.action_value from cr_report_log a, cr_report cr where user_id = [userID] AND action = 'Report Execution Time' and a.rep_id = cr.rep_id order by log_time desc) AS x) AS y where rnum <= 6 AND rnum >= 1 + +create.report.log.entry = INSERT INTO cr_report_log (rep_id, log_time, user_id, action, action_value, form_fields) VALUES([reportID], now(), [userID], '[action]' , '[executionTime]', '[form_fields]') + +create.report.log.entry.exec.time = INSERT INTO cr_report_log (rep_id, log_time, user_id, action, action_value, form_fields) VALUES([reportID], now()+'1 second', [userID], '[action]' , '[executionTime]', '[formFields]') + +clear.report.log.entries = DELETE FROM cr_report_log WHERE rep_id = ? and user_id = ? + +load.report.log.entries = SELECT x.log_time, x.user_id, (CASE WHEN x.action = 'Report Execution Time' THEN ''||x.action||'' ELSE x.action END) action, (CASE WHEN x.action = 'Report Execution Time' THEN action_value ELSE 'N/A' END) time_taken, (CASE WHEN x.action = 'Report Execution Time' THEN '\"Run' ELSE 'N/A' END) run_image, x.name FROM (SELECT rl.rep_id, TO_CHAR(rl.log_time, 'Month DD, YYYY HH:MI:SS AM') log_time, rl.action_value, fuser.last_name ||', '||fuser.first_name name, rl.user_id, rl.action, rl.form_fields FROM cr_report_log rl, fn_user fuser WHERE rl.rep_id = [nvls(reportId)] and rl.action != 'Report Run' and fuser.user_id = rl.user_id ORDER BY rl.log_time DESC) x WHERE LIMIT 100 + +does.user.can.schedule.report = select crs.sched_user_id, count(*) from cr_report_schedule crs where sched_user_id = [userId] group by crs.sched_user_id having count(*) >= [Globals.getScheduleLimit()] + +does.user.can.schedule = select crs.schedule_id from cr_report_schedule crs where schedule_id = [scheduleId] + +get.system.date.time = select to_char(now(),'MM/dd/yyyy HH24:mi:ss') + +get.next.day.date.time = select to_char(now()+'1 day','MM/dd/yyyy HH24:mi:ss') + +get.next.fifteen.minutes.date.time = select to_char(now()+'15 min','MM/dd/yyyy HH24:mi:ss') + +get.next.thirty.minutes.date.time = select to_char(now()+'30 min','MM/dd/yyyy HH24:mi:ss') + +get.template.file = select template_file from cr_report_template_map where report_id = [reportId] + +load.pdf.img.lookup = select image_id, image_loc from cr_raptor_pdf_img + +load.action.img.lookup = select image_id, image_loc from cr_raptor_action_img + + +#ActionHandler.java + +report.values.map.def.a = SELECT x FROM (SELECT DISTINCT + +report.values.map.def.b = TO_CHAR([colName], '[nvl(displayFormat, AppConstants.DEFAULT_DATE_FORMAT)]') + +report.values.map.def.c = [colName] + +report.values.map.def.d = x FROM [rdef.getTableById(tableId).getTableName()] WHERE [colName] IS NOT NULL ORDER BY 1) xx LIMIT <= [Globals.getDefaultPageSize()] + +test.sched.cond.popup = SELECT 1 WHERE EXISTS ([sql]) + +download.all.email.sent = Select user_id, rep_id from CR_REPORT_EMAIL_SENT_LOG where gen_key='[pdfAttachmentKey.trim()]' and log_id =[report_email_sent_log_id.trim()] and (now() - sent_date) < '1 day' limit 1 + +download.all.gen.key = select schedule_id from cr_report_email_sent_log u where U.GEN_KEY = '[pdfAttachmentKey]' + +download.all.retrieve = SELECT au.user_id FROM (SELECT rs.schedule_id, rs.rep_id FROM cr_report_schedule rs WHERE rs.enabled_yn='Y' AND rs.run_date IS NOT NULL AND rs.schedule_id = [scheduleId]) x, cr_report r, app_user au WHERE x.rep_id = r.rep_id AND au.user_id IN (SELECT rsu.user_id FROM cr_report_schedule_users rsu WHERE rsu.schedule_id = x.schedule_id and rsu.schedule_id = [scheduleId] UNION SELECT ur.user_id FROM fn_user_role ur WHERE ur.role_id IN (SELECT rsu2.role_id FROM cr_report_schedule_users rsu2 WHERE rsu2.schedule_id = x.schedule_id and rsu2.schedule_id = [scheduleId])) + +download.all.insert = insert into cr_report_dwnld_log (user_id,rep_id,file_name,dwnld_start_time,filter_params) values (?,?,?,?,?) + +#ReportWrapper.java + +report.wrapper.format = SELECT coalesce(cr.owner_id, cr.create_id) owner_id, cr.create_id, TO_CHAR(cr.create_date, '[Globals.getOracleTimeFormat()]') create_date, maint_id, TO_CHAR(cr.maint_date, '[Globals.getOracleTimeFormat()]') update_date, cr.menu_id, cr.menu_approved_yn FROM cr_report cr WHERE cr.rep_id= [reportID] + +generate.subset.sql = SELECT [colNames.toString()] FROM (SELECT row_number() OVER () AS rnum, [colNames.toString()] FROM ([reportSQL]) AS x ) AS y + +report.sql.only.first.part = SELECT row_number() OVER () AS rnum, [colNames.toString()] FROM (SELECT row_number() OVER () AS rnum, [colNames.toString()] FROM ( + +report.sql.only.second.part.a = WHERE rnum <= [endRow] + +report.sql.only.second.part.b = AND rnum >= [startRow] ORDER BY rnum + +report.sql.only.second.part.b.noorderby = AND rnum >= [startRow] + +generate.sql.visual.select = SELECT + +generate.sql.visual.count = COUNT(*) cnt + +generate.sql.visual.dual = +#No DUAL table in PostgreSQL so this is blank + +#ReportRuntime.java + +load.crosstab.report.data = SELECT row_number() OVER () AS rnum, [colNames.toString()] FROM ( [reportSQL] + +#RaptorRunHandler.java + +generate.sql.handler = SELECT row_number() OVER () AS rnum, x.* from ([sql]) AS x LIMIT 2 + +generate.sql.select = SELECT [colNames.toString()] FROM (SELECT row_number() OVER () AS rnum, [colNames.toString()] FROM ([sql]) AS y) AS x + +#ReportSchedule.java + +load.schedule.data = SELECT rs.enabled_yn, TO_CHAR(rs.start_date, 'MM/DD/YYYY') start_date, TO_CHAR(rs.end_date, 'MM/DD/YYYY') end_date, TO_CHAR(rs.run_date, 'MM/DD/YYYY') run_date, coalesce(TO_CHAR(rs.run_date, 'HH'), '12') run_hour, coalesce(TO_CHAR(rs.run_date, 'MI'), '00') run_min, coalesce(TO_CHAR(rs.run_date, 'AM'), 'AM') run_ampm, rs.recurrence, rs.conditional_yn, rs.notify_type, rs.max_row, rs.initial_formfields, rs.schedule_id, coalesce(TO_CHAR(rs.end_date, 'HH'), '11') end_hour, coalesce(TO_CHAR(rs.end_date, 'MI'), '45') end_min, coalesce(TO_CHAR(rs.end_date, 'AM'), 'PM') end_ampm, encrypt_yn, attachment_yn FROM cr_report_schedule rs WHERE rs.rep_id = [reportID] + +load.schedule.getid = SELECT rsu.user_id, fuser.last_name||', '||fuser.first_name, fuser.login_id FROM cr_report_schedule_users rsu, fn_user fuser WHERE rsu.rep_id = [reportID] AND rsu.schedule_id = [getScheduleID()] and rsu.user_id IS NOT NULL and rsu.user_id = fuser.user_id + +load.schedule.users = SELECT rsu.role_id FROM cr_report_schedule_users rsu WHERE rsu.rep_id = [reportID] AND rsu.schedule_id = [getScheduleID()] AND rsu.role_id IS NOT NULL + +new.schedule.data = SELECT nextval('SEQ_CR_REPORT_SCHEDULE') AS sequence + +execute.update = DELETE FROM cr_report_schedule_users WHERE rep_id = [reportID] and schedule_id = [getScheduleID()] + +execute.update.users = INSERT INTO cr_report_schedule_users (schedule_id, rep_id, user_id, role_id, order_no) VALUES([getScheduleID()], [reportID], [emailToUsers.get(i)).getId()], NULL, [(i + 1)]) + +execute.update.roles = INSERT INTO cr_report_schedule_users (schedule_id, rep_id, user_id, role_id, order_no) VALUES([getScheduleID()], [reportID], NULL, [emailToRoles.get(i)).getId()], [((emailToUsers.size() + i + 1)]) + +execute.update.activity = INSERT into cr_schedule_activity_log (schedule_id, notes, run_time) values ([getScheduleID()],'Submitted:Schedule',TO_DATE('[getRunDate()] [getRunHour()]:[getRunMin()] [getRunAMPM()]', 'MM/DD/YYYY HH:MI AM')) + +delete.schedule.data = SELECT 1 FROM cr_report_schedule WHERE rep_id = [reportID] and sched_user_id = [getScheduleUserID()] and schedule_id = [getScheduleID()] + +delete.schedule.data.users = DELETE FROM cr_report_schedule_users WHERE rep_id = [reportID] and schedule_id = [getScheduleID()] + +delete.schedule.data.id = DELETE FROM cr_report_schedule where rep_id = [reportID] and sched_user_id = [getScheduleUserID()] and schedule_id = [getScheduleID()] + +load.cond.sql = SELECT condition_large_sql FROM cr_report_schedule WHERE schedule_id=?::int + +load.cond.sql.select = SELECT condition_sql FROM cr_report_schedule WHERE schedule_id = [scheduleId] + +persist.cond.sql.update = update cr_report_schedule set condition_large_sql = '' where schedule_id = [scheduleId] +#EMPTY CLOB() changed to '' + +persist.cond.sql.large = SELECT condition_large_sql FROM cr_report_schedule cr WHERE schedule_id=? FOR UPDATE + +persist.cond.sql.set = update cr_report_schedule set condition_sql = ? where schedule_id = [scheduleId] + +#DataCache.java + +get.data.view.actions = SELECT ts.web_view_action FROM cr_table_source ts WHERE ts.web_view_action IS NOT NULL + +get.public.report.id.names = SELECT rep_id, title FROM cr_report WHERE public_yn = 'Y' ORDER BY title + +get.private.accessible.names.a = SELECT cr.rep_id, cr.title FROM cr_report cr WHERE cr.rep_id not in (select rep_id from cr_report_access cra where user_id = '[user_id]' + +get.private.accessible.names.if = OR role_id in ( + +get.private.accessible.names.b = ) AND public_yn = 'N' and cr.owner_id = '[user_id]' order by 2 + +get.group.accessible.names.a = SELECT cr.rep_id, cr.title FROM cr_report cr WHERE cr.rep_id in (select rep_id from cr_report_access cra where user_id = '[user_id]' + +get.group.accessible.names.b = ) AND public_yn = 'N' order by 2 + +get.report.table.sources.a = SELECT table_name, display_name, pk_fields, web_view_action, large_data_source_yn, filter_sql FROM cr_table_source + +get.report.table.sources.where = where SOURCE_DB= '[dBInfo]' + +get.report.table.sources.if = where SOURCE_DB is null or SOURCE_DB = '[AppConstants.DB_LOCAL]' + +get.report.table.sources.else = ORDER BY table_name + +grab.report.table.a = SELECT ts.table_name, ts.display_name, ts.pk_fields, ts.web_view_action, ts.large_data_source_yn, ts.filter_sql FROM cr_table_source ts WHERE + +grab.report.table.if = ts.SOURCE_DB= '[dBInfo]' + +grab.report.table.else = (ts.SOURCE_DB is null or ts.SOURCE_DB = '[AppConstants.DB_LOCAL]') + +grab.report.table.b = except SELECT ts.table_name, ts.display_name, ts.pk_fields, ts.web_view_action, ts.large_data_source_yn, ts.filter_sql from cr_table_source ts where table_name in (select table_name from cr_table_role where role_id not IN [sb.toString()]) and + +grab.report.table.c = ORDER BY 1 + +get.report.table.crjoin = SELECT src_table_name, dest_table_name, join_expr FROM cr_table_join + +get.report.table.joins = SELECT tj.src_table_name, tj.dest_table_name, tj.join_expr FROM cr_table_join tj WHERE ((EXISTS (SELECT 1 FROM cr_table_role trs WHERE trs.table_name=tj.src_table_name AND trs.role_id IN [sb.toString()])) OR (NOT EXISTS (SELECT 1 FROM cr_table_role trs WHERE trs.table_name=tj.src_table_name))) AND ((EXISTS (SELECT 1 FROM cr_table_role trd WHERE trd.table_name=tj.dest_table_name AND trd.role_id IN [sb.toString()])) OR (NOT EXISTS (SELECT 1 FROM cr_table_role trd WHERE trd.table_name=tj.dest_table_name))) + +generate.report.table.col = SELECT a.table_name, a.column_name, a.data_type, a.label FROM user_column_def a WHERE a.table_name = '[tableName.toUpperCase()]' ORDER BY a.column_id + +generate.db.user.sql.a = SELECT utc.table_name, utc.column_name, utc.data_type, + +generate.db.user.sql.if = utc.column_name FROM user_tab_columns utc + +generate.db.user.sql.else = coalesce(x.label, utc.column_name) FROM user_tab_columns utc + +generate.db.user.sql.b = WHERE utc.table_name = '[tableName.toUpperCase()]' + +generate.db.user.sql.c = AND utc.table_name = x.table_name AND utc.column_name = x.column_name + +generate.db.user.sql.d = ORDER BY utc.column_id + +#SearchHandler.java + +load.report.search.result = SELECT cr.rep_id, cr.rep_id report_id, [rep_title_sql] || CASE WHEN cr.public_yn = 'Y' THEN '' ELSE '[PRIVATE_ICON]' END || cr.title ||'' title, cr.descr, au.first_name||' '||au.last_name owner_name, TO_CHAR(cr.create_date, 'MM/DD/YYYY') create_date, CASE WHEN coalesce(cr.owner_id, cr.create_id) = [userID] THEN 'N' ELSE coalesce(ra.read_only_yn, 'Y') END read_only_yn, CASE WHEN coalesce(cr.owner_id, cr.create_id) = [userID] THEN 'Y' ELSE 'N' END user_is_owner_yn, case when report_xml like '%N%' then 'N' when report_xml like '%Y%' or 1 = (select distinct 1 from cr_report_schedule where rep_id = cr.rep_id) then 'Y' else 'N' end FROM cr_report cr JOIN fn_user au ON coalesce (cr.owner_id, cr.create_id) = au.user_id AND TO_CHAR(cr.rep_id, 'FM99999999') like coalesce('%[fReportID]%', TO_CHAR(cr.rep_id, 'FM99999999')) AND UPPER(cr.title) LIKE UPPER('%[fReportName]%') LEFT JOIN(SELECT rep_id, MIN(read_only_yn) read_only_yn FROM ((SELECT ua.rep_id, ua.read_only_yn FROM cr_report_access ua WHERE ua.user_id = [userID]) UNION ALL (SELECT ra.rep_id, ra.read_only_yn FROM cr_report_access ra WHERE ra.role_id IN ([roleList.toString()]))) report_access GROUP BY rep_id) ra ON ra.rep_id = cr.rep_id + +load.report.search.instr = WHERE cr.menu_id LIKE '%[menuId]%' + +load.report.search.result.user = WHERE coalesce(cr.owner_id, cr.create_id) = [userID] + +load.report.search.result.public = WHERE (coalesce(cr.owner_id, cr.create_id) = [userID] OR cr.public_yn = 'Y' OR ra.read_only_yn IS NOT NULL) + +load.report.search.result.fav = WHERE cr.rep_id in (select rep_id from cr_favorite_reports where user_id = [userID] + +load.report.search.result.sort = ORDER BY CASE coalesce(cr.owner_id, cr.create_id) WHEN [userID] THEN ' ' WHEN 'upper(au.first_name||' '||au.last_name)' ELSE 'upper(cr.title)' END + +load.folder.report.result = SELECT cr.rep_id, cr.rep_id report_id, [rep_title_sql] || CASE WHEN cr.public_yn = 'Y' THEN '' ELSE '[PRIVATE_ICON]' END || cr.title || '' title, cr.descr, au.first_name||' '||au.last_name owner_name, TO_CHAR(cr.create_date, 'MM/DD/YYYY') create_date, CASE WHEN coalesce(cr.owner_id, cr.create_id) = [userID] THEN 'N' ELSE coalesce(ra.read_only_yn, 'Y') END read_only_yn, CASE WHEN coalesce(cr.owner_id, cr.create_id) = [userID] THEN 'Y' ELSE 'N' END user_is_owner_yn FROM cr_report cr JOIN fn_user au ON coalesce (cr.owner_id, cr.create_id) = au.user_id AND TO_CHAR(cr.rep_id, 'FM99999999') like coalesce('%[fReportID]%', TO_CHAR(cr.rep_id, 'FM99999999')) AND UPPER(cr.title) LIKE UPPER('%[fReportName]%') LEFT JOIN(SELECT rep_id, MIN(read_only_yn) read_only_yn FROM ((SELECT ua.rep_id, ua.read_only_yn FROM cr_report_access ua WHERE ua.user_id = [userID]) UNION ALL (SELECT ra.rep_id, ra.read_only_yn FROM cr_report_access ra WHERE ra.role_id IN ([roleList.toString()]))) report_access GROUP BY rep_id) ra ON ra.rep_id = cr.rep_id + +load.folder.report.result.sort = ORDER BY CASE coalesce(cr.owner_id, cr.create_id) WHEN [userID] THEN ' ' WHEN '(au.first_name||' '||au.last_name)' ELSE 'cr.title' END + +#WizardProcessor.java + +process.filter.add.edit = '[argValue]' + +#ReportDefinition.java + +persist.report.adhoc = SELECT nextval('[Globals.getAdhocReportSequence()]') AS sequence + +#Globals.java + +initialize.roles = SELECT 1 WHERE EXISTS (SELECT 1 FROM cr_table_role) + +initialize.version = SELECT cr_raptor.get_version + +# scheduler + + +scheduler.available.schedules = SELECT x.rep_id, x.schedule_id, x.conditional_yn, x.condition_large_sql, x.notify_type, x.max_row, x.initial_formfields, x.processed_formfields, r.title, x.user_id FROM ( SELECT rs.rep_id, rs.schedule_id, rs.sched_user_id user_id, rs.conditional_yn, rs.condition_large_sql, rs.notify_type, rs.max_row, rs.initial_formfields, rs.processed_formfields FROM cr_report_schedule rs WHERE rs.enabled_yn='Y' AND rs.start_date <= [currentDate] AND (rs.end_date >= [currentDate] or rs.end_date is null ) AND rs.run_date IS NOT NULL ) x, cr_report r WHERE x.rep_id = r.rep_id + +random.string = select ( 'Z' || round(random() * 1000000000000)) + + +scheduler.user.emails = SELECT au.user_id FROM (SELECT rs.schedule_id, rs.rep_id FROM cr_report_schedule rs WHERE rs.enabled_yn='Y' AND rs.start_date <= now() AND rs.end_date >= now() AND rs.run_date IS NOT NULL AND rs.schedule_id = [p_schedule_id] ) x, cr_report r, fn_user au WHERE x.rep_id = r.rep_id AND au.user_id IN (SELECT rsu.user_id FROM cr_report_schedule_users rsu WHERE rsu.schedule_id = x.schedule_id and rsu.schedule_id = [p_schedule_id] UNION SELECT ur.user_id FROM fn_user_role ur WHERE ur.role_id IN (SELECT rsu2.role_id FROM cr_report_schedule_users rsu2 WHERE rsu2.schedule_id = x.schedule_id and rsu2.schedule_id = [p_schedule_id])) + + +# my logins + +app.query = SELECT APP_ID, ML_APP_NAME, MOTS_ID from fn_app where ((enabled = 'Y' and open = 'N') or app_id = 1 ) + +user.log.query = SELECT DISTINCT IFNULL(ORG_USER_ID, '') CUID, '' AWID, CONCAT('"',IFNULL(ORG_USER_ID, ''),'"') APPLICATIONUSERID, CONCAT('"',IFNULL(FIRST_NAME, ''),'"') FIRST_NAME, CONCAT('"',substr(IFNULL(MIDDLE_NAME, ''), 0, 1),'"') MIDDLE_INITIAL, CONCAT('"',IFNULL(LAST_NAME, ''),'"') LAST_NAME, IFNULL(DATE_FORMAT(LAST_LOGIN_DATE, '%Y/%m/%d'), '') LAST_LOGON_DATE, DATE_FORMAT(CREATED_DATE, '%Y/%m/%d') ACCOUNT_ACTIVATION_DATE, IFNULL(DATE_FORMAT(MODIFIED_DATE, '%Y/%m/%d'), '') LAST_DATE_ACCOUNT_MODIFIED, '' LAST_PASSWORD_CHANGE_DATE, CONCAT('"',IFNULL(FIRST_NAME, ''),' ',IFNULL(MIDDLE_NAME, ''),' ',IFNULL(LAST_NAME, ''),'"') FULL_USER_NAME, '' NT_ID, IFNULL(EMAIL, '') EMAIL FROM FN_USER FU, FN_USER_ROLE FUR, FN_ROLE FR WHERE FU.USER_ID = FUR.USER_ID and FUR.ROLE_ID = FR.ROLE_ID and ((FUR.APP_ID = 1 and FUR.APP_ID = ? and FR.ROLE_NAME <> 'Standard User') or (FUR.APP_ID = ? and FUR.APP_ID <> 1)) and FU.ACTIVE_YN = 'Y' and FU.org_user_id is not null order by 1 + +profile.log.query = SELECT DISTINCT CONCAT('"' , ROLE_NAME , '"') PROFILE_NAME, '""' SECURITY_SETTINGS FROM FN_ROLE FR, FN_USER_ROLE FUR WHERE FUR.ROLE_ID = FR.ROLE_ID and FR.ACTIVE_YN = 'Y' and ((FUR.APP_ID = 1 and FUR.APP_ID = ? and FR.ROLE_NAME <> 'Standard User') or (FUR.APP_ID = ? and FUR.APP_ID <> 1)) ORDER BY 1 + +user.profile.log.query = SELECT DISTINCT IFNULL(ORG_USER_ID, '') CUID, '' AWID, CONCAT('"' , IFNULL(ORG_USER_ID, '') , '"') APPLICATIONUSERID , CONCAT('"' , ROLE_NAME , '"') PROFILE_NAME FROM FN_USER A, FN_USER_ROLE B, FN_ROLE C WHERE A.USER_ID = B.USER_ID AND B.ROLE_ID = C.ROLE_ID AND A.ACTIVE_YN = 'Y' AND C.ACTIVE_YN = 'Y' AND a.ORG_USER_ID is not null AND ((B.APP_ID = 1 and B.APP_ID = ? and C.ROLE_NAME <> 'Standard User') or (B.APP_ID = ? and B.APP_ID <> 1)) ORDER BY 1 + +all.accounts.log.query = SELECT DISTINCT IFNULL(ORG_USER_ID, '') CUID, (case when A.ACTIVE_YN='Y' then 'ACTIVE' else 'INACTIVE' end) ACTIVE_YN, CONCAT('"' , IFNULL(ORG_USER_ID, '') , '"') APPLICATIONUSERID , IFNULL(DATE_FORMAT(LAST_LOGIN_DATE, '%Y/%m/%d'), '') LAST_LOGON_DATE, '' LAST_PASSWORD_CHANGE_DATE, CONCAT('"' , ROLE_NAME , '"') PROFILE_NAME FROM FN_USER A, FN_USER_ROLE B, FN_ROLE C WHERE A.USER_ID = B.USER_ID AND B.ROLE_ID = C.ROLE_ID AND a.ORG_USER_ID is not null AND ((B.APP_ID = 1 and B.APP_ID = ? and C.ROLE_NAME <> 'Standard User') or (B.APP_ID = ? and B.APP_ID <> 1)) ORDER BY 1 + +# basic sql + +seq.next.val = SELECT nextval('[sequenceName]') AS id + +current.date = now() + +nvl = IFNULL diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/system.properties b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/system.properties new file mode 100644 index 00000000..8c682649 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/system.properties @@ -0,0 +1,118 @@ +### +# ================================================================================ +# eCOMP Portal +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file 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. +# ================================================================================ +### + +db.driver = com.mysql.jdbc.Driver +db.connectionURL = jdbc:mysql://localhost:3306/ecomp_portal +db.userName = XXXX +db.password = XXXX +# is the db.password property encrypted? +db.encrypt_flag = false + +db.hib.dialect = org.hibernate.dialect.MySQLDialect +db.min_pool_size = 5 +db.max_pool_size = 10 +hb.dialect = org.hibernate.dialect.MySQLDialect +hb.show_sql = false +hb.db_reconnect = true +hb.idle_connection_test_period = 3600 + +app_display_name = app_display_name +files_path = /demeter/WebApps/dev/ECOMP_APP/files +context_root = ECOMPPORTAL +# menu settings +menu_query_name = menuData +menu_properties_file_location = /WEB-INF/fusion/menu/ +application_menu_set_name = APP +application_menu_attribute_name = applicationMenuData +application_menu_properties_name = menu.properties +business_direct_menu_set_name = BD +business_direct_menu_properties_name = bd.menu.properties +business_direct_menu_attribute_name = businessDirectMenuData + +application_user_id = 30000 +post_default_role_id = 1 + +#Enable Fusion Mobile capabilities for the application +mobile_enable = false + +cache_config_file_path = /WEB-INF/conf/cache.ccf +cache_switch = 1 +cache_load_on_startup = false + +user_name = fullName +decryption_key = AGLDdG4D04BKm2lxlWEr8o== + + +#Cron Schedules +cron_site_name = one +log_cron = 0 * * * * ? * +sessiontimeout_feed_cron = 0 0/5 * * * ? * + +#Front end URL +frontend_url = http://localhost:9000/ecompportal/applicationsHome + +#cookie domain PLEASE DO NOT REMOVE THIS VALUE FOR OPEN SOUCE REFACTOR +cookie_domain = openecomp.org + +# An Unique 128-bit value defined to identify a specific version of +# ECOMP Portal deployed on a specific virtual machine. +# This value must be generated and updated at the time of +# the deployment. +# Online Unique UUID generator - https://www.uuidgenerator.net/ +instance_uuid = 90bc9497-10e6-49fe-916b-dcdfaa972383 + +ecomp_shared_context_rest_url= http://todo_enter_be_hostname:9000/ecompportal/context + +ecomp_shared_context_rest_url= http://todo_enter_share_context_rest_hostname:9000/ecompportal/context +elastic_search_url = http://todo_enter_elastic_search_hostname:9200 +contact_us_link = http://todo_enter_contact_us_hostname +user_guide_link = http://todo_enter_user_guide_link + +# Contact Us page properties +ush_ticket_url = http://todo_enter_ush_ticket_url +feedback_email_address = portal@lists.openecomp.org +portal_info_url = https://todo_enter_portal_info_url + +#Online user bar refresh interval, in seconds +online_user_update_rate = 5 + +#Online user bar refresh total duration, in seconds +online_user_update_duration = 900 + +# User notification refresh interval and duration, in seconds +notification_update_rate = 90 +notification_update_duration = 900 + +#Microservices Related Properties for Portal +microservices.widget.username = widget_user +microservices.widget.password = KpuqIB08YHg+btG+pjX+sA== +#This property won't be needed after consul is functional on VMs - +microservices.widget.local.port = 8082 + +#delete auditlog from number of days ago +auditlog_del_day_from = 365 + + +#authenticate user server +authenticate_user_server=http://todo_enter_auth_server_hostname:8383/openid-connect-server-webapp/allUsers + +#window width threshold to collapse left/right menu when page onload +window_width_threshold_left_menu = 1400 +window_width_threshold_right_menu = 1350 \ No newline at end of file diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/defs/definitions.xml b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/defs/definitions.xml new file mode 100644 index 00000000..603e1144 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/defs/definitions.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/fusion/conf/fusion.properties b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/fusion/conf/fusion.properties new file mode 100644 index 00000000..c39588b5 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/fusion/conf/fusion.properties @@ -0,0 +1,83 @@ +#os +### +# ================================================================================ +# eCOMP Portal +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file 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. +# ================================================================================ +### +# domain settings +#domain_class_location = + +# validator settings +#default_error_message = Default error message + +login_url_no_ret_val = http://localhost:9000/ecompportal/login.htm + +user_attribute_name = user + +# User Session settings +#user_attribute_name = user +roles_attribute_name = roles +role_functions_attribute_name = role_functions +#client_device_attribute_name = client_device +#client_device_emulation = false +#client_device_type_to_emulate = + +# menu settings +menu_query_name = menuData +#menu_properties_file_location = /WEB-INF/fusion/menu/ +application_menu_set_name = APP +application_menu_attribute_name = applicationMenuData +#application_menu_properties_name = menu.properties +business_direct_menu_set_name = BD +#business_direct_menu_properties_name = bd.menu.properties +business_direct_menu_attribute_name = businessDirectMenuData + +# RAPTOR config settings +#raptor_config_file_path = /WEB-INF/conf/ + +# ECOMP settings +ecomp_app_id = 1 +# Role settings +sys_admin_role_id = 1 +account_admin_role_id = 999 +restricted_app_role_id = 900 +#sys_admin_role_function_delete_from_ui = true + +# Profile Search settings +#profile_search_report_id=181 +#callable_profile_search_report_id=386 + + +# Home Page index html + +home_page = /index.html + +authentication_mechanism = DBAUTH + +login.error.hrid.empty = Login failed, please contact system administrator. +login.error.hrid.not-found = User not found, please contact system administrator. +login.error.user.inactive = Account is disabled, please contact system administrator. + +# +# Number of seconds to poll health (database operational, etc.) +# +health_poll_interval_seconds = 5 +# +# If a component is down a log entry will be written that triggers an alert. This parameter specifies how often this alert should be triggered +# if the component remains down. For example a value of 30, would translate to 30 * 60 seconds = 1800 seconds, or every 30 minutes +# +health_fail_alert_every_x_intervals = 30 diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/fusion/defs/definitions.xml b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/fusion/defs/definitions.xml new file mode 100644 index 00000000..f11b39a0 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/fusion/defs/definitions.xml @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/error.jsp b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/error.jsp new file mode 100644 index 00000000..c79aa89a --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/error.jsp @@ -0,0 +1,20 @@ +<%-- + ================================================================================ + eCOMP Portal + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file 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. + ================================================================================ + --%> +${errMsg} diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/index.jsp b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/index.jsp new file mode 100644 index 00000000..4726ce19 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/index.jsp @@ -0,0 +1,21 @@ +<%-- + ================================================================================ + eCOMP Portal + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file 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. + ================================================================================ + --%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> + diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/login.jsp b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/login.jsp new file mode 100644 index 00000000..7ca8531c --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/login.jsp @@ -0,0 +1,166 @@ +<%-- + ================================================================================ + eCOMP Portal + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file 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. + ================================================================================ + --%> +<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> +<%@ page import="org.openecomp.portalsdk.core.util.SystemProperties" %> +<%@ page import="org.openecomp.portalapp.portal.utils.EPSystemProperties" %> + +" /> + + + + + + + Login + + + + + + + + + + + + + + + <% + String frontUrl = SystemProperties.getProperty(EPSystemProperties.FE_URL); + %> +
+
+ +
+
+ +
+ + +
+
+ + +
+
+                + +
+
+
+






+
+ + + + diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/oid-admin.jsp b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/oid-admin.jsp new file mode 100644 index 00000000..93fd69ce --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/oid-admin.jsp @@ -0,0 +1,72 @@ +<%-- + ================================================================================ + eCOMP Portal + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file 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. + ================================================================================ + --%> +<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> +<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> +<%@ taglib prefix="o" tagdir="/WEB-INF/tags"%> + + +
+
+
+ +

Hello ${ userInfo.name }

+ +
+

This page requires that the user be logged in with a valid account and the ROLE_ADMIN Spring Security authority. + If you are reading this page, you are currently logged in as an administrator.

+ +

The authorization provider will assign your account a set of authorities depending on how it's configured. + Your current login has the following Spring Security authorities:

+ +
    + + +
  • ${ auth }
  • +
    +
+ +
+
+

Administrators

+ +

Logged in users are assigned the ROLE_USER authority by default, but the following users + (identified by issuer/subject pairs) will also be given ROLE_ADMIN:

+ + + + + + + + + + + + +
IssuerSubject
${ admin.issuer }${ admin.subject }
+
+ +
+
+
+ + + diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/oid-home.jsp b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/oid-home.jsp new file mode 100644 index 00000000..9fd11036 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/oid-home.jsp @@ -0,0 +1,102 @@ +<%-- + ================================================================================ + eCOMP Portal + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file 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. + ================================================================================ + --%> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> +<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> +<%@ taglib prefix="o" tagdir="/WEB-INF/tags"%> +<%@ page session="false" %> + + +
+
+
+ +

+ Hello world! +

+ +
+

+ + You are currently logged in. + + + You are NOT currently logged in. + +

+ +

This example application is configured with several pages requiring different levels of access. + This page does not require the user to be logged in. Use the tabs in the navbar above to navigate to + pages with different access requirements. +

+ +
    +
  • User, requires the user to be logged in with the ROLE_USER Spring Security authority.
  • +
  • Admin, requires the user to be logged in with the ROLE_ADMIN Spring Security authority. + See below for the currently configured list of admin accounts.
  • + +
  • Logout, log out directly and return to this page.
  • +
    + +
  • Log in, log in directly and return to this page.
  • +
    +
+ + +
+ +
+

Client Filter Configuration

+ +

This authorization filter for this client has been configured with the following components:

+ +
    +
  • Issuer service: ${ issuerServiceClass }
  • +
  • Server configuration service: ${ serverConfigurationServiceClass }
  • +
  • Client configuration service: ${ clientConfigurationServiceClass }
  • +
  • Auth request options service: ${ authRequestOptionsServiceClass }
  • +
  • Auth request URI builder: ${ authRequestUriBuilderClass }
  • +
+
+ +
+

Administrators

+ +

Logged in users are assigned the ROLE_USER authority by default, but the following users + (identified by issuer/subject pairs) will also be given ROLE_ADMIN:

+ + + + + + + + + + + + +
IssuerSubject
${ admin.issuer }${ admin.subject }
+
+
+
+
+ + + diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/oid-login.jsp b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/oid-login.jsp new file mode 100644 index 00000000..cf2f9bcc --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/oid-login.jsp @@ -0,0 +1,76 @@ +<%-- + ================================================================================ + eCOMP Portal + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file 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. + ================================================================================ + --%> +<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> +<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> +<%@ taglib prefix="o" tagdir="/WEB-INF/tags"%> + +
+
+
+ +

Welcome to ECOMP Portal OpenId Login

+ +

+ Please provide the URI for your OpenId Authorization Server. Make sure the OpenId Connect Server is Running on the following location +

+ +

+ If you do not have one of your own, for a quick start up, you can clone from this github location - It's an open source OpenID Connect Server. +

+ +

+ Simply clone on your local, go to sub-project directory called 'openid-connect-server-webapp' and do + + mvn jetty:run + +

+ +

+ Choose a different port using the jetty plugin inside pom.xml, if the default 8080 is already taken by your Application. +

+ + + +
+
+ +
+
+ + +
+
+
+
+
+
+ + diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/oid-user.jsp b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/oid-user.jsp new file mode 100644 index 00000000..112415b0 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/oid-user.jsp @@ -0,0 +1,139 @@ +<%-- + ================================================================================ + eCOMP Portal + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file 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. + ================================================================================ + --%> +<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> +<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> +<%@ taglib prefix="o" tagdir="/WEB-INF/tags"%> + + +
+
+
+ +

Hello ${ userInfo.name }

+ +
+

This page requires that the user be logged in with a valid account and the ROLE_USER Spring Security authority. + If you are reading this page, you are currently logged in.

+ + + +

The authorization provider will create a Principal object based on the iss and sub + claims associated with your ID token. This value can be used as a globally unique username within the application + (though it's not meant to be human-readable). + Your Principal is: ${ user }

+ +

The authorization provider will assign your account a set of authorities depending on how it's configured. + Your current login has the following Spring Security authorities:

+ +
    + + +
  • ${ auth }
  • +
    +
+ +

ID Token

+ +

Your ID Token has the following set of claims:

+ + + + + + + + + + + +
NameValue
+ +

The ID Token header contains the following claims:

+ + + + + + + + + + +
NameValue
+ +

User Info

+ +

The call to the User Info Endpoint returned the following set of claims:

+ + + + + + + + + + +
NameValue
+ +
+ +
+
+
+ + + + diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/welcome.jsp b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/welcome.jsp new file mode 100644 index 00000000..054c38fe --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/welcome.jsp @@ -0,0 +1,695 @@ +<%-- + ================================================================================ + eCOMP Portal + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file 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. + ================================================================================ + --%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> +<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ Welcome ${sessionScope.user.firstName} ${sessionScope.user.lastName}  + (Last Login:  ${lastLogin}) +
+ +
+

Network

+

Visualization

+ +
+ + +
+

+ You can toggle between the Image Slider and Carousel controls by clicking on the respective radio button below: +

+ Slider
+ Carousel + +
+
+ +
+ +
+
+ Drive test analytics + MTSA - Nationwide DL throughput for iOS devices over cellular network + Location based services county level drive test + Network demand data by LATA (2020 forecast) + Linear regression prediction of LBS/E911 drive test accuracy + SDN Simulator - SNRC Traffic + (Click on Image to Rotate) +
+
+
+
+
+
+ Drive test analytics +
+

Drive test analytics

+
+
+
+ MTSA - Nationwide DL throughput for iOS devices over cellular network +
+

Nationwide DL throughput for iOS devices over cellular network

+
+
+
+ Network demand data by LATA (2020 forecast) +
+

Network demand data by LATA (2020 forecast)

+
+
+
+ Location based services county level drive test +
+

Location based services county level drive test

+
+
+
+ SDN Simulator - SNRC Traffic +
+

SDN Simulator - SNRC Traffic

+
+
+
+ Linear regression prediction of LBS/E911 drive test accuracy +
+

Linear regression prediction of LBS/E911 drive test accuracy

+
+
+
+ + +
+ Example Frame +
+
+ +
+
+
+
+
+ +
+ + + + +
+ +
+
+ +
+
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+ +
+ + + +
+
Monday
+ + + + + + +
+
+
+ + + +
+
Monday
+ + + + +
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Contacts + +
Developer Program + +
ZK Framework + +
JQuery + +
RNC Visualization + +
Heat Map + +
Animated Map + +
Process Management + +
Chat Session + +
+
+
+
+
+
+ + + + + + + + +
+ +
+ + +
+ +
+
+
+
+ +
+ + + + + diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/oid-context.xml b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/oid-context.xml new file mode 100644 index 00000000..33458d6d --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/oid-context.xml @@ -0,0 +1,455 @@ + + + + + + + + + + + classpath:openid-connect.properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + openid + email + address + profile + phone + + + + + + ${ecomp_openid_connect_client} + + + + + + + + + + + + + + + + + + + + openid + email + address + profile + phone + + + + + + ${ecomp_openid_connect_client} + + + + + + + + + + + + + + + + + + + openid + email + address + profile + phone + + + + + + ${ecomp_openid_connect_client} + + + + + + + + + + + + + openid + email + address + profile + phone + + + + + + ${ecomp_openid_connect_client} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/tags/copyright.tag b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/tags/copyright.tag new file mode 100644 index 00000000..f06786c6 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/tags/copyright.tag @@ -0,0 +1 @@ +Powered by MITREid Connect ${project.version} © 2014 The MITRE Corporation and MIT KIT. diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/tags/footer.tag b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/tags/footer.tag new file mode 100644 index 00000000..8b47824a --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/tags/footer.tag @@ -0,0 +1,12 @@ +<%@ attribute name="js" required="false"%> +<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="o" tagdir="/WEB-INF/tags"%> + + + + + + + diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/tags/header.tag b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/tags/header.tag new file mode 100644 index 00000000..6f8c5c3d --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/tags/header.tag @@ -0,0 +1,59 @@ +<%@attribute name="title" required="false"%> +<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ tag import="com.google.gson.Gson" %> + + + + + + + + Simple Web App - ${title} + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/tags/topbar.tag b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/tags/topbar.tag new file mode 100644 index 00000000..5109523a --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/tags/topbar.tag @@ -0,0 +1,96 @@ +<%@attribute name="pageName" required="false"%> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> +<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags"%> +<%@ taglib prefix="o" tagdir="/WEB-INF/tags"%> + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/web.xml b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 00000000..8c920d12 --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,87 @@ + + + + + fusion + + + + + + + + contextConfigLocation + /WEB-INF/oid-context.xml + + + + + org.springframework.web.context.ContextLoaderListener + + + + + + org.openecomp.portalapp.portal.listener.UserSessionListener + + + + CorsFilter + org.apache.catalina.filters.CorsFilter + + cors.allowed.methods + GET,POST,HEAD,OPTIONS,PUT,DELETE + + + cors.allowed.headers + EPService,JSESSIONID,X-ECOMP-RequestID,X-Widgets-Type,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers + + + + + CorsFilter + /* + + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + + + springSecurityFilterChain + /* + + + diff --git a/ecomp-portal-BE-os/src/main/webapp/images/cache/README.txt b/ecomp-portal-BE-os/src/main/webapp/images/cache/README.txt new file mode 100644 index 00000000..65bb14cc --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/images/cache/README.txt @@ -0,0 +1 @@ +image cache \ No newline at end of file diff --git a/ecomp-portal-BE-os/src/main/webapp/index.jsp b/ecomp-portal-BE-os/src/main/webapp/index.jsp new file mode 100644 index 00000000..2811bb4b --- /dev/null +++ b/ecomp-portal-BE-os/src/main/webapp/index.jsp @@ -0,0 +1,41 @@ +<%-- + ================================================================================ + ECOMP Portal + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file 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. + ================================================================================ + --%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> + +<%-- Redirected because we can't set the welcome page to a virtual URL. --%> +<%-- + --%> + + + ecompportal-BE index.jsp + + +

ECOMP Portal Core

+ This is the ecompportal-BE application, page index.jsp. + + <% + + response.sendRedirect("welcome.htm"); + + %> + + + + diff --git a/ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/controller/SharedContextRestClient.java b/ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/controller/SharedContextRestClient.java new file mode 100644 index 00000000..49686c80 --- /dev/null +++ b/ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/controller/SharedContextRestClient.java @@ -0,0 +1,280 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.net.URI; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.SSLContext; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.Consts; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.ssl.SSLContexts; +import org.apache.http.ssl.TrustStrategy; +import org.apache.http.util.EntityUtils; +/** + * Provides reusable features for test cases to get or post from an REST + * endpoint, allowing use of HTTPS connections to servers that use self-signed + * certificates. + */ +public class SharedContextRestClient { + + private static final Log logger = LogFactory.getLog(SharedContextRestClient.class); + + /** + * Convenience method that builds and sends a GET request using properties + * to build the URI and populate header with credentials. + * + * @param task + * last component(s) of REST endpoint name; e.g., "get". + * @param contextId + * @param contextKey + * @return JSON string fetched + * @throws Exception + * if the HTTP response code is anything other than OK. + */ + public static String getJson(final SharedContextTestProperties properties, final String task, + final String contextId, final String contextKey) throws Exception { + String requestPath = '/' + properties.getProperty(SharedContextTestProperties.APPNAME) // + + '/' + properties.getProperty(SharedContextTestProperties.RESTPATH) // + + '/' + task; + return getJson(properties.getProperty(SharedContextTestProperties.HOSTNAME), // + properties.getProperty(SharedContextTestProperties.PORT, -1), // + properties.getProperty(SharedContextTestProperties.SECURE, true), // + properties.getProperty(SharedContextTestProperties.UEBKEY), // + properties.getProperty(SharedContextTestProperties.USERNAME), // + properties.getProperty(SharedContextTestProperties.PASSWORD), requestPath, // + contextId, // + contextKey); + } + + /** + * Constructs and sends a GET request using the specified values. + * + * @param hostname + * @param port + * ignored if negative + * @param secure + * If true, uses https; else http. + * @param headerUebkey + * @param headerUsername + * @param headerPassword + * @param requestPath + * full path of the REST endpoint + * @param contextId + * @param contextKey + * Ignored if null + * @return JSON result + */ + public static String getJson(final String hostname, final int port, boolean secure, final String headerUebkey, + final String headerUsername, final String headerPassword, final String requestPath, final String contextId, + final String contextKey) throws Exception { + + URIBuilder uriBuilder = new URIBuilder(); + if (secure) + uriBuilder.setScheme("https"); + else + uriBuilder.setScheme("http"); + uriBuilder.setHost(hostname); + if (port > 0) + uriBuilder.setPort(port); + uriBuilder.setPath(requestPath); + uriBuilder.addParameter("context_id", contextId); + if (contextKey != null) + uriBuilder.addParameter("ckey", contextKey); + final URI uri = uriBuilder.build(); + + CloseableHttpClient httpClient; + if (secure) { + // Tell HttpClient to accept any server certificate for HTTPS. + // http://stackoverflow.com/questions/24720013/apache-http-client-ssl-certificate-error + SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { + @Override + public boolean isTrusted(final X509Certificate[] chain, final String authType) + throws CertificateException { + return true; + } + }).build(); + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, + NoopHostnameVerifier.INSTANCE); + httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build(); + } else { + httpClient = HttpClients.createDefault(); + } + + HttpGet httpGet = new HttpGet(uri); + httpGet.setHeader("uebkey", headerUebkey); + httpGet.setHeader("username", headerUsername); + httpGet.setHeader("password", headerPassword); + + String json = null; + CloseableHttpResponse response = null; + try { + logger.debug("GET from " + uri); + response = httpClient.execute(httpGet); + logger.info("Status is " + response.getStatusLine()); + if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) + throw new Exception("Status is " + response.getStatusLine().toString()); + HttpEntity entity = response.getEntity(); + if (entity == null) { + logger.warn("Entity is null!"); + } else { + // entity content length is never set. + // this naively tries to read everything. + json = EntityUtils.toString(entity); + EntityUtils.consume(entity); + } + } finally { + if (response != null) + response.close(); + } + return json; + } + + /** + * Convenience method that builds and sends a POST request using properties + * to build the URI and populate header with credentials. + * + * @param path + * last component(s) of REST endpoint name; e.g., "users" or + * "user/{userid}/roles". + * @return JSON string fetched + * @throws Exception + * if the HTTP response code is anything other than OK. + */ + public static String postJson(final SharedContextTestProperties properties, final String path, final String json) + throws Exception { + String requestPath = '/' + properties.getProperty(SharedContextTestProperties.APPNAME) // + + '/' + properties.getProperty(SharedContextTestProperties.RESTPATH) // + + '/' + path; + return postJson(properties.getProperty(SharedContextTestProperties.HOSTNAME), // + properties.getProperty(SharedContextTestProperties.PORT, -1), // + properties.getProperty(SharedContextTestProperties.SECURE, true), // + properties.getProperty(SharedContextTestProperties.UEBKEY), // + properties.getProperty(SharedContextTestProperties.USERNAME), // + properties.getProperty(SharedContextTestProperties.PASSWORD), // + requestPath, // + json); + } + + /** + * Constructs and sends a POST request using the specified values. + * + * @param hostname + * @param port + * @param secure + * If true, uses https; else http. + * @param requestPath + * full path of the REST endpoint + * @param headerUebkey + * @param headerUsername + * @param headerPassword + * @param json + * Content to post + * @return JSON result + * @throws Exception + */ + public static String postJson(final String hostname, final int port, boolean secure, final String headerUebkey, + final String headerUsername, final String headerPassword, final String requestPath, final String json) + throws Exception { + + URIBuilder builder = new URIBuilder(); + if (secure) + builder.setScheme("https"); + else + builder.setScheme("http"); + builder.setHost(hostname); + if (port > 0) + builder.setPort(port); + builder.setPath(requestPath); + final URI uri = builder.build(); + + CloseableHttpClient httpClient; + if (secure) { + // Tell HttpClient to accept any server certificate for HTTPS. + // http://stackoverflow.com/questions/24720013/apache-http-client-ssl-certificate-error + SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { + @Override + public boolean isTrusted(final X509Certificate[] chain, final String authType) + throws CertificateException { + return true; + } + }).build(); + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, + NoopHostnameVerifier.INSTANCE); + httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslsf).build(); + } else { + httpClient = HttpClients.createDefault(); + } + HttpPost httpPost = new HttpPost(uri); + httpPost.setHeader("uebkey", headerUebkey); + httpPost.setHeader("username", headerUsername); + httpPost.setHeader("password", headerPassword); + + StringEntity postEntity = new StringEntity(json, ContentType.create("application/json", Consts.UTF_8)); + httpPost.setEntity(postEntity); + + String responseJson = null; + CloseableHttpResponse response = null; + try { + logger.debug("POST to " + uri); + response = httpClient.execute(httpPost); + logger.info("Status is " + response.getStatusLine()); + if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) + throw new Exception("Status is " + response.getStatusLine().toString()); + + HttpEntity entity = response.getEntity(); + if (entity == null) { + logger.warn("Entity is null!"); + } else { + long len = entity.getContentLength(); + if (len < 0) + logger.warn("Content length is -1"); + if (len < 2048) { + responseJson = EntityUtils.toString(entity); + logger.debug(responseJson); + } else { + logger.warn("Not implemented - stream content"); + } + EntityUtils.consume(entity); + } + } finally { + if (response != null) + response.close(); + } + return responseJson; + } + +} diff --git a/ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/controller/SharedContextRestControllerTest.java b/ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/controller/SharedContextRestControllerTest.java new file mode 100644 index 00000000..a7a86e8c --- /dev/null +++ b/ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/controller/SharedContextRestControllerTest.java @@ -0,0 +1,125 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Assert; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Tests the endpoints exposed by the Shared Context REST controller in Portal + * Core. + * + * @author clott + */ +public class SharedContextRestControllerTest { + + private final Log logger = LogFactory.getLog(getClass()); + + private final SharedContextTestProperties properties; + + private final String ckey = "ckey"; + private final String cvalue = "cvalue"; + + // Supposed to be a Portal session ID + private final String cxid = UUID.randomUUID().toString(); + + private final String key = "key123"; + private final String value1 = "first value"; + private final String value2 = "second value"; + + public SharedContextRestControllerTest() throws IOException { + properties = new SharedContextTestProperties(); + } + + @SuppressWarnings("unchecked") + //@Test + public void test() throws Exception { + String response = null, val = null; + ObjectMapper mapper = new ObjectMapper(); + Map responseMap, jsonMap; + + logger.info("Get on empty context"); + response = SharedContextRestClient.getJson(properties, "get", cxid, key); + // Should not exist - just generated the UUID + Map responseMap1 = mapper.readValue(response, Map.class); + response = (String) responseMap1.get("response"); + Assert.assertNull(response); + + logger.info("Set a new context"); + response = setContext(cxid, key, value1); + Assert.assertNotNull(response); + responseMap = mapper.readValue(response, Map.class); + String responseValue = (String) responseMap.get("response"); + Assert.assertNotNull(responseValue); + Assert.assertEquals("added", responseValue); + + logger.info("Get existing context"); + response = SharedContextRestClient.getJson(properties, "get", cxid, key); + responseMap = mapper.readValue(response, Map.class); + jsonMap = (Map) responseMap.get("response"); + Assert.assertNotNull(jsonMap); + val = (String) jsonMap.get(cvalue); + Assert.assertEquals(val, value1); + + logger.info("Overwrite exiting context"); + response = setContext(cxid, key, value2); + Assert.assertNotNull(response); + responseMap = mapper.readValue(response, Map.class); + response = (String) responseMap.get("response"); + Assert.assertNotNull(responseValue); + // Assert.assertEquals("replaced", responseValue); + + logger.info("Get existing context to verify overwrite"); + response = SharedContextRestClient.getJson(properties, "get", cxid, key); + responseMap = mapper.readValue(response, Map.class); + jsonMap = (Map) responseMap.get("response"); + Assert.assertNotNull(jsonMap); + val = (String) jsonMap.get(cvalue); + Assert.assertEquals(val, value2); + + logger.info("Delete one context"); + response = SharedContextRestClient.getJson(properties, "remove", cxid, key); + responseMap = mapper.readValue(response, Map.class); + response = (String) responseMap.get("response"); + Assert.assertEquals(response, "removed"); + + logger.info("Clear the context"); + response = SharedContextRestClient.getJson(properties, "clear", cxid, null); + Assert.assertEquals("", response); + } + + private String setContext(String context, String id, String value) throws Exception { + ObjectMapper mapper = new ObjectMapper(); + HashMap stringMap = new HashMap(); + stringMap.put("context_id", cxid); + stringMap.put(ckey, key); + stringMap.put(cvalue, value2); + String json = mapper.writeValueAsString(stringMap); + String response = SharedContextRestClient.postJson(properties, "set", json); + return response; + } +} diff --git a/ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/controller/SharedContextTestProperties.java b/ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/controller/SharedContextTestProperties.java new file mode 100644 index 00000000..baed554b --- /dev/null +++ b/ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/controller/SharedContextTestProperties.java @@ -0,0 +1,81 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +/** + * Trivial extension of Properties that populates itself from a known source. + */ +public class SharedContextTestProperties extends Properties { + + private static final long serialVersionUID = -4064100267979036550L; + + // property names + public static final String HOSTNAME = "hostname"; + public static final String PORT = "port"; + public static final String SECURE = "secure"; + public static final String APPNAME = "appname"; + public static final String RESTPATH = "restpath"; + public static final String UEBKEY = "uebkey"; + public static final String USERNAME = "username"; + public static final String PASSWORD = "password"; + + /** + * Expected on the classpath + */ + private static final String propertiesFileName = "shared-context-test.properties"; + + /** + * Constructor populates itself from properties file found in same package. + * + * @throws Exception + */ + public SharedContextTestProperties() throws IOException { + InputStream inStream = getClass().getResourceAsStream(propertiesFileName); + if (inStream == null) + throw new IOException("Failed to find file on classpath: " + propertiesFileName); + super.load(inStream); + inStream.close(); + } + + public int getProperty(final String name, final int defVal) throws NumberFormatException { + String prop = getProperty(name); + if (prop == null) + return defVal; + return Integer.parseInt(prop); + } + + public boolean getProperty(final String name, final boolean defVal) { + String prop = getProperty(name); + if (prop == null) + return false; + return Boolean.parseBoolean(prop); + } + + // Test this class + public static void main(String[] args) throws Exception { + SharedContextTestProperties p = new SharedContextTestProperties(); + System.out.println("Property " + SharedContextTestProperties.HOSTNAME + " = " + + p.getProperty(SharedContextTestProperties.HOSTNAME)); + } +} diff --git a/ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/controller/shared-context-test.properties b/ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/controller/shared-context-test.properties new file mode 100644 index 00000000..3e44a781 --- /dev/null +++ b/ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/controller/shared-context-test.properties @@ -0,0 +1,28 @@ +### +# ================================================================================ +# ECOMP Portal +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file 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. +# ================================================================================ +### + +hostname= localhost +# port = 80 +secure = true +appname = ecompportal +restpath = context +uebkey = xgnLrmNmkfCRnIwa +username = Default +password = AppPassword!1 diff --git a/ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/listener/HealthMonitorTest.java b/ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/listener/HealthMonitorTest.java new file mode 100644 index 00000000..6d01f2c9 --- /dev/null +++ b/ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/listener/HealthMonitorTest.java @@ -0,0 +1,36 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.listener; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class HealthMonitorTest { + + @Test + public void initialFlagsTest() { + assertEquals(false, HealthMonitor.isBackEndUp()); + assertEquals(false, HealthMonitor.isFrontEndUp()); + assertEquals(false, HealthMonitor.isDatabaseUp()); + assertEquals(false, HealthMonitor.isUebUp()); + } + +} diff --git a/ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/utils/EcompPortalUtilsTest.java b/ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/utils/EcompPortalUtilsTest.java new file mode 100644 index 00000000..4df4f761 --- /dev/null +++ b/ecomp-portal-BE-os/src/test/java/org/openecomp/portalapp/portal/utils/EcompPortalUtilsTest.java @@ -0,0 +1,33 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file 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. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.utils; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class EcompPortalUtilsTest { + + + @Test + public void legitimateUserIdFailureTest() { + assertEquals(false, EcompPortalUtils.legitimateUserId("1#@23456")); + } +} -- cgit 1.2.3-korg