From 2845910b34682056c1949f82e39d9205a26554e9 Mon Sep 17 00:00:00 2001 From: "Kishore Reddy, Gujja (kg811t)" Date: Mon, 14 May 2018 17:19:51 -0400 Subject: Bulk upload changes and music health check apis Issue-ID: PORTAL-290, PORTAL-291 Bulk upload changes and music health check apis Change-Id: I63d289d75420658ff4a14385a5106838fa8c32b2 Signed-off-by: Kishore Reddy, Gujja (kg811t) --- .../org/onap/portalapp/annotation/ApiVersion.java | 55 ++ .../portalapp/config/ExternalSecurityConfig.java | 10 +- .../SessionCommunicationVersionController.java | 68 ++ .../controller/AppsControllerExternalRequest.java | 2 + .../AppsControllerExternalVersionRequest.java | 89 +++ .../controller/AuxApiRequestMapperController.java | 890 +++++++++++++++++++++ .../controller/ExternalAccessRolesController.java | 36 +- .../ExternalAppsRestfulVersionController.java | 80 ++ .../portal/controller/HealthCheckController.java | 31 +- .../portal/controller/RoleManageController.java | 78 +- .../RolesApprovalSystemVersionController.java | 75 ++ .../portal/controller/RolesController.java | 207 +++++ .../controller/TicketEventVersionController.java | 63 ++ .../WebAnalyticsExtAppVersionController.java | 68 ++ .../controller/WidgetsCatalogController.java | 34 +- .../onap/portalapp/portal/domain/EPUserApp.java | 3 +- .../ecomp/model/UploadRoleFunctionExtSystem.java | 98 +++ .../interceptor/PortalResourceInterceptor.java | 29 +- .../portalapp/portal/listener/HealthMonitor.java | 166 +++- .../portal/logging/format/EPAppMessagesEnum.java | 7 +- .../portal/logging/format/EPErrorCodesEnum.java | 2 + .../portal/scheduler/SchedulerRestInterface.java | 1 - .../scheduleraux/SchedulerAuxRestInterface.java | 51 +- .../service/ApplicationsRestClientServiceImpl.java | 8 +- .../portal/service/BasicAuthAccountService.java | 10 + .../service/BasicAuthAccountServiceImpl.java | 30 +- .../portal/service/EPAppCommonServiceImpl.java | 86 +- .../portal/service/ExternalAccessRolesService.java | 35 +- .../service/ExternalAccessRolesServiceImpl.java | 427 ++++++++-- .../portal/service/MicroserviceServiceImpl.java | 16 +- .../portal/service/UserRolesCommonServiceImpl.java | 39 +- .../portalapp/portal/service/UserServiceImpl.java | 4 +- .../portalapp/portal/transport/CentralV2Role.java | 2 +- .../portal/transport/CentralizedAppRoles.java | 111 +++ .../transport/ExternalAccessUserRoleDetail.java | 10 +- .../portalapp/portal/transport/RemoteRoleV1.java | 96 +++ .../org/onap/portalapp/portal/ueb/EPUebHelper.java | 229 ------ .../portal/utils/EPCommonSystemProperties.java | 5 + .../portalapp/portal/utils/EcompPortalUtils.java | 12 +- .../utils/MusicCookieCsrfTokenRepository.java | 102 +++ .../service/sessionmgt/TimeoutHandler.java | 1 + .../uebhandler/FunctionalMenuHandler.java | 133 +++ .../onap/portalapp/uebhandler/InitUebHandler.java | 85 ++ .../onap/portalapp/uebhandler/MainUebHandler.java | 125 +++ .../uebhandler/WidgetNotificationHandler.java | 109 +++ 45 files changed, 3395 insertions(+), 423 deletions(-) create mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/annotation/ApiVersion.java create mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/controller/sessionmgt/SessionCommunicationVersionController.java create mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalVersionRequest.java create mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperController.java create mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulVersionController.java create mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RolesApprovalSystemVersionController.java create mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RolesController.java create mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/TicketEventVersionController.java create mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppVersionController.java create mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/ecomp/model/UploadRoleFunctionExtSystem.java create mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CentralizedAppRoles.java create mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/RemoteRoleV1.java delete mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/ueb/EPUebHelper.java create mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/MusicCookieCsrfTokenRepository.java create mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/uebhandler/FunctionalMenuHandler.java create mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/uebhandler/InitUebHandler.java create mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/uebhandler/MainUebHandler.java create mode 100644 ecomp-portal-BE-common/src/main/java/org/onap/portalapp/uebhandler/WidgetNotificationHandler.java (limited to 'ecomp-portal-BE-common/src/main/java/org/onap/portalapp') diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/annotation/ApiVersion.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/annotation/ApiVersion.java new file mode 100644 index 00000000..79f7b70e --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/annotation/ApiVersion.java @@ -0,0 +1,55 @@ + +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ +package org.onap.portalapp.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface ApiVersion { + + String service() default ""; + String max() default ""; + int min() default 0; + String method() default ""; + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/config/ExternalSecurityConfig.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/config/ExternalSecurityConfig.java index 9f561b05..5354fa39 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/config/ExternalSecurityConfig.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/config/ExternalSecurityConfig.java @@ -41,11 +41,11 @@ import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; +import org.onap.portalapp.portal.utils.MusicCookieCsrfTokenRepository; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.web.csrf.CookieCsrfTokenRepository; import org.springframework.security.web.util.matcher.RegexRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; @@ -61,14 +61,12 @@ public class ExternalSecurityConfig extends WebSecurityConfigurerAdapter { @Override public boolean matches(HttpServletRequest request) { if(allowedMethods.matcher(request.getMethod()).matches()) - return false; - + return false; if(requestMatcher.matches(request)) - return true; - + return true; return false; } }; - http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).requireCsrfProtectionMatcher(csrfRequestMatcher); + http.csrf().csrfTokenRepository(MusicCookieCsrfTokenRepository.withHttpOnlyFalse()).requireCsrfProtectionMatcher(csrfRequestMatcher); } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/controller/sessionmgt/SessionCommunicationVersionController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/controller/sessionmgt/SessionCommunicationVersionController.java new file mode 100644 index 00000000..f78b14bd --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/controller/sessionmgt/SessionCommunicationVersionController.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + */ +package org.onap.portalapp.controller.sessionmgt; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.portalapp.annotation.ApiVersion; +import org.onap.portalapp.portal.logging.aop.EPAuditLog; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; + +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +@ApiVersion +public class SessionCommunicationVersionController { + + @Autowired + SessionCommunicationController sessionCommunicationController; + + @ApiVersion(max = "v3", service = "/v3/getSessionSlotCheckInterval", min = 0,method = "GET") + public Integer getSessionSlotCheckInterval(HttpServletRequest request, HttpServletResponse response) + throws Exception { + return sessionCommunicationController.getSessionSlotCheckInterval(request, response); + } + + + @ApiVersion(max = "v3", service = "/v3/extendSessionTimeOuts", min = 0,method = "POST") + public Boolean extendSessionTimeOuts(HttpServletRequest request, HttpServletResponse response, String sessionMap) throws Exception { + return sessionCommunicationController.extendSessionTimeOuts(request, response, sessionMap); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java index 483d76ea..cef5fa74 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java @@ -53,6 +53,7 @@ import org.onap.portalapp.portal.service.PortalAdminService; import org.onap.portalapp.portal.service.UserService; import org.onap.portalapp.portal.transport.FieldsValidator; import org.onap.portalapp.portal.transport.OnboardingApp; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; import org.onap.portalapp.portal.utils.EcompPortalUtils; import org.onap.portalapp.portal.utils.PortalConstants; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; @@ -212,6 +213,7 @@ public class AppsControllerExternalRequest implements BasicAuthenticationControl @PathVariable("appId") Long appId) { EPApp epApp = appService.getApp(appId); OnboardingApp obApp = new OnboardingApp(); + epApp.setAppPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD); //to hide password from get request appService.createOnboardingFromApp(epApp, obApp); EcompPortalUtils.logAndSerializeObject(logger, "getOnboardAppExternal", "response", obApp); return obApp; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalVersionRequest.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalVersionRequest.java new file mode 100644 index 00000000..13a6811e --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalVersionRequest.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + */ +package org.onap.portalapp.portal.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.portalapp.annotation.ApiVersion; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; +import org.onap.portalapp.portal.logging.aop.EPAuditLog; +import org.onap.portalapp.portal.transport.OnboardingApp; +import org.onap.portalapp.portal.utils.EcompPortalUtils; +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.ResponseBody; + +import io.swagger.annotations.ApiOperation; + +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +@ApiVersion +public class AppsControllerExternalVersionRequest implements BasicAuthenticationController { + + @Autowired + AppsControllerExternalRequest appsControllerExternalRequest; + + @ApiVersion(max = "v3", service = "/v3/portalAdmin", min = 0, method = "POST") + public PortalRestResponse postPortalAdmin(HttpServletRequest request, HttpServletResponse response, + EPUser epUser) { + return appsControllerExternalRequest.postPortalAdmin(request, response, epUser); + } + + @ApiVersion(max = "v3", service = "/v3/onboardApp/[0-9]{1,25}$", min = 0, method = "GET") + public OnboardingApp getOnboardAppExternal(HttpServletRequest request, HttpServletResponse response, Long appId) { + return appsControllerExternalRequest.getOnboardAppExternal(request, response, appId); + } + + @ApiVersion(max = "v3", service = "/v3/onboardApp", min = 0, method = "POST") + public PortalRestResponse postOnboardAppExternal(HttpServletRequest request, HttpServletResponse response, + OnboardingApp newOnboardApp) { + return appsControllerExternalRequest.postOnboardAppExternal(request, response, newOnboardApp); + + } + @ApiVersion(max = "v3", service = "/v3/onboardApp/[0-9]{1,25}$", min = 0, method = "PUT") + public PortalRestResponse putOnboardAppExternal(HttpServletRequest request, HttpServletResponse response, + Long appId, OnboardingApp oldOnboardApp) { + return appsControllerExternalRequest.putOnboardAppExternal(request, response, appId, oldOnboardApp); + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperController.java new file mode 100644 index 00000000..60c25c65 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AuxApiRequestMapperController.java @@ -0,0 +1,890 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + */ +package org.onap.portalapp.portal.controller; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.jar.Attributes; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.portalapp.annotation.ApiVersion; +import org.onap.portalapp.externalsystemapproval.model.ExternalSystemUser; +import org.onap.portalapp.portal.domain.CentralV2RoleFunction; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; +import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.onap.portalapp.portal.logging.aop.EPAuditLog; +import org.onap.portalapp.portal.service.ManifestService; +import org.onap.portalapp.portal.transport.Analytics; +import org.onap.portalapp.portal.transport.CentralUser; +import org.onap.portalapp.portal.transport.CentralV2Role; +import org.onap.portalapp.portal.transport.EpNotificationItem; +import org.onap.portalapp.portal.transport.FavoritesFunctionalMenuItemJson; +import org.onap.portalapp.portal.transport.FunctionalMenuItem; +import org.onap.portalapp.portal.transport.OnboardingApp; +import org.onap.portalsdk.core.domain.Role; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse; +import org.onap.portalsdk.core.restful.domain.EcompRole; +import org.onap.portalsdk.core.restful.domain.EcompUser; +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.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.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.swagger.annotations.ApiOperation; + +@RestController +@RequestMapping("/auxapi") +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class AuxApiRequestMapperController implements ApplicationContextAware, BasicAuthenticationController { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AuxApiRequestMapperController.class); + + ApplicationContext context = null; + int minorVersion = 0; + + @Autowired + private ManifestService manifestService; + + @ApiOperation(value = "Gets user roles for an application which is upgraded to newer version.", response = String.class, responseContainer = "List") + @RequestMapping(value = { "/v3/user/{loginId}" }, method = RequestMethod.GET, produces = "application/json") + public String getUser(HttpServletRequest request, HttpServletResponse response, + @PathVariable("loginId") String loginId) throws Exception { + Map res = getMethod(request, response); + String answer = null; + try { + answer = (String) invokeMethod(res, request, response, loginId); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getUser failed", e); + } + return answer; + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Gets roles for an application which is upgraded to newer version.", response = CentralV2Role.class, responseContainer = "Json") + @RequestMapping(value = { "/v3/roles" }, method = RequestMethod.GET, produces = "application/json") + public List getRoles(HttpServletRequest request, HttpServletResponse response) throws Exception { + Map res = getMethod(request, response); + request.getMethod(); + List answer = null; + try { + answer = (List) invokeMethod(res, request, response); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getRoles failed", e); + } + return answer; + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Saves role for an application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { "/v3/role" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse saveRole(HttpServletRequest request, HttpServletResponse response, + @RequestBody Role role) throws Exception { + Map res = getMethod(request, response); + PortalRestResponse out = null; + try { + out = (PortalRestResponse) invokeMethod(res, request, response, role); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + return out; + } + + @ApiOperation(value = "Gets v2 role information for an application which is upgraded to newer version.", response = CentralV2Role.class, responseContainer = "Json") + @RequestMapping(value = { "/v3/role/{role_id}" }, method = RequestMethod.GET, produces = "application/json") + public CentralV2Role getRoleInfo(HttpServletRequest request, HttpServletResponse response, + @PathVariable("role_id") Long roleId) throws Exception { + Map res = getMethod(request, response); + CentralV2Role role = null; + try { + role = (CentralV2Role) invokeMethod(res, request, response, roleId); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo failed", e); + } + return role; + + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Gets all active Users of application", response = String.class, responseContainer = "Json") + @RequestMapping(value = { "/v3/users" }, method = RequestMethod.GET, produces = "application/json") + public List getUsersOfApplication(HttpServletRequest request, HttpServletResponse response) + throws Exception { + Map res = getMethod(request, response); + List users = null; + try { + users = (List) invokeMethod(res, request, response); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getUsersOfApplication failed", e); + } + return users; + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Gets all role functions for an application which is upgraded to newer version.", response = CentralV2RoleFunction.class, responseContainer = "Json") + @RequestMapping(value = { "/v3/functions" }, method = RequestMethod.GET, produces = "application/json") + public List getRoleFunctionsList(HttpServletRequest request, HttpServletResponse response) + throws Exception { + Map res = getMethod(request, response); + List roleFunctionsList = null; + try { + roleFunctionsList = (List) invokeMethod(res, request, response); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunctionsList failed", e); + } + return roleFunctionsList; + } + + @ApiOperation(value = "Gets role information for an application provided by function code.", response = CentralV2RoleFunction.class, responseContainer = "Json") + @RequestMapping(value = { "/v3/function/{code}" }, method = RequestMethod.GET, produces = "application/json") + public CentralV2RoleFunction getRoleFunction(HttpServletRequest request, HttpServletResponse response, + @PathVariable("code") String code) throws Exception { + Map res = getMethod(request, response); + CentralV2RoleFunction roleFunction = null; + try { + roleFunction = (CentralV2RoleFunction) invokeMethod(res, request, response, code); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction failed", e); + } + return roleFunction; + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Saves role function for an application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { "/v3/roleFunction" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse saveRoleFunction(HttpServletRequest request, HttpServletResponse response, + @RequestBody String roleFunc) throws Exception { + PortalRestResponse result = null; + Map res = getMethod(request, response); + try { + result = (PortalRestResponse) invokeMethod(res, request, response, roleFunc); + return result; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Deletes role function for an application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { "/v3/roleFunction/{code}" }, method = RequestMethod.DELETE, produces = "application/json") + public PortalRestResponse deleteRoleFunction(HttpServletRequest request, HttpServletResponse response, + @PathVariable("code") String code) throws Exception { + PortalRestResponse result = null; + Map res = getMethod(request, response); + try { + result = (PortalRestResponse) invokeMethod(res, request, response, code); + return result; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunction failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "deletes roles for an application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { "/v3/deleteRole/{roleId}" }, method = RequestMethod.DELETE, produces = "application/json") + public PortalRestResponse deleteRole(HttpServletRequest request, HttpServletResponse response, + @PathVariable("roleId") Long roleId) throws Exception { + PortalRestResponse result = null; + Map res = getMethod(request, response); + try { + result = (PortalRestResponse) invokeMethod(res, request, response, roleId); + return result; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "deleteRole failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Gets active roles for an application.", response = CentralV2Role.class, responseContainer = "Json") + @RequestMapping(value = { "/v3/activeRoles" }, method = RequestMethod.GET, produces = "application/json") + public List getActiveRoles(HttpServletRequest request, HttpServletResponse response) + throws Exception { + List cenRole = null; + Map res = getMethod(request, response); + try { + cenRole = (List) invokeMethod(res, request, response); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles failed", e); + } + return cenRole; + } + + @ApiOperation(value = "Gets ecompUser of an application.", response = CentralUser.class, responseContainer = "List") + @RequestMapping(value = { "/v4/user/{loginId}" }, method = RequestMethod.GET, produces = "application/json") + public String getEcompUser(HttpServletRequest request, HttpServletResponse response, + @PathVariable("loginId") String loginId) throws Exception { + Map res = getMethod(request, response); + String answer = null; + try { + answer = (String) invokeMethod(res, request, response, loginId); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getEcompUser failed", e); + } + return answer; + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Gets user ecomp role for an application.", response = CentralUser.class, responseContainer = "List") + @RequestMapping(value = { "/v4/roles" }, method = RequestMethod.GET, produces = "application/json") + public List getEcompRolesOfApplication(HttpServletRequest request, HttpServletResponse response) + throws Exception { + Map res = getMethod(request, response); + List answer = null; + try { + answer = (List) invokeMethod(res, request, response); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getEcompRolesOfApplication failed", e); + } + return answer; + } + + @ApiOperation(value = "Gets session slot-check interval, a duration in milliseconds.", response = Integer.class) + @RequestMapping(value = { + "/v3/getSessionSlotCheckInterval" }, method = RequestMethod.GET, produces = "application/json") + public Integer getSessionSlotCheckInterval(HttpServletRequest request, HttpServletResponse response) + throws Exception { + Map res = getMethod(request, response); + Integer ans = null; + try { + ans = (Integer) invokeMethod(res, request, response); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getSessionSlotCheckInterval failed", e); + } + return ans; + } + + @ApiOperation(value = "Extends session timeout values for all on-boarded applications.", response = Boolean.class) + @RequestMapping(value = { "/v3/extendSessionTimeOuts" }, method = RequestMethod.POST) + public Boolean extendSessionTimeOuts(HttpServletRequest request, HttpServletResponse response, + @RequestParam String sessionMap) throws Exception { + Map res = getMethod(request, response); + Boolean ans = null; + try { + ans = (Boolean) invokeMethod(res, request, response, sessionMap); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "extendSessionTimeOuts failed", e); + } + return ans; + } + + @ApiOperation(value = "Gets javascript with functions that support gathering and reporting web analytics.", response = String.class) + @RequestMapping(value = { "/v3/analytics" }, method = RequestMethod.GET, produces = "application/javascript") + public String getAnalyticsScript(HttpServletRequest request, HttpServletResponse response) throws Exception { + Map res = getMethod(request, response); + String ans = null; + try { + ans = (String) invokeMethod(res, request, response); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getAnalyticsScript failed", e); + } + return ans; + } + + @RequestMapping(value = { "/v3/storeAnalytics" }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + @ApiOperation(value = "Accepts data from partner applications with web analytics data.", response = PortalAPIResponse.class) + public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, HttpServletResponse response, + @RequestBody Analytics analyticsMap) throws Exception { + Map res = getMethod(request, response); + PortalAPIResponse ans = new PortalAPIResponse(true, "error"); + try { + ans = (PortalAPIResponse) invokeMethod(res, request, response, analyticsMap); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "storeAnalyticsScript failed", e); + } + return ans; + + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Bulk upload functions for an application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { + "/v3/upload/portal/functions" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse bulkUploadFunctions(HttpServletRequest request, HttpServletResponse response) + throws Exception { + PortalRestResponse result = null; + Map res = getMethod(request, response); + try { + result = (PortalRestResponse) invokeMethod(res, request, response); + return result; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Bulk upload roles for an application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { "/v3/upload/portal/roles" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse bulkUploadRoles(HttpServletRequest request, HttpServletResponse response) + throws Exception { + PortalRestResponse result = null; + Map res = getMethod(request, response); + try { + result = (PortalRestResponse) invokeMethod(res, request, response); + return result; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Bulk upload role functions for an application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { + "/v3/upload/portal/roleFunctions" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse bulkUploadRoleFunctions(HttpServletRequest request, HttpServletResponse response) + throws Exception { + PortalRestResponse result = null; + Map res = getMethod(request, response); + try { + result = (PortalRestResponse) invokeMethod(res, request, response); + return result; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoleFunctions failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Bulk upload user roles for an application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { + "/v3/upload/portal/userRoles" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse bulkUploadUserRoles(HttpServletRequest request, HttpServletResponse response) + throws Exception { + PortalRestResponse result = null; + Map res = getMethod(request, response); + try { + result = (PortalRestResponse) invokeMethod(res, request, response); + return result; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadUserRoles failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Bulk upload users for renamed role of an application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { + "/v3/upload/portal/userRole/{roleId}" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse bulkUploadUsersSingleRole(HttpServletRequest request, + HttpServletResponse response, @PathVariable Long roleId) throws Exception { + PortalRestResponse result = null; + Map res = getMethod(request, response); + try { + result = (PortalRestResponse) invokeMethod(res, request, response, roleId); + return result; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadUsersSingleRole failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Bulk upload functions for an partner application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { + "/v3/upload/partner/functions" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse bulkUploadPartnerFunctions(HttpServletRequest request, + HttpServletResponse response) throws Exception { + PortalRestResponse result = null; + Map res = getMethod(request, response); + try { + result = (PortalRestResponse) invokeMethod(res, request, response); + return result; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerFunctions failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + } + + // not using + @SuppressWarnings("unchecked") + @ApiOperation(value = "Bulk upload roles for an partner application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { "/v3/upload/partner/roles" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse bulkUploadPartnerRoles(HttpServletRequest request, HttpServletResponse response, + @RequestBody List upload) throws Exception { + PortalRestResponse result = null; + Map res = getMethod(request, response); + try { + result = (PortalRestResponse) invokeMethod(res, request, response, upload); + return result; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerRoles failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Bulk upload role functions for an partner application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { + "/v3/upload/partner/roleFunctions" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse bulkUploadPartnerRoleFunctions(HttpServletRequest request, + HttpServletResponse response) throws Exception { + PortalRestResponse result = null; + Map res = getMethod(request, response); + try { + result = (PortalRestResponse) invokeMethod(res, request, response); + return result; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerRoleFunctions failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Gets all functions along with global functions", response = List.class, responseContainer = "Json") + @RequestMapping(value = { "/v3/menuFunctions" }, method = RequestMethod.GET, produces = "application/json") + public List getMenuFunctions(HttpServletRequest request, HttpServletResponse response) throws Exception { + List functionsList = null; + Map res = getMethod(request, response); + try { + functionsList = (List) invokeMethod(res, request, response); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctions failed", e); + } + return functionsList; + } + + private String getPatchNumber() { + String response = "0"; + try { + Attributes attributes = manifestService.getWebappManifest(); + response = attributes.getValue("Build-Number"); + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "getPatchNumber failed", ex); + } + return response; + } + + @SuppressWarnings("rawtypes") + private List getObject(HttpServletRequest request, HttpServletResponse response) { + Map beans = context.getBeansWithAnnotation(ApiVersion.class); + @SuppressWarnings("unchecked") + List beansList = new ArrayList(beans.values()); + return beansList; + + } + + private Map getMethod(HttpServletRequest request, HttpServletResponse response) { + Method finalmethod = null; + String url = request.getRequestURI(); + String version = ""; + String service = ""; + Object currentObject = null; + Map res = new HashMap(); + String[] uriArray = url.split("/auxapi"); + List minorversionList = new ArrayList<>(); + if (uriArray.length > 1) { + service = uriArray[1]; + } + int first = service.indexOf("/"); + int second = service.indexOf("/", first + 1); + version = service.substring(first + 1, second); + int min = minorVersion; + if (request.getHeader("MinorVersion") != null) { + min = Integer.parseInt(request.getHeader("MinorVersion")); + } + res.put("min", version+"."+min); + res.put("service", service); + List objList = getObject(request, response); + String requestedApiMethodType = request.getMethod(); + String majorVersion = latestMajorVersionOfService(objList, service, version, requestedApiMethodType); + int latestMinorVersion = latestMinorVersionOfService(objList, service, version, requestedApiMethodType); + res.put("majorVersion", majorVersion); + res.put("latestMinorVersion", String.valueOf(latestMinorVersion)); + outerloop: for (Object obj : objList) { + final List allMethods = getAllMethodsOfClass(obj); + for (final Method method : allMethods) { + if (method.isAnnotationPresent(ApiVersion.class)) { + ApiVersion annotInstance = method.getAnnotation(ApiVersion.class); + Pattern p = Pattern.compile(annotInstance.service(), + Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); + Matcher matcher = p.matcher(service); + boolean b = matcher.matches(); + logger.debug(EELFLoggerDelegate.debugLogger, "Requested Servie is:" + service + + "Requested MinVersion is:" + min + "Requested MajorVersion is: " + version); + if (annotInstance.max().equals(version) && b && annotInstance.min() == min + && annotInstance.method().equals(request.getMethod())) { + finalmethod = method; + currentObject = obj; + res.put("method", method); + res.put("Obj", obj); + break outerloop; + } + } + } + } + return res; + } + + private String latestMajorVersionOfService(List objList, String service, String reuqestedVersion, + String requestedApiMethodType) { + Integer majorVersion = 0; + String serviceEndPoint = service; + int firstindex = serviceEndPoint.indexOf("/"); + int secondindex = serviceEndPoint.indexOf("/", firstindex + 1); + serviceEndPoint = serviceEndPoint.substring(secondindex + 1); + + List latestMajorVersionList = new ArrayList<>(); + for (Object obj : objList) { + final List allMethods = getAllMethodsOfClass(obj); + for (final Method method : allMethods) { + if (method.isAnnotationPresent(ApiVersion.class)) { + ApiVersion annotInstance = method.getAnnotation(ApiVersion.class); + String endpoint = annotInstance.service(); + int first = endpoint.indexOf("/"); + int second = endpoint.indexOf("/", first + 1); + endpoint = endpoint.substring(second + 1); + Pattern p = Pattern.compile(endpoint, + Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); + Matcher matcher = p.matcher(serviceEndPoint); + boolean b = matcher.matches(); + if (b && annotInstance.method().equals(requestedApiMethodType)) { + int index1 = annotInstance.service().indexOf("/"); + int index2 = annotInstance.service().indexOf("/", index1 + 1); + String majorversion = annotInstance.service().substring(index1 + 2, index2); + latestMajorVersionList.add(Integer.parseInt(majorversion)); + } + } + } + } + majorVersion = Collections.max(latestMajorVersionList); + String majorVersionWithLastestMin = "/v"+String.valueOf(majorVersion)+"/"+serviceEndPoint; + int latestMinorVersion = latestMinorVersionOfService(objList, majorVersionWithLastestMin, "v"+String.valueOf(majorVersion), requestedApiMethodType); + return majorVersion+"."+latestMinorVersion; + } + + private List getAllMethodsOfClass(Object obj) { + List allMethods = new ArrayList<>(); + Class objClz = obj.getClass(); + if (org.springframework.aop.support.AopUtils.isAopProxy(obj)) { + objClz = org.springframework.aop.support.AopUtils.getTargetClass(obj); + } + allMethods = new ArrayList(Arrays.asList(objClz.getMethods())); + allMethods.removeIf(s -> !(s.isAnnotationPresent(ApiVersion.class))); + return allMethods; + } + + private Integer latestMinorVersionOfService(List objList, String service, String reuqestedVersion, + String requestedApiMethodType) { + Integer minVersion = 0; + String serviceEndPoint = service; + List latestMinorVersionList = new ArrayList<>(); + for (Object obj : objList) { + final List allMethods = getAllMethodsOfClass(obj); + for (final Method method : allMethods) { + if (method.isAnnotationPresent(ApiVersion.class)) { + ApiVersion annotInstance = method.getAnnotation(ApiVersion.class); + String endpoint = annotInstance.service(); + + Pattern p = Pattern.compile(endpoint, + Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); + Matcher matcher = p.matcher(serviceEndPoint); + boolean b = matcher.matches(); + if (annotInstance.max().equals(reuqestedVersion) && b + && annotInstance.method().equals(requestedApiMethodType)) { + int minorversion = annotInstance.min(); + latestMinorVersionList.add(minorversion); + } + } + } + } + minVersion = Collections.max(latestMinorVersionList); + return minVersion; + } + + private HttpServletResponse setResponse(HttpServletResponse response, String requestedMinVersion, + String majorVersion, String latestMinorVersion, String service) { + response.setHeader("X-MinorVersion", requestedMinVersion.toUpperCase()); + response.setHeader("X-PatchVersion", getPatchNumber()); + response.setHeader("X-LatestVersion", "V"+majorVersion); + return response; + } + + /** + * + * @param res + * @param args + * method parameters(Maintain HttpServletRequest at 0th position + * and HttpServletResponse at 1th position in args array) + * @return + * @throws Exception + */ + private Object invokeMethod(Map res, Object... args) throws Exception { + Method method = (Method) res.get("method"); + Object obj = res.get("Obj"); + Object responseObj = null; + String min = res.get("min").toString(); + String majorVersion = res.get("majorVersion").toString(); + String latestMinorVersion = res.get("latestMinorVersion").toString(); + String service = res.get("service").toString(); + HttpServletRequest request = (HttpServletRequest) args[0]; + HttpServletResponse response = (HttpServletResponse) args[1]; + setResponse(response, min, majorVersion, latestMinorVersion, service); + final Map errorMap = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + String reason = ""; + try { + if (method != null && obj != null) { + responseObj = method.invoke(obj, args); + } else { + errorMap.put("error", "Requested api is not available"); + reason = mapper.writeValueAsString(errorMap); + response.getWriter().write(reason); + logger.debug(EELFLoggerDelegate.debugLogger, "Requested api " + request.getRequestURI() + + "is not available with minorVersion " + request.getHeader("MinorVersion")); + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + } + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + logger.error(EELFLoggerDelegate.errorLogger, "Method :" + method + "invocation failed", e); + } + return responseObj; + } + + @Override + public void setApplicationContext(ApplicationContext context) throws BeansException { + this.context = context; + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Creates an application user with the specified roles.", response = PortalRestResponse.class) + @RequestMapping(value = { "/v3/userProfile" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse postUserProfile(HttpServletRequest request, + @RequestBody ExternalSystemUser extSysUser, HttpServletResponse response) { + PortalRestResponse result = null; + Map res = getMethod(request, response); + try { + result = (PortalRestResponse) invokeMethod(res, request, response, extSysUser); + return result; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "postUserProfile failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Updates an application user to have only the specified roles.", response = PortalRestResponse.class) + @RequestMapping(value = { "/v3/userProfile" }, method = RequestMethod.PUT, produces = "application/json") + public PortalRestResponse putUserProfile(HttpServletRequest request, + @RequestBody ExternalSystemUser extSysUser, HttpServletResponse response) { + PortalRestResponse result = null; + Map res = getMethod(request, response); + try { + result = (PortalRestResponse) invokeMethod(res, request, response, extSysUser); + return result; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "putUserProfile failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Processes a request to delete one or more application roles for one specified user who has roles.", response = PortalRestResponse.class) + @RequestMapping(value = { "/v3/userProfile" }, method = RequestMethod.DELETE, produces = "application/json") + public PortalRestResponse deleteUserProfile(HttpServletRequest request, + @RequestBody ExternalSystemUser extSysUser, HttpServletResponse response) { + PortalRestResponse result = null; + Map res = getMethod(request, response); + try { + result = (PortalRestResponse) invokeMethod(res, request, response, extSysUser); + return result; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "deleteUserProfile failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Accepts messages from external ticketing systems and creates notifications for Portal users.", response = PortalRestResponse.class) + @RequestMapping(value = { "/v3/ticketevent" }, method = RequestMethod.POST) + public PortalRestResponse handleRequest(HttpServletRequest request, HttpServletResponse response, + @RequestBody String ticketEventJson) throws Exception { + PortalRestResponse result = null; + Map res = getMethod(request, response); + try { + result = (PortalRestResponse) invokeMethod(res, request, response, ticketEventJson); + return result; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "handleRequest failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Creates a new user as a Portal administrator.", response = PortalRestResponse.class) + @RequestMapping(value = "/v3/portalAdmin", method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public PortalRestResponse postPortalAdmin(HttpServletRequest request, HttpServletResponse response, + @RequestBody EPUser epUser) { + PortalRestResponse result = null; + Map res = getMethod(request, response); + try { + result = (PortalRestResponse) invokeMethod(res, request, response, epUser); + return result; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "postPortalAdmin failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + } + + @ApiOperation(value = "Gets the specified application that is on-boarded in Portal.", response = OnboardingApp.class) + @RequestMapping(value = { "/v3/onboardApp/{appId}" }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public OnboardingApp getOnboardAppExternal(HttpServletRequest request, HttpServletResponse response, + @PathVariable("appId") Long appId) { + OnboardingApp result = new OnboardingApp(); + Map res = getMethod(request, response); + try { + result = (OnboardingApp) invokeMethod(res, request, response, appId); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getOnboardAppExternal failed", e); + } + return result; + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Adds a new application to Portal.", response = PortalRestResponse.class) + @RequestMapping(value = { "/v3/onboardApp" }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public PortalRestResponse postOnboardAppExternal(HttpServletRequest request, HttpServletResponse response, + @RequestBody OnboardingApp newOnboardApp) { + PortalRestResponse result = new PortalRestResponse<>(); + Map res = getMethod(request, response); + try { + result = (PortalRestResponse) invokeMethod(res, request, response, newOnboardApp); + return result; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "postOnboardAppExternal failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Updates information about an on-boarded application in Portal.", response = PortalRestResponse.class) + @RequestMapping(value = { "/v3/onboardApp/{appId}" }, method = RequestMethod.PUT, produces = "application/json") + @ResponseBody + public PortalRestResponse putOnboardAppExternal(HttpServletRequest request, HttpServletResponse response, + @PathVariable("appId") Long appId, @RequestBody OnboardingApp oldOnboardApp) { + PortalRestResponse result = new PortalRestResponse<>(); + Map res = getMethod(request, response); + try { + result = (PortalRestResponse) invokeMethod(res, request, response, appId, oldOnboardApp); + return result; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "putOnboardAppExternal failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + } + + @ApiOperation(value = "Creates a Portal user notification for roles identified in the content from an external application.", response = PortalAPIResponse.class) + @RequestMapping(value = { "/v3/publishNotification" }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public PortalAPIResponse publishNotification(HttpServletRequest request, + @RequestBody EpNotificationItem notificationItem, HttpServletResponse response) throws Exception { + PortalAPIResponse result = new PortalAPIResponse(true, "success"); + Map res = getMethod(request, response); + try { + result = (PortalAPIResponse) invokeMethod(res, request, response, notificationItem); + return result; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "publishNotification failed", e); + return new PortalAPIResponse(false, e.getMessage()); + } + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Gets favorite items within the functional menu for the current user.", response = FavoritesFunctionalMenuItemJson.class, responseContainer = "List") + @RequestMapping(value = { "/v3/getFavorites" }, method = RequestMethod.GET, produces = "application/json") + public List getFavoritesForUser(HttpServletRequest request, + HttpServletResponse response) throws Exception { + List favorites = null; + Map res = getMethod(request, response); + try { + favorites = (List) invokeMethod(res, request, response); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getFavoritesForUser failed", e); + } + return favorites; + } + + @SuppressWarnings("unchecked") + @ApiOperation(value = "Gets functional menu items appropriate for the current user.", response = FunctionalMenuItem.class, responseContainer = "List") + @RequestMapping(value = { + "/v3/functionalMenuItemsForUser" }, method = RequestMethod.GET, produces = "application/json") + public List getFunctionalMenuItemsForUser(HttpServletRequest request, + HttpServletResponse response) throws Exception { + List fnMenuItems = null; + Map res = getMethod(request, response); + try { + fnMenuItems = (List) invokeMethod(res, request, response); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getFunctionalMenuItemsForUser failed", e); + } + return fnMenuItems; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAccessRolesController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAccessRolesController.java index de6ae3cf..e0bf7b01 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAccessRolesController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAccessRolesController.java @@ -69,7 +69,6 @@ import org.onap.portalapp.portal.utils.EcompPortalUtils; import org.onap.portalapp.portal.utils.PortalConstants; import org.onap.portalsdk.core.domain.AuditLog; import org.onap.portalsdk.core.domain.Role; -import org.onap.portalsdk.core.domain.RoleFunction; import org.onap.portalsdk.core.domain.User; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.restful.domain.EcompRole; @@ -334,6 +333,7 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl @RequestMapping(value = { "/roleFunction" }, method = RequestMethod.POST, produces = "application/json") public PortalRestResponse saveRoleFunction(HttpServletRequest request, HttpServletResponse response, @RequestBody String roleFunc) throws Exception { + String status = "Successfully saved!"; try { fieldsValidation(request); String data = roleFunc; @@ -343,7 +343,11 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); CentralV2RoleFunction availableRoleFunction = mapper.readValue(data, CentralV2RoleFunction.class); CentralV2RoleFunction domainRoleFunction = null; + boolean isCentralV2Version = false; if(availableRoleFunction.getType()!=null && availableRoleFunction.getAction()!= null) { + isCentralV2Version = true; + } + if(isCentralV2Version) { String code = availableRoleFunction.getType()+"|"+availableRoleFunction.getCode()+"|"+availableRoleFunction.getAction(); domainRoleFunction = externalAccessRolesService.getRoleFunction(code, requestedApp.getUebKey()); @@ -353,7 +357,7 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl } boolean saveOrUpdateResponse = false; - if (domainRoleFunction != null && domainRoleFunction.getCode().equals(availableRoleFunction.getCode()) + if (domainRoleFunction != null && isCentralV2Version && domainRoleFunction.getCode().equals(availableRoleFunction.getCode()) && domainRoleFunction.getType().equals(availableRoleFunction.getType()) && domainRoleFunction.getAction().equals(availableRoleFunction.getAction())) { domainRoleFunction.setName(availableRoleFunction.getName()); @@ -363,13 +367,15 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl availableRoleFunction.setAppId(requestedApp.getId()); saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(availableRoleFunction, requestedApp); - } + } + + if(domainRoleFunction != null) { + status = "Successfully updated!"; + } if (saveOrUpdateResponse) { EPUser user = externalAccessRolesService.getUser(request.getHeader(LOGIN_ID)).get(0); EPApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0); - CentralV2RoleFunction function = externalAccessRolesService - .getRoleFunction(availableRoleFunction.getCode(), request.getHeader(UEBKEY)); - String activityCode = (function.getCode() == null) + String activityCode = (!status.equals("Successfully updated!")) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION; logger.info(EELFLoggerDelegate.applicationLogger, "saveRoleFunction: succeeded for app {}, function {}", @@ -401,7 +407,7 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl "Failed to saveRoleFunction for '" + availableRoleFunction.getCode() + "'", "Failed"); } } catch (Exception e) { - if (e.getMessage().contains(INVALID_UEB_KEY)) { + if (e.getMessage() == null ||e.getMessage().contains(INVALID_UEB_KEY)) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); }else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); @@ -409,7 +415,7 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction failed", e); return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); } - return new PortalRestResponse(PortalRestStatusEnum.OK, "Successfully Saved", "Success"); + return new PortalRestResponse(PortalRestStatusEnum.OK, status, "Success"); } @ApiOperation(value = "Deletes role function for an application.", response = PortalRestResponse.class, responseContainer = "Json") @@ -731,15 +737,16 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl @ApiOperation(value = "Bulk upload functions for an partner application.", response = PortalRestResponse.class, responseContainer = "Json") @RequestMapping(value = { "/upload/partner/functions" }, method = RequestMethod.POST, produces = "application/json") - public PortalRestResponse bulkUploadPartnerFunctions(HttpServletRequest request, HttpServletResponse response, @RequestBody List upload) throws Exception { + public PortalRestResponse bulkUploadPartnerFunctions(HttpServletRequest request, HttpServletResponse response) throws Exception { + Integer addedFunctions = 0; try { - externalAccessRolesService.bulkUploadPartnerFunctions(request.getHeader(UEBKEY), upload); + addedFunctions = externalAccessRolesService.bulkUploadPartnerFunctions(request.getHeader(UEBKEY)); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions failed", e); return new PortalRestResponse(PortalRestStatusEnum.ERROR, "Failed to bulkUploadFunctions", "Failed"); } - return new PortalRestResponse(PortalRestStatusEnum.OK, "Successfully added", "Success"); + return new PortalRestResponse(PortalRestStatusEnum.OK, "Successfully added: '"+addedFunctions+"' functions", "Success"); } @ApiOperation(value = "Bulk upload roles for an partner application.", response = PortalRestResponse.class, responseContainer = "Json") @@ -757,15 +764,16 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl @ApiOperation(value = "Bulk upload role functions for an partner application.", response = PortalRestResponse.class, responseContainer = "Json") @RequestMapping(value = { "/upload/partner/roleFunctions" }, method = RequestMethod.POST, produces = "application/json") - public PortalRestResponse bulkUploadPartnerRoleFunctions(HttpServletRequest request, HttpServletResponse response, @RequestBody List upload) throws Exception { + public PortalRestResponse bulkUploadPartnerRoleFunctions(HttpServletRequest request, HttpServletResponse response) throws Exception { + Integer addedRoleFunctions = 0; try { - externalAccessRolesService.bulkUploadPartnerRoleFunctions(request.getHeader(UEBKEY), upload); + addedRoleFunctions = externalAccessRolesService.bulkUploadPartnerRoleFunctions(request.getHeader(UEBKEY)); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles failed", e); return new PortalRestResponse(PortalRestStatusEnum.ERROR, "Failed to bulkUploadPartnerRoleFunctions", "Failed"); } - return new PortalRestResponse(PortalRestStatusEnum.OK, "Successfully added", "Success"); + return new PortalRestResponse(PortalRestStatusEnum.OK, "Successfully added: '"+addedRoleFunctions + "' role functions", "Success"); } @ApiOperation(value = "Gets all functions along with global functions", response = List.class, responseContainer = "Json") diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulVersionController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulVersionController.java new file mode 100644 index 00000000..588a888a --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAppsRestfulVersionController.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + */ +package org.onap.portalapp.portal.controller; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.portalapp.annotation.ApiVersion; +import org.onap.portalapp.portal.logging.aop.EPAuditLog; +import org.onap.portalapp.portal.transport.EpNotificationItem; +import org.onap.portalapp.portal.transport.FavoritesFunctionalMenuItemJson; +import org.onap.portalapp.portal.transport.FunctionalMenuItem; +import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; + +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +@ApiVersion +public class ExternalAppsRestfulVersionController implements BasicAuthenticationController { + + @Autowired + ExternalAppsRestfulController externalAppsRestfulController = new ExternalAppsRestfulController(); + + @ApiVersion(max = "v3", service = "/v3/publishNotification", min = 0,method = "POST") + public PortalAPIResponse publishNotification(HttpServletRequest request,HttpServletResponse response, EpNotificationItem notificationItem) + throws Exception { + return externalAppsRestfulController.publishNotification(request, notificationItem); + } + + @ApiVersion(max = "v3", service = "/v3/getFavorites", min = 0,method = "GET") + public List getFavoritesForUser(HttpServletRequest request, + HttpServletResponse response) throws Exception { + return externalAppsRestfulController.getFavoritesForUser(request, response); + } + + @ApiVersion(max = "v3", service = "/v3/functionalMenuItemsForUser", min = 0,method = "GET") + public List getFunctionalMenuItemsForUser(HttpServletRequest request, + HttpServletResponse response) throws Exception { + return externalAppsRestfulController.getFunctionalMenuItemsForUser(request, response); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java index afb5de17..f1628e02 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/HealthCheckController.java @@ -48,6 +48,7 @@ import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; +import org.onap.music.main.MusicUtil; import org.onap.portalapp.controller.EPUnRestrictedBaseController; import org.onap.portalapp.portal.listener.HealthMonitor; import org.onap.portalapp.portal.logging.aop.EPAuditLog; @@ -177,17 +178,29 @@ public class HealthCheckController extends EPUnRestrictedBaseController { dbInfo.dbPermissions = statusOk; } statusCollection.add(dbInfo); + + HealthStatusInfo CassandraStatusInfo = new HealthStatusInfo("Music-Cassandra"); + //CassandraStatusInfo.hostName = EcompPortalUtils.getMyHostName(); + CassandraStatusInfo.ipAddress = MusicUtil.getMyCassaHost(); + + if (!HealthMonitor.isCassandraStatusOk()) { + overallStatus = false; + CassandraStatusInfo.healthCheckStatus = statusDown; + CassandraStatusInfo.description = "Check the logs for more details"; + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.MusicHealthCheckCassandraError); + } + statusCollection.add(CassandraStatusInfo); - HealthStatusInfo uebInfo = new HealthStatusInfo("UEB"); - if (!HealthMonitor.isUebUp()) { - // As per test case review meeting, UEB is considered as - // critical as DB. Hence commenting - // overallStatus = false; - uebInfo.healthCheckStatus = statusDown; - uebInfo.description = "Check the logs for more details"; - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError); + HealthStatusInfo zookeeperStatusInfo = new HealthStatusInfo("Music-zookeeper"); + //zookeeperStatusInfo.hostName = EcompPortalUtils.getMyHostName(); + zookeeperStatusInfo.ipAddress = MusicUtil.getMyZkHost(); + if (!HealthMonitor.isZookeeperStatusOk()) { + overallStatus = false; + zookeeperStatusInfo.healthCheckStatus = statusDown; + zookeeperStatusInfo.description = "Check the logs for more details"; + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.MusicHealthCheckZookeeperError); } - statusCollection.add(uebInfo); + statusCollection.add(zookeeperStatusInfo); String json = ""; try { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java index a9f523b6..4956e3fd 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java @@ -60,6 +60,7 @@ import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.domain.EcompAuditLog; import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.onap.portalapp.portal.ecomp.model.UploadRoleFunctionExtSystem; import org.onap.portalapp.portal.exceptions.DuplicateRecordException; import org.onap.portalapp.portal.exceptions.InvalidApplicationException; import org.onap.portalapp.portal.exceptions.InvalidRoleException; @@ -78,7 +79,6 @@ import org.onap.portalapp.portal.utils.PortalConstants; import org.onap.portalapp.util.EPUserUtils; import org.onap.portalsdk.core.domain.AuditLog; import org.onap.portalsdk.core.domain.Role; -import org.onap.portalsdk.core.domain.RoleFunction; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.service.AuditService; import org.onap.portalsdk.core.util.SystemProperties; @@ -194,7 +194,7 @@ public class RoleManageController extends EPRestrictedBaseController { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); CentralV2Role domainRole = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey()); // role. toggle active ind - boolean active = domainRole.isActive(); + boolean active = domainRole.getActive(); domainRole.setActive(!active); String result = mapper.writeValueAsString(domainRole); @@ -329,6 +329,7 @@ public class RoleManageController extends EPRestrictedBaseController { domainRole = new CentralV2Role(); domainRole.setName(role.getName()); domainRole.setPriority(role.getPriority()); + domainRole.setActive(role.getActive()); if (role.getChildRoles() != null && role.getChildRoles().size() > 0) { for (Object childRole : childRoles) { domainRole.addChildRole((CentralV2Role) childRole); @@ -528,27 +529,7 @@ public class RoleManageController extends EPRestrictedBaseController { String activityCode = (isSave) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION; - logger.info(EELFLoggerDelegate.applicationLogger, - "saveRoleFunction: succeeded for app {}, function {}", app.getId(), code); - AuditLog auditLog = getAuditInfo(requestedUser, activityCode); - auditLog.setComments(EcompPortalUtils.truncateString("saveRoleFunction role for app:" - + app.getId() + " and function:'" + code + "'", - PortalConstants.AUDIT_LOG_COMMENT_SIZE)); - auditService.logActivity(auditLog, null); - MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, - EPEELFLoggerAdvice.getCurrentDateTimeUTC()); - MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, - EPEELFLoggerAdvice.getCurrentDateTimeUTC()); - EcompPortalUtils.calculateDateTimeDifferenceForLog( - MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), - MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); - logger.info(EELFLoggerDelegate.auditLogger, - EPLogUtil.formatAuditLogMessage("RoleManageController.saveRoleFunction", activityCode, - String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(), - code)); - MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); - MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); - MDC.remove(SystemProperties.MDC_TIMER); + logExterlaAuthRoleFunctionActivity(code, requestedUser, app, activityCode); } } else throw new NonCentralizedAppException(requestedApp.getName() + " is not Centralized Application"); @@ -564,6 +545,30 @@ public class RoleManageController extends EPRestrictedBaseController { } return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Saved Successfully!", "Success"); } + + private void logExterlaAuthRoleFunctionActivity(String code, EPUser requestedUser, EPApp app, String activityCode) { + logger.info(EELFLoggerDelegate.applicationLogger, + "saveRoleFunction: succeeded for app {}, function {}", app.getId(), code); + AuditLog auditLog = getAuditInfo(requestedUser, activityCode); + auditLog.setComments(EcompPortalUtils.truncateString("saveRoleFunction role for app:" + + app.getId() + " and function:'" + code + "'", + PortalConstants.AUDIT_LOG_COMMENT_SIZE)); + auditService.logActivity(auditLog, null); + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, + EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, + EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + EcompPortalUtils.calculateDateTimeDifferenceForLog( + MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + logger.info(EELFLoggerDelegate.auditLogger, + EPLogUtil.formatAuditLogMessage("RoleManageController.saveRoleFunction", activityCode, + String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(), + code)); + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + } @@ -733,7 +738,7 @@ public class RoleManageController extends EPRestrictedBaseController { Iterator availableChildRolesIterator = availableChildRoles.iterator(); while (availableChildRolesIterator.hasNext()) { CentralV2Role role = availableChildRolesIterator.next(); - if (!role.isActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) { + if (!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)) { availableChildRolesIterator.remove(); } } @@ -784,4 +789,29 @@ public class RoleManageController extends EPRestrictedBaseController { EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); response.getWriter().write("Unauthorized User"); } + + @RequestMapping(value = { "/portalApi/uploadRoleFunction/{appId}" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse bulkUploadRoleFunc(HttpServletRequest request, HttpServletResponse response, + @RequestBody UploadRoleFunctionExtSystem data, @PathVariable("appId") Long appId) { + EPUser user = EPUserUtils.getUserSession(request); + try { + EPApp app = appService.getApp(appId); + if (isAuthorizedUser(user, app)) { + fieldsValidation(app); + externalAccessRolesService.bulkUploadRoleFunc(data, app); + String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION; + String code = data.getName()+","+data.getType()+ PIPE + data.getInstance() + PIPE + data.getAction(); + logExterlaAuthRoleFunctionActivity(code , user, app, activityCode); + } else { + logger.info(EELFLoggerDelegate.auditLogger, + "RoleManageController.syncRoles, Unauthorized user:" + user.getOrgUserId()); + EcompPortalUtils.setBadPermissions(user, response, "createAdmin"); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure"); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed bulkUploadRoleFunc!", e); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Uploaded Role Function successfully!", "Success"); + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RolesApprovalSystemVersionController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RolesApprovalSystemVersionController.java new file mode 100644 index 00000000..404fb310 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RolesApprovalSystemVersionController.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + */ +package org.onap.portalapp.portal.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.portalapp.annotation.ApiVersion; +import org.onap.portalapp.externalsystemapproval.model.ExternalSystemUser; +import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; +import org.onap.portalapp.portal.logging.aop.EPAuditLog; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; + +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +@ApiVersion +public class RolesApprovalSystemVersionController implements BasicAuthenticationController { + + @Autowired + RolesApprovalSystemController rolesApprovalSystemController; + + @ApiVersion(max = "v3", service = "/v3/userProfile", min = 0, method = "POST") + public PortalRestResponse postUserProfile(HttpServletRequest request, + HttpServletResponse response, ExternalSystemUser extSysUser) { + return rolesApprovalSystemController.postUserProfile(request, extSysUser, response); + } + + @ApiVersion(max = "v3", service = "/v3/userProfile", min = 0, method = "PUT") + public PortalRestResponse putUserProfile(HttpServletRequest request, + HttpServletResponse response, ExternalSystemUser extSysUser) { + return rolesApprovalSystemController.putUserProfile(request, extSysUser, response); + } + + @ApiVersion(max = "v3", service = "/v3/userProfile", min = 0, method = "DELETE") + public PortalRestResponse deleteUserProfile(HttpServletRequest request, + HttpServletResponse response ,ExternalSystemUser extSysUser) { + return rolesApprovalSystemController.deleteUserProfile(request, extSysUser, response); + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RolesController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RolesController.java new file mode 100644 index 00000000..c61fb43b --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RolesController.java @@ -0,0 +1,207 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + */ +package org.onap.portalapp.portal.controller; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.portalapp.annotation.ApiVersion; +import org.onap.portalapp.portal.domain.CentralV2RoleFunction; +import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; +import org.onap.portalapp.portal.logging.aop.EPAuditLog; +import org.onap.portalapp.portal.transport.CentralUser; +import org.onap.portalapp.portal.transport.CentralV2Role; +import org.onap.portalsdk.core.domain.Role; +import org.onap.portalsdk.core.domain.RoleFunction; +import org.onap.portalsdk.core.restful.domain.EcompRole; +import org.onap.portalsdk.core.restful.domain.EcompUser; +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.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import io.swagger.annotations.ApiOperation; + +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +@ApiVersion +public class RolesController implements BasicAuthenticationController { + + final String LOGINID_PATTERN = "/v3/user/[a-zA-Z0-9]{1,25}$"; + final String FUNCTION_CD_PATTERN = "/v3/function/[a-zA-Z0-9_-]{1,75}$"; + + final String DELETE_ROLEFUNCTION = "/v3/roleFunction/[a-zA-Z0-9_-]{1,75}$"; + + @Autowired + ExternalAccessRolesController externalAccessRolesController = new ExternalAccessRolesController(); + + @ApiOperation(value = "Gets roles for an application which is upgraded to newer version.", response = CentralV2Role.class, responseContainer = "Json") + @ApiVersion(max = "v3", service = "/v3/roles", min = 0, method = "GET") + public List getV2RolesForApp(HttpServletRequest request, HttpServletResponse response) + throws Exception { + return externalAccessRolesController.getV2RolesForApp(request, response); + } + + @ApiVersion(max = "v3", service = LOGINID_PATTERN, min = 0, method = "GET") + public String getV2UserList(HttpServletRequest request, HttpServletResponse response, String loginId) + throws Exception { + return externalAccessRolesController.getV2UserList(request, response, loginId); + } + + @ApiVersion(max = "v3", service = "/v3/role", min = 0, method = "POST") + public PortalRestResponse saveRole(HttpServletRequest request, HttpServletResponse response, Role role) + throws Exception { + return externalAccessRolesController.saveRole(request, response, role); + } + + @ApiVersion(max = "v3", service = "/v3/role/[0-9]{1,25}$", min = 0, method = "GET") + public CentralV2Role getV2RoleInfo(HttpServletRequest request, HttpServletResponse response, Long roleId) + throws Exception { + return externalAccessRolesController.getV2RoleInfo(request, response, roleId); + } + + @ApiVersion(max = "v3", service = "/v3/users", min = 0, method = "GET") + public List getUsersOfApplication(HttpServletRequest request, HttpServletResponse response) + throws Exception { + return externalAccessRolesController.getUsersOfApplication(request, response); + } + + @ApiVersion(max = "v3", service = "/v3/functions", min = 0, method = "GET") + public List getRoleFunctionsList(HttpServletRequest request, HttpServletResponse response) + throws Exception { + return externalAccessRolesController.getV2RoleFunctionsList(request, response); + } + + @ApiVersion(max = "v3", service = FUNCTION_CD_PATTERN, min = 0, method = "GET") + public CentralV2RoleFunction getRoleFunction(HttpServletRequest request, HttpServletResponse response, String code) + throws Exception { + return externalAccessRolesController.getV2RoleFunction(request, response, code); + } + + @ApiVersion(max = "v3", service = "/v3/roleFunction", min = 0, method = "POST") + public PortalRestResponse saveRoleFunction(HttpServletRequest request, HttpServletResponse response, + String roleFunc) throws Exception { + return externalAccessRolesController.saveRoleFunction(request, response, roleFunc); + } + + @ApiVersion(max = "v3", service = DELETE_ROLEFUNCTION, min = 0, method = "DELETE") + public PortalRestResponse deleteRoleFunction(HttpServletRequest request, HttpServletResponse response, + String code) throws Exception { + return externalAccessRolesController.deleteRoleFunction(request, response, code); + } + + @ApiVersion(max = "v3", service = "/v3/deleteRole/[0-9]{1,25}$", min = 0, method = "DELETE") + public PortalRestResponse deleteRole(HttpServletRequest request, HttpServletResponse response, Long roleId) + throws Exception { + return externalAccessRolesController.deleteRole(request, response, roleId); + } + + @ApiVersion(max = "v3", service = "/v3/activeRoles", min = 0, method = "GET") + public List getV2ActiveRoles(HttpServletRequest request, HttpServletResponse response) + throws Exception { + return externalAccessRolesController.getV2ActiveRoles(request, response); + } + + @ApiVersion(max = "v3", service = "/v3/upload/portal/functions", min = 0, method = "POST") + public PortalRestResponse bulkUploadFunctions(HttpServletRequest request, HttpServletResponse response) + throws Exception { + return externalAccessRolesController.bulkUploadFunctions(request, response); + } + + @ApiVersion(max = "v3", service = "/v3/upload/portal/roles", min = 0, method = "POST") + public PortalRestResponse bulkUploadRoles(HttpServletRequest request, HttpServletResponse response) + throws Exception { + return externalAccessRolesController.bulkUploadRoles(request, response); + } + + @ApiVersion(max = "v3", service = "/v3/upload/portal/roleFunctions", min = 0, method = "POST") + public PortalRestResponse bulkUploadRoleFunctions(HttpServletRequest request, HttpServletResponse response) + throws Exception { + return externalAccessRolesController.bulkUploadRoleFunctions(request, response); + } + + @ApiVersion(max = "v3", service = "/v3/upload/portal/userRoles", min = 0, method = "POST") + public PortalRestResponse bulkUploadUserRoles(HttpServletRequest request, HttpServletResponse response) + throws Exception { + return externalAccessRolesController.bulkUploadUserRoles(request, response); + } + + @ApiVersion(max = "v3", service = "/v3/upload/portal/userRole/[0-9]{1,25}$", min = 0, method = "POST") + public PortalRestResponse bulkUploadUsersSingleRole(HttpServletRequest request, + HttpServletResponse response, Long roleId) throws Exception { + return externalAccessRolesController.bulkUploadUsersSingleRole(request, response, roleId); + } + + @ApiVersion(max = "v3", service = "/v3/upload/partner/functions", min = 0, method = "POST") + public PortalRestResponse bulkUploadPartnerFunctions(HttpServletRequest request, + HttpServletResponse response) throws Exception { + return externalAccessRolesController.bulkUploadPartnerFunctions(request, response); + } +//not using this + @ApiVersion(max = "v3", service = "/v3/upload/partner/roles", min = 0, method = "POST") + public PortalRestResponse bulkUploadPartnerRoles(HttpServletRequest request, HttpServletResponse response, + List upload) throws Exception { + return externalAccessRolesController.bulkUploadPartnerRoles(request, response, upload); + } + + @ApiVersion(max = "v3", service = "/v3/upload/partner/roleFunctions", min = 0, method = "POST") + public PortalRestResponse bulkUploadPartnerRoleFunctions(HttpServletRequest request, + HttpServletResponse response) throws Exception { + return externalAccessRolesController.bulkUploadPartnerRoleFunctions(request, response); + } + + @ApiVersion(max = "v3", service = "/v3/menuFunctions", min = 0, method = "GET") + public List getMenuFunctions(HttpServletRequest request, HttpServletResponse response) throws Exception { + return externalAccessRolesController.getMenuFunctions(request, response); + } + + @ApiVersion(max = "v4", service = "/v4/user/[a-zA-Z0-9]{1,25}$", min = 0, method = "GET") + public String getEcompUser(HttpServletRequest request, HttpServletResponse response, String loginId) + throws Exception { + return externalAccessRolesController.getEcompUser(request, response, loginId); + } + + @ApiVersion(max = "v4", service = "/v4/roles", min = 0, method = "GET") + public List getEcompRolesOfApplication(HttpServletRequest request, HttpServletResponse response) + throws Exception { + return externalAccessRolesController.getEcompRolesOfApplication(request, response); + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/TicketEventVersionController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/TicketEventVersionController.java new file mode 100644 index 00000000..cd87507b --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/TicketEventVersionController.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + */ +package org.onap.portalapp.portal.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.portalapp.annotation.ApiVersion; +import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; +import org.onap.portalapp.portal.logging.aop.EPAuditLog; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; + +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +@ApiVersion +public class TicketEventVersionController implements BasicAuthenticationController { + + @Autowired + TicketEventController ticketEventController; + + @ApiVersion(max = "v3", service = "/v3/ticketevent", min = 0, method = "POST") + public PortalRestResponse handleRequest(HttpServletRequest request, HttpServletResponse response, + String ticketEventJson) throws Exception { + return ticketEventController.handleRequest(request, response, ticketEventJson); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppVersionController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppVersionController.java new file mode 100644 index 00000000..952ca75f --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WebAnalyticsExtAppVersionController.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + */ +package org.onap.portalapp.portal.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.portalapp.annotation.ApiVersion; +import org.onap.portalapp.portal.logging.aop.EPAuditLog; +import org.onap.portalapp.portal.transport.Analytics; +import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; + +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +@ApiVersion +public class WebAnalyticsExtAppVersionController { + + @Autowired + WebAnalyticsExtAppController webAnalyticsExtAppController; + + @ApiVersion(max = "v3", service = "/v3/analytics", min = 0,method = "GET") + public String getAnalyticsScript(HttpServletRequest request, HttpServletResponse response) throws Exception { + return webAnalyticsExtAppController.getAnalyticsScript(request); + } + + @ApiVersion(max = "v3", service = "/v3/storeAnalytics", min = 0,method = "POST") + public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, HttpServletResponse response, Analytics analyticsMap) throws Exception { + return webAnalyticsExtAppController.storeAnalyticsScript(request, analyticsMap); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WidgetsCatalogController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WidgetsCatalogController.java index f43930f6..d05fe014 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WidgetsCatalogController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/WidgetsCatalogController.java @@ -49,6 +49,7 @@ import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.commons.lang.StringUtils; import org.onap.portalapp.controller.EPRestrictedBaseController; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.domain.MicroserviceParameter; @@ -62,6 +63,7 @@ import org.onap.portalapp.portal.logging.aop.EPAuditLog; import org.onap.portalapp.portal.service.ConsulHealthService; import org.onap.portalapp.portal.service.MicroserviceService; import org.onap.portalapp.portal.service.WidgetParameterService; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; import org.onap.portalapp.portal.utils.EcompPortalUtils; import org.onap.portalapp.util.EPUserUtils; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; @@ -98,6 +100,8 @@ public class WidgetsCatalogController extends EPRestrictedBaseController { private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetsCatalogController.class); private static final String MS_WIDGET_LOCAL_PORT = "microservices.widget.local.port"; + + private static final String UNAUTHORIZED_OR_FORBIDDEN_FOR_A_DISABLED_USER = "Unauthorized or Forbidden for a disabled user"; private RestTemplate template = new RestTemplate(); @@ -135,7 +139,7 @@ public class WidgetsCatalogController extends EPRestrictedBaseController { ResponseEntity ans = template.exchange( EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, - SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT)) + SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT)) + "/widget/microservices/widgetCatalog/" + loginName, HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), List.class); widgets = ans.getBody(); @@ -155,7 +159,7 @@ public class WidgetsCatalogController extends EPRestrictedBaseController { ResponseEntity ans = template.exchange( EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, - SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT)) + SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT)) + "/widget/microservices/widgetCatalog", HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), List.class); widgets = ans.getBody(); @@ -215,7 +219,7 @@ public class WidgetsCatalogController extends EPRestrictedBaseController { respond = template.postForObject( EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, - SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT)) + SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT)) + "/widget/microservices/widgetCatalog/" + widgetId, new HttpEntity<>(multipartRequest, WidgetServiceHeaders.getInstance()), String.class); File f = new File(tmpFolderName + fileName); @@ -236,6 +240,12 @@ public class WidgetsCatalogController extends EPRestrictedBaseController { @RequestMapping(value = { "/portalApi/microservices/widgetCatalog" }, method = RequestMethod.POST) public String createWidgetCatalog(HttpServletRequest request) throws Exception { + + if (StringUtils.isNotBlank(SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_UPLOAD_FLAG)) + && SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_UPLOAD_FLAG).equalsIgnoreCase("false")) { + return UNAUTHORIZED_OR_FORBIDDEN_FOR_A_DISABLED_USER; + } + MultipartHttpServletRequest mRequest; MultiValueMap multipartRequest = new LinkedMultiValueMap<>(); String fileName; @@ -260,7 +270,7 @@ public class WidgetsCatalogController extends EPRestrictedBaseController { respond = template.postForObject( EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, - SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT)) + SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT)) + "/widget/microservices/widgetCatalog", new HttpEntity<>(multipartRequest, WidgetServiceHeaders.getInstance()), String.class); File f = new File(tmpFolderName + fileName); @@ -314,7 +324,7 @@ public class WidgetsCatalogController extends EPRestrictedBaseController { Long serviceId = template.exchange( EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, - SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT)) + SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT)) + "/widget/microservices/widgetCatalog/parameters/" + widgetId, HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), Long.class).getBody(); if (serviceId == null) { @@ -361,7 +371,7 @@ public class WidgetsCatalogController extends EPRestrictedBaseController { .exchange( EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, - SystemProperties.getProperty(MS_WIDGET_LOCAL_PORT)) + SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_LOCAL_PORT)) + "/widget/microservices/download/" + widgetId, HttpMethod.GET, new HttpEntity<>(WidgetServiceHeaders.getInstance()), byte[].class) .getBody(); @@ -414,4 +424,16 @@ public class WidgetsCatalogController extends EPRestrictedBaseController { } return new PortalRestResponse(PortalRestStatusEnum.OK, "SUCCESS", ""); } + + @RequestMapping(value = { "/portalApi/microservices/uploadFlag" }, method = RequestMethod.GET) + public String getUploadFlag() { + String uplaodFlag=""; + try { + uplaodFlag = SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_UPLOAD_FLAG); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "uploadFlag failed", e); + return null; + } + return uplaodFlag; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUserApp.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUserApp.java index 64ed4ac1..f0dd7b2b 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUserApp.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUserApp.java @@ -37,9 +37,10 @@ */ package org.onap.portalapp.portal.domain; +import org.onap.portalsdk.core.domain.support.DomainVo; @SuppressWarnings("rawtypes") -public class EPUserApp implements java.io.Serializable, Comparable { +public class EPUserApp extends DomainVo implements java.io.Serializable, Comparable { private static final long serialVersionUID = 1L; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/ecomp/model/UploadRoleFunctionExtSystem.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/ecomp/model/UploadRoleFunctionExtSystem.java new file mode 100644 index 00000000..d7f86e10 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/ecomp/model/UploadRoleFunctionExtSystem.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ +package org.onap.portalapp.portal.ecomp.model; + +import java.io.Serializable; + +public class UploadRoleFunctionExtSystem implements Serializable{ + + private static final long serialVersionUID = -5543202387278296091L; + private String roleName; + private String type; + private String instance; + private String action; + private String name; + private boolean isGlobalRolePartnerFunc; + + public String getRoleName() { + return roleName; + } + public void setRoleName(String roleName) { + this.roleName = roleName; + } + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + public String getInstance() { + return instance; + } + public void setInstance(String instance) { + this.instance = instance; + } + public String getAction() { + return action; + } + public void setAction(String action) { + this.action = action; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public boolean getIsGlobalRolePartnerFunc() { + return isGlobalRolePartnerFunc; + } + public void setIsGlobalRolePartnerFunc(boolean isGlobalRolePartnerFunc) { + this.isGlobalRolePartnerFunc = isGlobalRolePartnerFunc; + } + + @Override + public String toString() { + return "UploadRoleFunctionExtSystem [roleName=" + roleName + ", type=" + type + ", instance=" + instance + + ", action=" + action + ", name=" + name + ", isGlobalRolePartnerFunc=" + isGlobalRolePartnerFunc + + "]"; + } + + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java index fcd17639..25ca5e65 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java @@ -49,20 +49,20 @@ import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.commons.codec.binary.Hex; import org.onap.portalapp.controller.sessionmgt.SessionCommunicationController; import org.onap.portalapp.portal.controller.BasicAuthenticationController; import org.onap.portalapp.portal.controller.ExternalAppsRestfulController; import org.onap.portalapp.portal.controller.SharedContextRestController; import org.onap.portalapp.portal.controller.WebAnalyticsExtAppController; import org.onap.portalapp.portal.domain.BasicAuthCredentials; +import org.onap.portalapp.portal.domain.EPApp; import org.onap.portalapp.portal.domain.EPEndpoint; -import org.onap.portalapp.portal.domain.EPRole; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice; import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum; import org.onap.portalapp.portal.logging.logic.EPLogUtil; import org.onap.portalapp.portal.service.BasicAuthenticationCredentialService; +import org.onap.portalapp.portal.service.ExternalAccessRolesService; import org.onap.portalapp.portal.utils.EcompPortalUtils; import org.onap.portalapp.service.RemoteWebServiceCallService; import org.onap.portalapp.service.sessionmgt.ManageService; @@ -94,6 +94,8 @@ public class PortalResourceInterceptor extends ResourceInterceptor { @Autowired private BasicAuthenticationCredentialService basicAuthService; + @Autowired + private ExternalAccessRolesService externalAccessRolesService; @SuppressWarnings("unchecked") @Override @@ -225,7 +227,8 @@ public class PortalResourceInterceptor extends ResourceInterceptor { uri = uri.substring(uri.indexOf("/", 1)); final String authHeader = request.getHeader("Authorization"); - + final String uebkey = request.getHeader("uebkey"); + // Unauthorized access due to missing HTTP Authorization request header if (authHeader == null) { final String msg = "no authorization found"; @@ -242,6 +245,26 @@ public class PortalResourceInterceptor extends ResourceInterceptor { return false; } + if(uebkey !=null && !uebkey.isEmpty()) + { + List app = externalAccessRolesService.getApp(uebkey); + EPApp application = null; + if (app.isEmpty()) { + throw new Exception("Invalid uebkey!"); + } + if (app.size() != 0 && !app.isEmpty()) { + application = app.get(0); + } + if (application != null) { + final String appUsername = application.getUsername(); + final String dbDecryptedPwd = CipherUtil.decryptPKC(application.getAppPassword()); + if (appUsername.equals(accountNamePassword[0]) && dbDecryptedPwd.equals(accountNamePassword[1])) { + return true; + } + } + } + + BasicAuthCredentials creds; try { creds = basicAuthService.getBasicAuthCredentialByUsernameAndPassword(accountNamePassword[0], diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java index 6c5810a8..6f934e98 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/listener/HealthMonitor.java @@ -37,18 +37,29 @@ */ package org.onap.portalapp.portal.listener; +import java.io.IOException; +import java.util.HashSet; import java.util.List; +import java.util.Set; +import java.util.UUID; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; +import org.apache.commons.lang3.StringUtils; +import org.apache.zookeeper.ZooKeeper; +import org.apache.zookeeper.client.FourLetterWordMain; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.MusicCore; +import org.onap.music.main.MusicUtil; +import org.onap.portalapp.music.util.MusicProperties; import org.onap.portalapp.portal.logging.aop.EPMetricsLog; import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum; import org.onap.portalapp.portal.logging.logic.EPLogUtil; -import org.onap.portalapp.portal.ueb.EPUebHelper; import org.onap.portalapp.portal.utils.EPCommonSystemProperties; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; @@ -56,19 +67,23 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.transaction.annotation.Transactional; + + + @Transactional @org.springframework.context.annotation.Configuration @EnableAspectJAutoProxy @EPMetricsLog public class HealthMonitor { - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HealthMonitor.class); + + ZooKeeper zookeeper = null; + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HealthMonitor.class); @Autowired private SessionFactory sessionFactory; - @Autowired - private EPUebHelper epUebHelper; private static boolean databaseUp; private static boolean uebUp; @@ -76,7 +91,9 @@ public class HealthMonitor { private static boolean backEndUp; private static boolean dbClusterStatusOk; private static boolean dbPermissionsOk; - + private static boolean zookeeperStatusOk; + private static boolean cassandraStatusOk; + /** * Read directly by external classes. */ @@ -110,13 +127,22 @@ public class HealthMonitor { public static boolean isBackEndUp() { return backEndUp; } + + public static boolean isZookeeperStatusOk() { + return zookeeperStatusOk; + } + + public static boolean isCassandraStatusOk() { + return cassandraStatusOk; + } private void monitorEPHealth() throws InterruptedException { int numIntervalsDatabaseHasBeenDown = 0; int numIntervalsClusterNotHealthy = 0; int numIntervalsDatabasePermissionsIncorrect = 0; - int numIntervalsUebHasBeenDown = 0; + int numIntervalsZookeeperNotHealthy = 0; + int numIntervalsCassandraNotHealthy = 0; logger.debug(EELFLoggerDelegate.debugLogger, "monitorEPHealth thread started"); @@ -168,26 +194,47 @@ public class HealthMonitor { numIntervalsDatabasePermissionsIncorrect = 0; } } + + zookeeperStatusOk = this.checkZookeeperStatus(); + if (zookeeperStatusOk == false) { + if ((numIntervalsZookeeperNotHealthy % numIntervalsBetweenAlerts) == 0) { + logger.debug(EELFLoggerDelegate.debugLogger, + "monitorEPHealth: cluster nodes down, logging to error log to trigger alert."); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.MusicHealthCheckZookeeperError); + numIntervalsZookeeperNotHealthy++; + } else { + numIntervalsZookeeperNotHealthy = 0; + } + } + cassandraStatusOk = this.checkCassandraStatus(); + if (cassandraStatusOk == false) { + if ((numIntervalsCassandraNotHealthy % numIntervalsBetweenAlerts) == 0) { + logger.debug(EELFLoggerDelegate.debugLogger, + "monitorEPHealth: cluster nodes down, logging to error log to trigger alert."); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.MusicHealthCheckCassandraError); + numIntervalsCassandraNotHealthy++; + } else { + numIntervalsCassandraNotHealthy = 0; + } + } + // // Get UEB status. Publish a bogus message to EP inbox, if 200 OK // returned, status is Up. // If down, signal alert once every X intervals. // EP will ignore this bogus message. - // - uebUp = this.checkIfUebUp(); - if (uebUp == false) { - - if ((numIntervalsUebHasBeenDown % numIntervalsBetweenAlerts) == 0) { - logger.debug(EELFLoggerDelegate.debugLogger, - "monitorEPHealth: UEB down, logging to error log to trigger alert"); - // Write a Log entry that will generate an alert - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHealthCheckUebClusterError); - numIntervalsUebHasBeenDown++; - } else { - numIntervalsUebHasBeenDown = 0; - } - } + // Commenting this out as Dependency on UEB is being deprecated + /* + * uebUp = this.checkIfUebUp(); if (uebUp == false) { + * + * if ((numIntervalsUebHasBeenDown % numIntervalsBetweenAlerts) == 0) { + * logger.debug(EELFLoggerDelegate.debugLogger, + * "monitorEPHealth: UEB down, logging to error log to trigger alert"); // Write + * a Log entry that will generate an alert EPLogUtil.logEcompError(logger, + * EPAppMessagesEnum.BeHealthCheckUebClusterError); + * numIntervalsUebHasBeenDown++; } else { numIntervalsUebHasBeenDown = 0; } } + */ // The front end should be up because the API is called through // proxy front end server. @@ -309,6 +356,71 @@ public class HealthMonitor { return isUp; } + private boolean checkZookeeperStatus() { + + String[] zookeeperNodes = MusicUtil.getMyZkHost().split(","); + logger.info(EELFLoggerDelegate.applicationLogger, "MusicUtil.getMyZkHost()---- :" + MusicUtil.getMyZkHost()); + for (int i = 0; i < zookeeperNodes.length; i++) { + try { + logger.info(EELFLoggerDelegate.applicationLogger, "server ip--zookeeper :" + zookeeperNodes[i].trim()); + String[] iport = zookeeperNodes[i].split(":"); + String zkNodeStatistics = FourLetterWordMain.send4LetterWord(iport[0].trim(), + Integer.parseInt(iport[1].trim()), "stat"); + logger.info(EELFLoggerDelegate.applicationLogger, + "Getting Status for Zookeeper zkNodeStatistics :" + zkNodeStatistics); + if (StringUtils.isNotBlank(zkNodeStatistics)) { + String state = zkNodeStatistics.substring(zkNodeStatistics.indexOf("Mode:"), + zkNodeStatistics.indexOf("Node")); + logger.info(EELFLoggerDelegate.applicationLogger, + "Getting Status for zookeeper :" + zookeeperNodes[i].trim() + ":------:" + state); + if (state.contains("leader")) + return true; + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "ZookeeperStatus Service is not responding", e.getCause()); + } + } + + return false; + } + + + public boolean checkCassandraStatus() { + logger.info(EELFLoggerDelegate.applicationLogger, "Getting Status for Cassandra"); + if (this.getAdminKeySpace()) { + return true; + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Cassandra Service is not responding"); + return false; + } + } + + private Boolean getAdminKeySpace() { + String musicKeySpace = MusicProperties.getProperty(MusicProperties.MUSIC_SESSION_KEYSPACE ); + //deletePortalHealthcheck(musicKeySpace); + PreparedQueryObject pQuery = new PreparedQueryObject(); + pQuery.appendQueryString("insert into "+musicKeySpace+".healthcheck (id) values (?)"); + pQuery.addValue(UUID.randomUUID()); + try { + MusicCore.nonKeyRelatedPut(pQuery, MusicUtil.EVENTUAL); + } catch (MusicServiceException e) { + logger.error(EELFLoggerDelegate.errorLogger, "getAdminKeySpace() failed", e.getCause()); + return Boolean.FALSE; + } + return Boolean.TRUE; + } + + + private void deletePortalHealthcheck(String musicKeySpace) { + PreparedQueryObject pQuery = new PreparedQueryObject(); + pQuery.appendQueryString("TRUNCATE "+musicKeySpace+".healthcheck"); + try { + MusicCore.nonKeyRelatedPut(pQuery, MusicUtil.EVENTUAL); + } catch (MusicServiceException e) { + logger.error(EELFLoggerDelegate.errorLogger, "deletePortalHealthcheck() failed", e.getCause()); + } + } + private boolean checkDatabasePermissions() { boolean isUp = false; Session localSession = null; @@ -348,17 +460,5 @@ public class HealthMonitor { } return isUp; } - - private boolean checkIfUebUp() { - boolean uebUp = false; - try { - boolean isAvailable = epUebHelper.checkAvailability(); - boolean messageCanBeSent = epUebHelper.MessageCanBeSentToTopic(); - uebUp = (isAvailable && messageCanBeSent); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "checkIfUebUp failed", e); - } - return uebUp; - } - + } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/logging/format/EPAppMessagesEnum.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/logging/format/EPAppMessagesEnum.java index 6274696f..8062926f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/logging/format/EPAppMessagesEnum.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/logging/format/EPAppMessagesEnum.java @@ -83,7 +83,7 @@ public enum EPAppMessagesEnum { BeRestApiAuthenticationError(EPErrorCodesEnum.BERESTAPIAUTHENTICATIONERROR, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, "ERR101E", "Rejected an incoming REST API request due to invalid credentials", "", "Please check application credentials defined in Database or properties files."), - + InternalAuthenticationInfo(EPErrorCodesEnum.INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, "ERR199I", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."), @@ -132,6 +132,11 @@ public enum EPAppMessagesEnum { BeHttpConnectionError(EPErrorCodesEnum.BEHTTPCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, "ERR213E", "It could be that communication to an external application might resulted an exception or failed to reach the external application", "Details: {0}.", "Please check logs for more information."), + MusicHealthCheckZookeeperError(EPErrorCodesEnum.MUSICHEALTHCHECKZOOKEEPERERROR_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR214E", "Connectivity to Music Cluster -zookeeper server", "Details: {0}.", "Please check zookeeper server list and check the logs for more information"), + + MusicHealthCheckCassandraError(EPErrorCodesEnum.MUSICHEALTHCHECKCASSANDRAERROR_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, + "ERR215E", "Connectivity to Music Cluster -Cassandra server", "Details: {0}.", "Please check Cassandra server list and check the logs for more information"), InternalConnectionInfo(EPErrorCodesEnum.INTERNALCONNECTIONINFO_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO, "ERR299I", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."), diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/logging/format/EPErrorCodesEnum.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/logging/format/EPErrorCodesEnum.java index d6729219..a93f7722 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/logging/format/EPErrorCodesEnum.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/logging/format/EPErrorCodesEnum.java @@ -109,6 +109,8 @@ public enum EPErrorCodesEnum implements EELFResolvableErrorEnum { SCHEDULERAUX_ACCESS_AUTHENTICATIONERROR, SCHEDULER_ACCESS_GENERALERROR, SCHEDULER_INVALID_ATTRIBUTEERROR, + MUSICHEALTHCHECKZOOKEEPERERROR_ONE_ARGUMENT, + MUSICHEALTHCHECKCASSANDRAERROR_ONE_ARGUMENT, ; /** diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterface.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterface.java index ac1f435f..0522b395 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterface.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterface.java @@ -48,7 +48,6 @@ import javax.ws.rs.core.Response; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; -import org.drools.compiler.lang.DRL5Expressions.neg_operator_key_return; import org.eclipse.jetty.util.security.Password; import org.json.simple.JSONObject; import org.onap.portalapp.portal.logging.logic.EPLogUtil; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxRestInterface.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxRestInterface.java index 599ada59..e0a2fe5f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxRestInterface.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxRestInterface.java @@ -37,11 +37,13 @@ */ package org.onap.portalapp.portal.scheduleraux; +import java.lang.reflect.Type; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; +import javax.annotation.PostConstruct; import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType; @@ -49,8 +51,10 @@ import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.Response; import org.apache.commons.codec.binary.Base64; +import org.apache.cxf.jaxrs.impl.ResponseImpl; import org.eclipse.jetty.util.security.Password; import org.json.simple.JSONObject; +import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum; import org.onap.portalapp.portal.logging.logic.EPLogUtil; import org.onap.portalapp.portal.scheduler.SchedulerProperties; import org.onap.portalapp.portal.scheduler.client.HttpBasicClient; @@ -59,6 +63,14 @@ import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.http.HttpStatus; import org.springframework.web.client.HttpClientErrorException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; + public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements SchedulerAuxRestInterfaceIfc { /** The logger. */ @@ -77,7 +89,27 @@ public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements Sc super(); } + Gson gson = null; + + private final ObjectMapper mapper = new ObjectMapper(); + + private void init() { + logger.debug(EELFLoggerDelegate.debugLogger, "initializing"); + GsonBuilder builder = new GsonBuilder(); + + // Register an adapter to manage the date types as long values + builder.registerTypeAdapter(Date.class, new JsonDeserializer() { + public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) + throws JsonParseException { + return new Date(json.getAsJsonPrimitive().getAsLong()); + } + }); + + gson = builder.create(); + } + public void initRestClient() { + init(); final String methodname = "initRestClient()"; final String mechId = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_CLIENT_MECHID_VAL); final String clientPassword = SchedulerProperties @@ -234,7 +266,24 @@ public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements Sc // .header("X-FromAppId", sourceID) .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON)); - t = (T) cres.readEntity(t.getClass()); + /* It is not recommendable to use the implementation class org.apache.cxf.jaxrs.impl.ResponseImpl in the code, + but had to force this in-order to prevent conflict with the ResponseImpl class of Jersey Client which + doesn't work as expected. Created Portal-253 for tracking */ + String str = ((ResponseImpl)cres).readEntity(String.class); + + try { + if(t.getClass().getName().equals(String.class.getName())){ + t=(T) str; + + }else{ + t = (T) gson.fromJson(str, t.getClass()); + } + + } catch (Exception e) { + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e); + } + + //t = (T) cres.readEntity(t.getClass()); if (t.equals("")) { restObject.set(null); } else { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ApplicationsRestClientServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ApplicationsRestClientServiceImpl.java index e7ea6622..c9f2c6ee 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ApplicationsRestClientServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ApplicationsRestClientServiceImpl.java @@ -130,14 +130,14 @@ public class ApplicationsRestClientServiceImpl implements ApplicationsRestClient logger.debug(EELFLoggerDelegate.debugLogger, "http response status=" + status); MDC.put(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(status)); if (!isHttpSuccess(status)) { - String errMsg = "Failed. Status=" + status + "; [" + response.getStatusInfo().getReasonPhrase().toString() + String errMsg = "Failed. Status=" + status + "; [" + ((ResponseImpl)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(); + if (((ResponseImpl)response).getLocation() != null) + url = ((ResponseImpl)response).getLocation().toURL(); } catch (MalformedURLException e) { // never mind. it is only for the debug message. logger.warn(EELFLoggerDelegate.errorLogger, "Failed to build URL", e); @@ -248,7 +248,7 @@ public class ApplicationsRestClientServiceImpl implements ApplicationsRestClient /* It is not recommendable to use the implementation class org.apache.cxf.jaxrs.impl.ResponseImpl in the code, but had to force this in-order to prevent conflict with the ResponseImpl class of Jersey Client which - doesn't work as expected. Created Portal-253 for tracking */ + doesn't work as expected. Created Portal-253 for tracking */ String incomingJson = ((ResponseImpl)response).readEntity(String.class); return incomingJson; } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/BasicAuthAccountService.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/BasicAuthAccountService.java index 1131308c..d32229d7 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/BasicAuthAccountService.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/BasicAuthAccountService.java @@ -98,4 +98,14 @@ public interface BasicAuthAccountService { * @throws Exception */ void updateBasicAuthAccount(Long accountId, BasicAuthCredentials newCredential) throws Exception; + + /** + * Returns BasicAuthenticationAccount + * + * @param accountId + * @return BasicAuthCredentials + * @throws Exception + */ + + BasicAuthCredentials getBasicAuthCredentialsById(long id) throws Exception; } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/BasicAuthAccountServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/BasicAuthAccountServiceImpl.java index c83b0d9b..a2ff3149 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/BasicAuthAccountServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/BasicAuthAccountServiceImpl.java @@ -48,6 +48,7 @@ import org.onap.portalapp.portal.domain.BasicAuthCredentials; import org.onap.portalapp.portal.domain.EPEndpoint; import org.onap.portalapp.portal.domain.EPEndpointAccount; import org.onap.portalapp.portal.logging.aop.EPMetricsLog; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.onboarding.util.CipherUtil; import org.onap.portalsdk.core.service.DataAccessService; @@ -117,8 +118,13 @@ public class BasicAuthAccountServiceImpl implements BasicAuthAccountService{ public void updateBasicAuthAccount(Long accountId, BasicAuthCredentials newCredential) throws Exception { try { newCredential.setId(accountId); - if (newCredential.getPassword() != null) - newCredential.setPassword(encryptedPassword(newCredential.getPassword())); + if (newCredential.getPassword() != null){ + if(newCredential.getPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD)){ + BasicAuthCredentials oldMS = getBasicAuthCredentialsById(accountId); + newCredential.setPassword(oldMS.getPassword()); // keep the old password + }else + newCredential.setPassword(encryptedPassword(newCredential.getPassword())); //new password + } getDataAccessService().saveDomainObject(newCredential, null); List endpoints = newCredential.getEndpoints(); @@ -174,7 +180,7 @@ public class BasicAuthAccountServiceImpl implements BasicAuthAccountService{ List list = (List) dataAccessService.getList(BasicAuthCredentials.class, null); for (int i = 0; i < list.size(); i++) { if (list.get(i).getPassword() != null) - list.get(i).setPassword(decryptedPassword(list.get(i).getPassword())); + list.get(i).setPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD); list.get(i).setEndpoints(getEPEndpoints(list.get(i).getId())); } return list; @@ -244,4 +250,22 @@ public class BasicAuthAccountServiceImpl implements BasicAuthAccountService{ public DataAccessService getDataAccessService() { return dataAccessService; } + + @Override + public BasicAuthCredentials getBasicAuthCredentialsById(long id) throws Exception { + try { + @SuppressWarnings("unchecked") + List list = (List) dataAccessService + .getList(BasicAuthCredentials.class, null); + for (BasicAuthCredentials auth : list) { + if (auth != null && auth.getId() == id) + return auth; + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getBasicAuthCredentialsDataById failed", e); + throw e; + } + return null; + + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppCommonServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppCommonServiceImpl.java index 7f4b2cea..24572fb2 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppCommonServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppCommonServiceImpl.java @@ -47,6 +47,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.UUID; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletResponse; @@ -82,7 +83,6 @@ import org.onap.portalapp.portal.transport.FieldsValidator; import org.onap.portalapp.portal.transport.FunctionalMenuItem; import org.onap.portalapp.portal.transport.LocalRole; import org.onap.portalapp.portal.transport.OnboardingApp; -import org.onap.portalapp.portal.ueb.EPUebHelper; import org.onap.portalapp.portal.utils.EPCommonSystemProperties; import org.onap.portalapp.portal.utils.EcompPortalUtils; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; @@ -118,9 +118,7 @@ public class EPAppCommonServiceImpl implements EPAppService { @Autowired protected SessionFactory sessionFactory; @Autowired - private DataAccessService dataAccessService; - @Autowired - private EPUebHelper epUebHelper; + private DataAccessService dataAccessService; @PostConstruct private void init() { @@ -666,6 +664,7 @@ public class EPAppCommonServiceImpl implements EPAppService { List onboardingAppsList = new ArrayList(); for (EPApp app : apps) { OnboardingApp onboardingApp = new OnboardingApp(); + app.setAppPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD);//to hide password from get request createOnboardingFromApp(app, onboardingApp); onboardingAppsList.add(onboardingApp); } @@ -680,6 +679,7 @@ public class EPAppCommonServiceImpl implements EPAppService { List onboardingAppsList = new ArrayList(); for (EPApp app : apps) { OnboardingApp onboardingApp = new OnboardingApp(); + app.setAppPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD); //to hide password from get request createOnboardingFromApp(app, onboardingApp); onboardingAppsList.add(onboardingApp); } @@ -1065,9 +1065,79 @@ public class EPAppCommonServiceImpl implements EPAppService { } } + protected void updateRestrictedApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator, EPUser user) { + synchronized (syncRests) { + boolean result = false; + Session localSession = null; + Transaction transaction = null; + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + EPApp app; + if (appId == null) { + app = new EPApp(); + /* + * In the parent class, the UEB code is responsible for generating the + * keys/secret/mailbox but UEB Messaging is not actually being used currently; + * may be used in future at which point we can just remove this method and + * depend on parent class's method So, using UUID generator to generate the + * unique key instead. + */ + String uuidStr = UUID.randomUUID().toString(); + String appKey = uuidStr; + String appSecret = uuidStr; + String appMailboxName = "ECOMP-PORTAL-OUTBOX"; + onboardingApp.setUebTopicName(appMailboxName); + onboardingApp.setUebKey(appKey); + onboardingApp.setUebSecret(appSecret); + } else { + app = (EPApp) localSession.get(EPApp.class, appId); + if (app == null || app.getId() == null) { + // App is already deleted! + transaction.commit(); + localSession.close(); + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND); + return; + } + } + logger.debug(EELFLoggerDelegate.debugLogger, + "updateRestrictedApp: about to call createAppFromOnboarding"); + createAppFromOnboarding(app, onboardingApp, localSession); + logger.debug(EELFLoggerDelegate.debugLogger, + "updateRestrictedApp: finished calling createAppFromOnboarding"); + localSession.saveOrUpdate(app); + logger.debug(EELFLoggerDelegate.debugLogger, + "updateRestrictedApp: finished calling localSession.saveOrUpdate"); + // Enable or disable all menu items associated with this app + setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId); + logger.debug(EELFLoggerDelegate.debugLogger, + "updateRestrictedApp: finished calling setFunctionalMenuItemsEnabled"); + transaction.commit(); + logger.debug(EELFLoggerDelegate.debugLogger, + "updateRestrictedApp: finished calling transaction.commit"); + result = true; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "updateRestrictedApp failed", e); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); + EcompPortalUtils.rollbackTransaction(transaction, + "updateRestrictedApp rollback, exception = " + e.toString()); + } finally { + EcompPortalUtils.closeLocalSession(localSession, "updateRestrictedApp"); + } + if (!result) { + fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } + + } + + @Deprecated + protected void updateRestrictedAppUeb(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator, + EPUser user) { synchronized (syncRests) { boolean result = false; Session localSession = null; @@ -1234,7 +1304,6 @@ public class EPAppCommonServiceImpl implements EPAppService { "LR: updateApp: finished calling setFunctionalMenuItemsEnabled"); transaction.commit(); logger.debug(EELFLoggerDelegate.debugLogger, "LR: updateApp: finished calling transaction.commit"); - epUebHelper.addPublisher(app); logger.debug(EELFLoggerDelegate.debugLogger, "LR: updateApp: finished calling epUebHelper.addPublisher"); result = true; @@ -1282,7 +1351,7 @@ public class EPAppCommonServiceImpl implements EPAppService { onboardingApp.isOpen = app.getOpen(); onboardingApp.isEnabled = app.getEnabled(); onboardingApp.username = app.getUsername(); - onboardingApp.appPassword = decryptedPassword(app.getAppPassword(), app); + onboardingApp.appPassword = (app.getAppPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD)) ? EPCommonSystemProperties.APP_DISPLAY_PASSWORD :decryptedPassword(app.getAppPassword(), app); onboardingApp.uebTopicName = app.getUebTopicName(); onboardingApp.uebKey = app.getUebKey(); onboardingApp.uebSecret = app.getUebSecret(); @@ -1313,8 +1382,9 @@ public class EPAppCommonServiceImpl implements EPAppService { app.setOpen(onboardingApp.isOpen); app.setEnabled(onboardingApp.isEnabled); app.setUsername(onboardingApp.username); + if(!onboardingApp.appPassword.equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD)) app.setAppPassword(this.encryptedPassword(onboardingApp.appPassword, app)); - app.setUebTopicName(onboardingApp.uebTopicName); + //app.setUebTopicName(onboardingApp.uebTopicName); app.setUebKey(onboardingApp.uebKey); app.setUebSecret(onboardingApp.uebSecret); app.setCentralAuth(onboardingApp.isCentralAuth); @@ -1662,4 +1732,4 @@ public class EPAppCommonServiceImpl implements EPAppService { return userAndRoles; } -} +} \ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesService.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesService.java index 09c7cc4f..170d4323 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesService.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesService.java @@ -49,6 +49,7 @@ import org.onap.portalapp.portal.domain.EPApp; import org.onap.portalapp.portal.domain.EPRole; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.domain.ExternalRoleDetails; +import org.onap.portalapp.portal.ecomp.model.UploadRoleFunctionExtSystem; import org.onap.portalapp.portal.exceptions.InvalidUserException; import org.onap.portalapp.portal.transport.CentralRole; import org.onap.portalapp.portal.transport.CentralRoleFunction; @@ -56,8 +57,8 @@ import org.onap.portalapp.portal.transport.CentralUser; import org.onap.portalapp.portal.transport.CentralV2Role; import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator; import org.onap.portalsdk.core.domain.Role; -import org.onap.portalsdk.core.domain.RoleFunction; import org.onap.portalsdk.core.restful.domain.EcompUser; +import org.springframework.http.HttpEntity; import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; @@ -240,7 +241,7 @@ public interface ExternalAccessRolesService { * @param upload * @throws Exception */ - public void bulkUploadPartnerFunctions(String uebkey, List upload) throws Exception; + public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception; /** * It uploads partner application role functions into external auth system @@ -282,7 +283,7 @@ public interface ExternalAccessRolesService { * @param roleList * @throws Exception */ - void bulkUploadPartnerRoleFunctions(String uebkey, List roleList) throws Exception; + Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception; /** * it deletes all dependency role records @@ -452,5 +453,33 @@ public interface ExternalAccessRolesService { * @return String action */ String getFunctionCodeAction(String roleFuncItem); + + /** + * + * Adds function to role in external auth system + * + * @param data + * @param app + */ + void bulkUploadRoleFunc(UploadRoleFunctionExtSystem data, EPApp app) throws Exception; + + /** + * + * Syncs user roles from external auth system to ecomp portal + * + * @param orgUserId + * @throws Exception + */ + public void syncApplicationUserRolesFromExtAuthSystem(String orgUserId) throws Exception; + + /** + * + * Gets all user roles from external auth system + * + * @param orgUserId + * @param getUserRolesEntity + * @return user roles from external auth system + */ + ResponseEntity getUserRolesFromExtAuthSystem(String orgUserId, HttpEntity getUserRolesEntity) throws Exception; } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java index eb6d730c..4c68fc9c 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java @@ -70,6 +70,7 @@ import org.onap.portalapp.portal.domain.EPRole; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.domain.EPUserApp; import org.onap.portalapp.portal.domain.ExternalRoleDetails; +import org.onap.portalapp.portal.ecomp.model.UploadRoleFunctionExtSystem; import org.onap.portalapp.portal.exceptions.DeleteDomainObjectFailedException; import org.onap.portalapp.portal.exceptions.ExternalAuthSystemException; import org.onap.portalapp.portal.exceptions.InactiveApplicationException; @@ -89,12 +90,14 @@ import org.onap.portalapp.portal.transport.CentralUserApp; import org.onap.portalapp.portal.transport.CentralV2Role; import org.onap.portalapp.portal.transport.CentralV2User; import org.onap.portalapp.portal.transport.CentralV2UserApp; +import org.onap.portalapp.portal.transport.CentralizedAppRoles; import org.onap.portalapp.portal.transport.EcompUserRoles; import org.onap.portalapp.portal.transport.ExternalAccessPerms; import org.onap.portalapp.portal.transport.ExternalAccessPermsDetail; import org.onap.portalapp.portal.transport.ExternalAccessRole; import org.onap.portalapp.portal.transport.ExternalAccessRolePerms; import org.onap.portalapp.portal.transport.ExternalAccessUser; +import org.onap.portalapp.portal.transport.ExternalAccessUserRoleDetail; import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator; import org.onap.portalapp.portal.transport.ExternalRoleDescription; import org.onap.portalapp.portal.transport.GlobalRoleWithApplicationRoleFunction; @@ -2418,6 +2421,35 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic addRoleInExternalSystem(role, app.get(0)); rolesListAdded++; } + if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) { + // Add Account Admin role in External AUTH System + try { + String addAccountAdminRole = ""; + ExternalAccessRole extRole = new ExternalAccessRole(); + extRole.setName(app.get(0).getNameSpace() + "." + PortalConstants.ADMIN_ROLE + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); + addAccountAdminRole = mapper.writeValueAsString(extRole); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity entity = new HttpEntity<>(addAccountAdminRole, headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", + HttpMethod.POST, entity, String.class); + rolesListAdded++; + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, + "HttpClientErrorException - Failed to create Account Admin role", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("409 Conflict")) { + logger.error(EELFLoggerDelegate.errorLogger, + "bulkUploadRoles: Account Admin Role already exits but does not break functionality", + e); + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "bulkUploadRoles: Failed to create Account Admin role", e.getMessage()); + } + } + } } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e); throw e; @@ -2488,14 +2520,24 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic * @param app */ private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app) { - String checkType = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url"; + String type = ""; + String instance = ""; + String action = ""; + if(addRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)){ + type = EcompPortalUtils.getFunctionType(addRoleFunc.getFunctionCd()); + instance = EcompPortalUtils.getFunctionCode(addRoleFunc.getFunctionCd()); + action = EcompPortalUtils.getFunctionAction(addRoleFunc.getFunctionCd()); + } else{ + type = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url"; + instance = addRoleFunc.getFunctionCd(); + action = "*"; + } ExternalAccessRolePerms extRolePerms = null; ExternalAccessPerms extPerms = null; ObjectMapper mapper = new ObjectMapper(); try { HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - - extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, addRoleFunc.getFunctionCd(), "*", + extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action, addRoleFunc.getFunctionName()); extRolePerms = new ExternalAccessRolePerms(extPerms, app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); @@ -2515,16 +2557,73 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } } + @SuppressWarnings("unchecked") @Override - public void bulkUploadPartnerFunctions(String uebkey, List roleFunctionsList) throws Exception { + public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception { EPApp app = getApp(uebkey).get(0); - CentralV2RoleFunction cenRoleFunc = null; - for (RoleFunction roleFunction : roleFunctionsList) { - cenRoleFunc = new CentralV2RoleFunction(roleFunction.getCode(), roleFunction.getName()); - addRoleFunctionInExternalSystem(cenRoleFunc, app); + final Map params = new HashMap<>(); + params.put("appId", app.getId()); + List roleFuncList = dataAccessService.executeNamedQuery("getPartnerAppFunctions", params, + null); + Integer functionsAdded = 0; + try { + for (CentralV2RoleFunction roleFunc : roleFuncList) { + addFunctionInExternalSystem(roleFunc, app); + functionsAdded++; + } + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadPartnerFunctions failed", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerFunctions: failed", e.getMessage(), e); } + return functionsAdded; } + private void addFunctionInExternalSystem(CentralV2RoleFunction roleFunc, EPApp app) throws Exception { + ObjectMapper mapper = new ObjectMapper(); + ExternalAccessPerms extPerms = new ExternalAccessPerms(); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + String type = ""; + String instance = ""; + String action = ""; + if ((roleFunc.getCode().contains(FUNCTION_PIPE)) + || (roleFunc.getType() != null && roleFunc.getAction() != null)) { + type = EcompPortalUtils.getFunctionType(roleFunc.getCode()); + instance = EcompPortalUtils.getFunctionCode(roleFunc.getCode()); + action = EcompPortalUtils.getFunctionAction(roleFunc.getCode()); + } else { + type = roleFunc.getCode().contains("menu") ? "menu" : "url"; + instance = roleFunc.getCode(); + action = "*"; + } + try { + extPerms.setAction(action); + extPerms.setInstance(instance); + extPerms.setType(app.getNameSpace() + "." + type); + extPerms.setDescription(roleFunc.getName()); + String addFunction = mapper.writeValueAsString(extPerms); + HttpEntity entity = new HttpEntity<>(addFunction, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction); + ResponseEntity addPermResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm", + HttpMethod.POST, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, + "addFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ", + addPermResponse.getStatusCode().value(), addFunction); + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, + "HttpClientErrorException - Failed to add function in external central auth system", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + throw e; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "addFunctionInExternalSystem: Failed to add fucntion in external central auth system", e); + throw e; + } + } + @Override public void bulkUploadPartnerRoles(String uebkey, List roleList) throws Exception { EPApp app = getApp(uebkey).get(0); @@ -2535,47 +2634,80 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic @SuppressWarnings("unchecked") @Override - public void bulkUploadPartnerRoleFunctions(String uebkey, List roleList) throws Exception { + public Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception { EPApp app = getApp(uebkey).get(0); - HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - for (Role role : roleList) { - try { - Set roleFunctionList = role.getRoleFunctions(); - List roleFunctionListNew = new ArrayList<>(); - ObjectMapper roleFunctionsMapper = new ObjectMapper(); - Iterator itetaror = roleFunctionList.iterator(); - while (itetaror.hasNext()) { - Object nextValue = itetaror.next(); - RoleFunction roleFunction = roleFunctionsMapper.convertValue(nextValue, RoleFunction.class); - roleFunctionListNew.add(roleFunction); - } - List listWithoutDuplicates = roleFunctionListNew.stream().distinct() - .collect(Collectors.toList()); - for (RoleFunction roleFunction : listWithoutDuplicates) { - String checkType = roleFunction.getCode().contains("menu") ? "menu" : "url"; - ExternalAccessRolePerms extRolePerms = null; - ExternalAccessPerms extPerms = null; - ObjectMapper mapper = new ObjectMapper(); - extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunction.getCode(), - "*"); - extRolePerms = new ExternalAccessRolePerms(extPerms, - app.getNameSpace() + "." + role.getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); - String updateRolePerms = mapper.writeValueAsString(extRolePerms); - HttpEntity entity = new HttpEntity<>(updateRolePerms, headers); - template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "role/perm", HttpMethod.PUT, entity, String.class); + List roles = getAppRoles(app.getId()); + final Map params = new HashMap<>(); + Integer roleFunctions = 0; + try { + for (EPRole role : roles) { + params.put("roleId", role.getId()); + List appRoleFunc = dataAccessService.executeNamedQuery("uploadPartnerRoleFunctions", + params, null); + if (!appRoleFunc.isEmpty()) { + for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) { + addRoleFunctionsInExternalSystem(addRoleFunc, role, app); + roleFunctions++; + } } - } catch (Exception e) { - if (e.getMessage().equalsIgnoreCase("409 Conflict")) { - logger.error(EELFLoggerDelegate.errorLogger, - "bulkUploadPartnerRoleFunctions: RoleFunction already exits but does not break functionality"); + } + // upload global role functions to ext auth system + if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + roleFunctions = bulkUploadGlobalRoleFunctions(app, roleFunctions); + } + } catch(HttpClientErrorException e){ + logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e); + } + return roleFunctions; + } + + @SuppressWarnings("unchecked") + private Integer bulkUploadGlobalRoleFunctions(EPApp app, Integer roleFunctions) throws Exception { + try { + EPApp portalApp = epAppService.getApp(1l); + final Map params = new HashMap<>(); + params.put("appId", app.getId()); + List globalRoleFuncs = dataAccessService + .executeNamedQuery("getBulkUploadPartnerGlobalRoleFunctions", params, null); + ObjectMapper mapper = new ObjectMapper(); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFuncs) { + ExternalAccessRolePerms extRolePerms; + ExternalAccessPerms extPerms; + String type = ""; + String instance = ""; + String action = ""; + if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) { + type = EcompPortalUtils.getFunctionType(globalRoleFunc.getFunctionCd()); + instance = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd()); + action = EcompPortalUtils.getFunctionAction(globalRoleFunc.getFunctionCd()); } else { - logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerRoleFunctions: Failed to addRoleFunctionsInExternalSystem", - e); + type = globalRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url"; + instance = globalRoleFunc.getFunctionCd(); + action = "*"; } + extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + type, instance, action); + extRolePerms = new ExternalAccessRolePerms(extPerms, portalApp.getNameSpace() + "." + globalRoleFunc.getRoleName() + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_")); + String updateRolePerms = mapper.writeValueAsString(extRolePerms); + HttpEntity entity = new HttpEntity<>(updateRolePerms, headers); + updateRoleFunctionInExternalSystem(updateRolePerms, entity); + roleFunctions++; } - + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, + "HttpClientErrorException - Failed to add role function in external central auth system", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + throw e; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "bulkUploadGlobalRoleFunctions: Failed to add role fucntion in external central auth system", e); + throw e; } + return roleFunctions; } @Override @@ -3413,7 +3545,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic CentralRoleFunction cenRoleFunc = new CentralRoleFunction(cenV2RoleFunc.getCode(), cenV2RoleFunc.getName()); cenRoleFunction.add(cenRoleFunc); } - CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(), userApp.getRole().isActive(), userApp.getRole().getPriority(), + CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(), userApp.getRole().getActive(), userApp.getRole().getPriority(), cenRoleFunction); cua.setRole(role); userApps.add(cua); @@ -3445,7 +3577,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName()); cenRoleFuncList.add(roleFunc); } - CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.isActive(), v2CenRole.getPriority(), cenRoleFuncList); + CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(), cenRoleFuncList); cenRoleList.add(role); } return cenRoleList; @@ -3481,7 +3613,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic CentralRoleFunction roleFunc = new CentralRoleFunction(v2CenRoleFunc.getCode(), v2CenRoleFunc.getName()); cenRoleFuncList.add(roleFunc); } - return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.isActive(), v2CenRole.getPriority(), + return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.getActive(), v2CenRole.getPriority(), cenRoleFuncList); } @@ -3520,4 +3652,207 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic encodedString = encodedString.replaceAll("\\*", "%"+ Hex.encodeHexString("*".getBytes())); return encodedString; } + + @Override + public void bulkUploadRoleFunc(UploadRoleFunctionExtSystem data, EPApp app) throws Exception { + ObjectMapper mapper = new ObjectMapper(); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + try { + ExternalAccessRolePerms extRolePerms; + ExternalAccessPerms extPerms; + extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + data.getType(), encodeFunctionCode(data.getInstance()), data.getAction()); + String appNameSpace = ""; + if(data.getIsGlobalRolePartnerFunc()) { + appNameSpace = epAppService.getApp(1l).getNameSpace(); + } else { + appNameSpace = app.getNameSpace(); + } + extRolePerms = new ExternalAccessRolePerms(extPerms, + appNameSpace + "." + + data.getRoleName().replaceAll( + EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, + "_")); + String updateRolePerms = mapper.writeValueAsString(extRolePerms); + HttpEntity entity = new HttpEntity<>(updateRolePerms, headers); + updateRoleFunctionInExternalSystem(updateRolePerms, entity); + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, + "HttpClientErrorException - Failed to add role function in external central auth system", e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + throw e; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "addFunctionInExternalSystem: Failed to add role fucntion in external central auth system", e); + throw e; + } + + } + + private void updateRoleFunctionInExternalSystem(String updateRolePerms, HttpEntity entity) { + logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms); + ResponseEntity addPermResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm", + HttpMethod.POST, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, + "bulkUploadRoleFunc: Finished adding permission for POST: {} and status code: {} ", + addPermResponse.getStatusCode().value(), updateRolePerms); + } + + @Override + public void syncApplicationUserRolesFromExtAuthSystem(String loginId) throws Exception { + String name = ""; + if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = loginId + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity getUserRolesEntity = new HttpEntity<>(headers); + ResponseEntity getResponse = getUserRolesFromExtAuthSystem(name, getUserRolesEntity); + List userRoleDetailList = new ArrayList<>(); + String res = getResponse.getBody(); + JSONObject jsonObj = null; + JSONArray extRoles = null; + if (!res.equals("{}")) { + jsonObj = new JSONObject(res); + extRoles = jsonObj.getJSONArray("role"); + } + updateUserRolesInLocal(userRoleDetailList, extRoles, loginId); + } + + @SuppressWarnings("unchecked") + private void updateUserRolesInLocal(List userRoleDetailList, JSONArray extRoles, + String loginId) throws InvalidUserException { + HashMap userParams = new HashMap<>(); + userParams.put("orgUserId", loginId); + // Get all centralized applications existing user roles from local + List currentUserAppRoles = dataAccessService + .executeNamedQuery("getUserCentralizedAppRoles", userParams, null); + EPUser user = getUser(loginId).get(0); + // Get all centralized applications roles from local + HashMap cenAppRolesMap = getCentralizedAppRoleList(); + HashMap currentCentralizedUserAppRolesMap = getCurrentUserCentralizedAppRoles( + currentUserAppRoles); + // Get all centralized applications + admin role from local + HashMap centralisedAppsMap = getCentralizedAdminAppsInfo(); + if (extRoles != null) { + ExternalAccessUserRoleDetail userRoleDetail = null; + for (int i = 0; i < extRoles.length(); i++) { + if (!extRoles.getJSONObject(i).getString("name").endsWith(ADMIN) + && !extRoles.getJSONObject(i).getString("name").endsWith(OWNER)) { + userRoleDetail = new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"), + null); + userRoleDetailList.add(userRoleDetail); + } + } + addUserRolesInLocal(userRoleDetailList, user, cenAppRolesMap, currentCentralizedUserAppRolesMap, + centralisedAppsMap); + } + } + + private void addUserRolesInLocal(List userRoleDetailList, EPUser user, + HashMap cenAppRolesMap, + HashMap currentCentralizedUserAppRolesMap, + HashMap centralisedAppsMap) { + for (ExternalAccessUserRoleDetail extUserRoleDetail : userRoleDetailList) { + try { + // check if user already has role in local + if (!currentCentralizedUserAppRolesMap.containsKey(extUserRoleDetail.getName())) { + CentralizedAppRoles getCenAppRole = cenAppRolesMap.get(extUserRoleDetail.getName()); + if (getCenAppRole != null) { + logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Adding user role from external auth system {}", + extUserRoleDetail.toString()); + EPUserApp userApp = new EPUserApp(); + EPApp app = new EPApp(); + app.setId(getCenAppRole.getAppId()); + EPRole epRole = new EPRole(); + epRole.setId(getCenAppRole.getRoleId()); + userApp.setApp(app); + userApp.setUserId(user.getId()); + userApp.setRole(epRole); + dataAccessService.saveDomainObject(userApp, null); + logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Finished user role from external auth system {}", + extUserRoleDetail.toString()); + } else if (getCenAppRole == null // check if user has app account admin role + && extUserRoleDetail.getName().endsWith(PortalConstants.ADMIN_ROLE.replaceAll( + EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) { + EPApp app = centralisedAppsMap.get(extUserRoleDetail.getName()); + if (app != null) { + logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Adding user role from external auth system {}", + extUserRoleDetail.toString()); + EPUserApp userApp = new EPUserApp(); + EPRole epRole = new EPRole(); + epRole.setId(PortalConstants.ACCOUNT_ADMIN_ROLE_ID); + userApp.setApp(app); + userApp.setUserId(user.getId()); + userApp.setRole(epRole); + dataAccessService.saveDomainObject(userApp, null); + logger.debug(EELFLoggerDelegate.debugLogger, "addUserRolesInLocal: Finished user role from external auth system {}", + extUserRoleDetail.toString()); + } + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "addUserRolesInLocal - Failed to update user role in local from external auth system {} ", + extUserRoleDetail.toString(), e); + } + } + } + + @SuppressWarnings("unchecked") + private HashMap getCentralizedAdminAppsInfo() { + List centralizedApps = dataAccessService + .executeNamedQuery("getCentralizedApps", null, null); + HashMap centralisedAppsMap = new HashMap<>(); + for (EPApp cenApp : centralizedApps) { + centralisedAppsMap.put(cenApp.getNameSpace()+ "." + + PortalConstants.ADMIN_ROLE.replaceAll( + EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), cenApp); + } + return centralisedAppsMap; + } + + private HashMap getCurrentUserCentralizedAppRoles( + List currentUserAppRoles) { + HashMap currentCentralizedUserAppRolesMap = new HashMap<>(); + for (CentralizedAppRoles cenAppUserRole : currentUserAppRoles) { + currentCentralizedUserAppRolesMap.put( + cenAppUserRole.getAppNameSpace() + "." + cenAppUserRole.getRoleName() + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), + cenAppUserRole); + } + return currentCentralizedUserAppRolesMap; + } + + @SuppressWarnings("unchecked") + private HashMap getCentralizedAppRoleList() { + List centralizedAppRoles = dataAccessService + .executeNamedQuery("getAllCentralizedAppsRoles", null, null); + HashMap cenAppRolesMap = new HashMap<>(); + for (CentralizedAppRoles CentralizedAppRole : centralizedAppRoles) { + cenAppRolesMap.put( + CentralizedAppRole.getAppNameSpace() + "." + CentralizedAppRole.getRoleName() + .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), + CentralizedAppRole); + } + return cenAppRolesMap; + } + + @Override + public ResponseEntity getUserRolesFromExtAuthSystem(String name, HttpEntity getUserRolesEntity) { + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles"); + ResponseEntity getResponse = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class); + if (getResponse.getStatusCode().value() == 200) { + logger.debug(EELFLoggerDelegate.debugLogger, "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}", + getResponse.getBody()); + + }else{ + logger.error(EELFLoggerDelegate.errorLogger, "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",getResponse.getBody() ); + EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode()); + } + return getResponse; + } + } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/MicroserviceServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/MicroserviceServiceImpl.java index 90e33bf9..e90aeb74 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/MicroserviceServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/MicroserviceServiceImpl.java @@ -49,6 +49,7 @@ import org.hibernate.criterion.Restrictions; import org.onap.portalapp.portal.domain.MicroserviceData; import org.onap.portalapp.portal.domain.MicroserviceParameter; import org.onap.portalapp.portal.logging.aop.EPMetricsLog; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.onboarding.util.CipherUtil; import org.onap.portalsdk.core.service.DataAccessService; @@ -105,11 +106,7 @@ public class MicroserviceServiceImpl implements MicroserviceService { List list = (List) dataAccessService.getList(MicroserviceData.class, null); for (int i = 0; i < list.size(); i++) { if (list.get(i).getPassword() != null) - try{ - list.get(i).setPassword(decryptedPassword(list.get(i).getPassword())); - } catch(BadPaddingException bpe){ - logger.error(EELFLoggerDelegate.errorLogger, "Couldn't decrypt - Check decryption key in system.properties - looks wrong. Still going ahead with list population though", bpe); - } + list.get(i).setPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD); //to hide password from get request list.get(i).setParameterList(getServiceParameters(list.get(i).getId())); } return list; @@ -149,8 +146,13 @@ public class MicroserviceServiceImpl implements MicroserviceService { public void updateMicroservice(long serviceId, MicroserviceData newService) throws Exception { try { newService.setId(serviceId); - if (newService.getPassword() != null) - newService.setPassword(encryptedPassword(newService.getPassword())); + if (newService.getPassword() != null){ + if(newService.getPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD)){ + MicroserviceData oldMS = getMicroserviceDataById(serviceId); + newService.setPassword(oldMS.getPassword()); // keep the old password + }else + newService.setPassword(encryptedPassword(newService.getPassword())); //new password + } getDataAccessService().saveDomainObject(newService, null); List oldService = getServiceParameters(serviceId); boolean foundParam; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java index 80411f95..1811f8dc 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java @@ -90,6 +90,7 @@ import org.onap.portalapp.portal.transport.FieldsValidator; import org.onap.portalapp.portal.transport.FunctionalMenuItem; import org.onap.portalapp.portal.transport.FunctionalMenuRole; import org.onap.portalapp.portal.transport.RemoteRole; +import org.onap.portalapp.portal.transport.RemoteRoleV1; import org.onap.portalapp.portal.transport.RemoteUserWithRoles; import org.onap.portalapp.portal.transport.RoleInAppForUser; import org.onap.portalapp.portal.transport.RolesInAppForUser; @@ -97,6 +98,7 @@ import org.onap.portalapp.portal.transport.UserApplicationRoles; import org.onap.portalapp.portal.utils.EPCommonSystemProperties; import org.onap.portalapp.portal.utils.EcompPortalUtils; import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalapp.util.SystemType; import org.onap.portalsdk.core.domain.Role; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.restful.domain.EcompRole; @@ -140,6 +142,9 @@ public class UserRolesCommonServiceImpl { @Autowired private ExternalAccessRolesService externalAccessRolesService; + @Autowired + private AppsCacheService appsCacheService; + RestTemplate template = new RestTemplate(); /** @@ -646,6 +651,24 @@ public class UserRolesCommonServiceImpl { Set updatedUserRolesinRemote = constructUsersRemoteAppRoles(roleInAppForUserList); Set updateUserRolesInEcomp = constructUsersEcompRoles(roleInAppForUserList); String userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemote); + EPApp externalApp = null; + SystemType type = SystemType.APPLICATION; + externalApp = appsCacheService.getApp(appId); + String appBaseUri = null; + Set updatedUserRolesinRemoteV1 = new TreeSet<>(); + if (externalApp != null) { + appBaseUri = (type == SystemType.APPLICATION) ? externalApp.getAppRestEndpoint() : ""; + } + if(appBaseUri != null && appBaseUri.endsWith("/api")){ + for(EcompRole eprole :updatedUserRolesinRemote) + { + RemoteRoleV1 role = new RemoteRoleV1(); + role.setId(eprole.getId()); + role.setName(eprole.getName()); + updatedUserRolesinRemoteV1.add(role); + } + userRolesAsString = mapper.writeValueAsString(updatedUserRolesinRemoteV1); + } applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString, String.format("/user/%s/roles", userId)); // TODO: We should add code that verifies that the post operation did @@ -962,18 +985,7 @@ public class UserRolesCommonServiceImpl { ObjectMapper mapper = new ObjectMapper(); HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); HttpEntity getUserRolesEntity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles"); - ResponseEntity getResponse = template - .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) - + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class); - if (getResponse.getStatusCode().value() == 200) { - logger.debug(EELFLoggerDelegate.debugLogger, "updateUserRolesInExternalSystem: Finished GET user roles from external system and received user roles {}", - getResponse.getBody()); - - }else{ - logger.error(EELFLoggerDelegate.errorLogger, "updateUserRolesInExternalSystem: Failed GET user roles from external system and received user roles {}",getResponse.getBody() ); - EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode()); - } + ResponseEntity getResponse = externalAccessRolesService.getUserRolesFromExtAuthSystem(name, getUserRolesEntity); List userRoleDetailList = new ArrayList<>(); String res = getResponse.getBody(); JSONObject jsonObj = null; @@ -1581,7 +1593,7 @@ public class UserRolesCommonServiceImpl { List cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey()); for(CentralV2Role cenRole : cenRoleList){ Role role = new Role(); - role.setActive(cenRole.isActive()); + role.setActive(cenRole.getActive()); role.setId(cenRole.getId()); role.setName(cenRole.getName()); role.setPriority(cenRole.getPriority()); @@ -1832,6 +1844,7 @@ public class UserRolesCommonServiceImpl { * @see org.onap.portalapp.portal.service.UserRolesService# * getCachedAppRolesForUser(java.lang.Long, java.lang.Long) */ + @SuppressWarnings("deprecation") 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); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserServiceImpl.java index d750f148..755de799 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserServiceImpl.java @@ -49,11 +49,9 @@ import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Restrictions; import org.json.JSONArray; import org.json.JSONObject; -import org.onap.portalapp.portal.service.UserService; -import org.onap.portalapp.portal.service.UserServiceImpl; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.utils.EPCommonSystemProperties; -import org.onap.portalsdk.core.FusionObject.Utilities; +import org.onap.portalsdk.core.domain.FusionObject.Utilities; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.onboarding.util.CipherUtil; import org.onap.portalsdk.core.service.DataAccessService; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CentralV2Role.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CentralV2Role.java index 4b758dca..54ce4f33 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CentralV2Role.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CentralV2Role.java @@ -150,7 +150,7 @@ public class CentralV2Role implements Serializable, Comparable{ this.name = name; } - public boolean isActive() { + public boolean getActive() { return active; } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CentralizedAppRoles.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CentralizedAppRoles.java new file mode 100644 index 00000000..507320f1 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/CentralizedAppRoles.java @@ -0,0 +1,111 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ +package org.onap.portalapp.portal.transport; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class CentralizedAppRoles implements Serializable{ + + private static final long serialVersionUID = 6670280863269352495L; + @Id + @Column(name = "app_id") + private Long appId; + @Column(name = "auth_namespace") + private String appNameSpace; + @Column(name = "role_name") + private String roleName; + @Id + @Column(name = "role_id") + private Long roleId; + + + /** + * @return the appId + */ + public Long getAppId() { + return appId; + } + /** + * @param appId the appId to set + */ + public void setAppId(Long appId) { + this.appId = appId; + } + /** + * @return the appNameSpace + */ + public String getAppNameSpace() { + return appNameSpace; + } + /** + * @param appNameSpace the appNameSpace to set + */ + public void setAppNameSpace(String appNameSpace) { + this.appNameSpace = appNameSpace; + } + /** + * @return the roleName + */ + public String getRoleName() { + return roleName; + } + /** + * @param roleName the roleName to set + */ + public void setRoleName(String roleName) { + this.roleName = roleName; + } + /** + * @return the roleId + */ + public Long getRoleId() { + return roleId; + } + /** + * @param roleId the roleId to set + */ + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + +} \ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/ExternalAccessUserRoleDetail.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/ExternalAccessUserRoleDetail.java index d47c5842..36ac9519 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/ExternalAccessUserRoleDetail.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/ExternalAccessUserRoleDetail.java @@ -43,9 +43,6 @@ public class ExternalAccessUserRoleDetail { private ExternalRoleDescription description; - /** - * - */ public ExternalAccessUserRoleDetail() { super(); } @@ -100,5 +97,12 @@ public class ExternalAccessUserRoleDetail { return true; } + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "ExternalAccessUserRoleDetail [name=" + name + ", description=" + description + "]"; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/RemoteRoleV1.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/RemoteRoleV1.java new file mode 100644 index 00000000..724c275d --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/RemoteRoleV1.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.transport; + +public class RemoteRoleV1 implements Comparable { + private Long id; + private String name; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + RemoteRoleV1 other = (RemoteRoleV1) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public int compareTo(RemoteRoleV1 arg0) { + return this.id.compareTo(arg0.id); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/ueb/EPUebHelper.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/ueb/EPUebHelper.java deleted file mode 100644 index 400fb7f0..00000000 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/ueb/EPUebHelper.java +++ /dev/null @@ -1,229 +0,0 @@ -/*- - * ============LICENSE_START========================================== - * ONAP Portal - * =================================================================== - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * =================================================================== - * - * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the "License"); - * you may not use this software except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); - * you may not use this documentation except in compliance with the License. - * You may obtain a copy of the License at - * - * https://creativecommons.org/licenses/by/4.0/ - * - * Unless required by applicable law or agreed to in writing, documentation - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================ - * - * - */ -package org.onap.portalapp.portal.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.onap.portalapp.portal.domain.EPApp; -import org.onap.portalapp.portal.domain.EcompApp; -import org.onap.portalapp.portal.logging.aop.EPMetricsLog; -import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum; -import org.onap.portalapp.portal.logging.logic.EPLogUtil; -import org.onap.portalapp.portal.service.EPAppService; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.onboarding.ueb.Helper; -import org.onap.portalsdk.core.onboarding.ueb.Publisher; -import org.onap.portalsdk.core.onboarding.ueb.UebException; -import org.onap.portalsdk.core.onboarding.ueb.UebManager; -import org.onap.portalsdk.core.onboarding.ueb.UebMsg; -import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; -import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; -import org.onap.portalapp.portal.ueb.EPUebHelper; -import org.onap.portalapp.portal.ueb.EPUebMsgTypes; -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 { - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUebHelper.class); - - @Autowired - private EPAppService appsService; - - @Autowired - private SessionFactory sessionFactory; - - @SuppressWarnings("unused") - private Publisher epPublisher; - - public EPUebHelper() { - - } - // - // This should only be called by the ONAP 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(logger, EPAppMessagesEnum.BeUebSystemError, e, "add/remove Publisher"); - logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while refreshing the publisher list", e); - } - - //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) { - logger.error(EELFLoggerDelegate.errorLogger, "initUeb failed", e); - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeUebConnectionError, e); - } - - Thread thread = new Thread("EPUebManager: postConstructMethod - refreshPublisherList") { - public void run(){ - refreshPublisherList(); - } - }; - thread.start(); - - } - - @EPMetricsLog - public void addPublisher(EPApp app) { - // TODO Auto-generated method stub - try { - UebManager.getInstance().addPublisher(app.getUebTopicName()); - } catch (UebException e) { - logger.error(EELFLoggerDelegate.errorLogger, "addPublisher failed", e); - } - } - - public boolean checkAvailability() { - // - // Test existence of topic at UEB url - // - // (ie http://uebsb91kcdc.it.com:3904/topics/ECOMP-PORTAL-INBOX) - // - boolean available = true; - LinkedList urlList = (LinkedList) 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(logger, 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; - logger.error(EELFLoggerDelegate.errorLogger, "checkAvailability failed", e); - } - } - } - 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(logger, EPAppMessagesEnum.BeHealthCheckUebClusterError, e); - sentMsgSuccessfully = false; - logger.warn(EELFLoggerDelegate.errorLogger, "Warning! could not successfully publish a UEB msg to " - + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME), e); - } - - return sentMsgSuccessfully; - } - -} - - diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EPCommonSystemProperties.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EPCommonSystemProperties.java index 00876389..53f6a3ee 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EPCommonSystemProperties.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EPCommonSystemProperties.java @@ -91,5 +91,10 @@ public class EPCommonSystemProperties extends SystemProperties { public static final String WIDGET_MS_HOSTNAME = "microservices.widget.hostname"; public static final String REMOTE_CENTRALIZED_SYSTEM_ACCESS = "remote_centralized_system_access"; + + public static final String APP_DISPLAY_PASSWORD = "*******"; + + public static final String MS_WIDGET_LOCAL_PORT = "microservices.widget.local.port"; + public static final String MS_WIDGET_UPLOAD_FLAG = "microservices.widget.upload.flag"; } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java index dd732771..53b69d7f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/EcompPortalUtils.java @@ -513,7 +513,7 @@ public class EcompPortalUtils { /** * - * It check whether the external auth namespace is matching with current namepsace exists in local DB + * It check whether the external auth namespace is matching with current namespace exists in local DB * * @param permTypeVal * @param appNamespaceVal @@ -523,9 +523,13 @@ public class EcompPortalUtils { String[] typeNamespace = permTypeVal.split("\\."); String[] appNamespace = appNamespaceVal.split("\\."); boolean isNamespaceMatching = true; - for (int k = 0; k < appNamespace.length; k++) { - if (!appNamespace[k].equals(typeNamespace[k])) - isNamespaceMatching = false; + if (appNamespace.length <= typeNamespace.length) { + for (int k = 0; k < appNamespace.length; k++) { + if (!appNamespace[k].equals(typeNamespace[k])) + isNamespaceMatching = false; + } + } else { + isNamespaceMatching = false; } return isNamespaceMatching; } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/MusicCookieCsrfTokenRepository.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/MusicCookieCsrfTokenRepository.java new file mode 100644 index 00000000..75c66162 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/MusicCookieCsrfTokenRepository.java @@ -0,0 +1,102 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * 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.onap.portalapp.portal.utils; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.music.eelf.logging.EELFLoggerDelegate; +import org.onap.portalapp.music.service.MusicService; +import org.springframework.security.web.csrf.CookieCsrfTokenRepository; +import org.springframework.security.web.csrf.CsrfToken; +import org.springframework.security.web.csrf.CsrfTokenRepository; +import org.springframework.security.web.csrf.DefaultCsrfToken; +import org.springframework.util.StringUtils; + + +public final class MusicCookieCsrfTokenRepository implements CsrfTokenRepository { + static final String CSRF_COOKIE_NAME = "XSRF-TOKEN"; + static final String CSRF_HEADER_NAME = "X-XSRF-TOKEN"; + static final String CSRF_PARAMETER_NAME = "_csrf"; + static final String EP_SERVICE = "EPService"; + CookieCsrfTokenRepository cookieRepo = null; + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicService.class); + + public MusicCookieCsrfTokenRepository() { + } + + public MusicCookieCsrfTokenRepository(CookieCsrfTokenRepository _cookieRepo) { + this(); + cookieRepo = _cookieRepo; + } + + @Override + public CsrfToken generateToken(HttpServletRequest request) { + return cookieRepo.generateToken(request) ; + } + + @Override + public void saveToken(CsrfToken token, HttpServletRequest request, + HttpServletResponse response) { + logger.debug(EELFLoggerDelegate.debugLogger, "initialize save csrf token ..."); + cookieRepo.saveToken(token, request, response); + } + + @Override + public CsrfToken loadToken(HttpServletRequest request) { + logger.debug(EELFLoggerDelegate.debugLogger, "initialize load csrf token ..."); + CsrfToken cookieRepoToken = cookieRepo.loadToken(request); + if(cookieRepoToken==null){ // if cookieRepo does not has the token, check the cassandra for the values stored by other tomcats + try { // todo this part of the code needs to be replaced with out depending on EPService cookie + String sessionId = getSessionIdFromCookie(request); + String token = MusicService.getAttribute(CSRF_COOKIE_NAME, sessionId); + if (token==null || !StringUtils.hasLength(token)) + return null; + cookieRepoToken = new DefaultCsrfToken(CSRF_HEADER_NAME, CSRF_PARAMETER_NAME , token); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Error while calling csrf saveToken" , e); + } + } + return cookieRepoToken; + } + + /** + * Factory method to conveniently create an instance that has + * {@link #setCookieHttpOnly(boolean)} set to false. + * + * @return an instance of CookieCsrfTokenRepository with + * {@link #setCookieHttpOnly(boolean)} set to false + */ + public static MusicCookieCsrfTokenRepository withHttpOnlyFalse() { + CookieCsrfTokenRepository result = new CookieCsrfTokenRepository(); + result.setCookieHttpOnly(false); + return new MusicCookieCsrfTokenRepository(result); + } + + private String getSessionIdFromCookie (HttpServletRequest request){ + Cookie cookies[] = request.getCookies(); + if (cookies != null) { + for (Cookie cookie : cookies) { + if (EP_SERVICE.equals(cookie.getName())) { + return cookie.getValue(); + } + } + } + return null; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/service/sessionmgt/TimeoutHandler.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/service/sessionmgt/TimeoutHandler.java index fb324c29..fe1d29d6 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/service/sessionmgt/TimeoutHandler.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/service/sessionmgt/TimeoutHandler.java @@ -245,6 +245,7 @@ public class TimeoutHandler extends QuartzJobBean { return ""; String jSessionKey = (String) attribute; return jSessionKey.split("-")[0]; + //return jSessionKey; } private static ApplicationContext applicationContext; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/uebhandler/FunctionalMenuHandler.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/uebhandler/FunctionalMenuHandler.java new file mode 100644 index 00000000..b366d0da --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/uebhandler/FunctionalMenuHandler.java @@ -0,0 +1,133 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ +package org.onap.portalapp.uebhandler; + +import java.util.List; + +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.logging.aop.EPAuditLog; +import org.onap.portalapp.portal.service.AdminRolesService; +import org.onap.portalapp.portal.service.FunctionalMenuService; +import org.onap.portalapp.portal.service.SearchService; +import org.onap.portalapp.portal.transport.FunctionalMenuItem; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.onboarding.ueb.UebException; +import org.onap.portalsdk.core.onboarding.ueb.UebManager; +import org.onap.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; + +import com.google.gson.Gson; + +@Component +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class FunctionalMenuHandler { + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FunctionalMenuHandler.class); + + @Autowired + private AdminRolesService adminRolesService; + + @Autowired + private FunctionalMenuService functionalMenuService; + + @Autowired + private SearchService searchSvc; + + @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, "getFunctionalMenu failed on UEB exception", e); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getFunctionalMenu failed", e); + } + + return true; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/uebhandler/InitUebHandler.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/uebhandler/InitUebHandler.java new file mode 100644 index 00000000..472be3fb --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/uebhandler/InitUebHandler.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + * + */ +package org.onap.portalapp.uebhandler; + +import java.util.concurrent.ConcurrentLinkedQueue; + +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.onboarding.ueb.UebManager; +import org.onap.portalsdk.core.onboarding.ueb.UebMsg; +import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; +import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; + +// +// 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 { + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(InitUebHandler.class); + + // @Autowired + private 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.info(EELFLoggerDelegate.errorLogger, "Not starting UEB listening thread because property could not be read " + PortalApiConstants.UEB_LISTENERS_ENABLE); + } + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/uebhandler/MainUebHandler.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/uebhandler/MainUebHandler.java new file mode 100644 index 00000000..33647874 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/uebhandler/MainUebHandler.java @@ -0,0 +1,125 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ +package org.onap.portalapp.uebhandler; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.concurrent.ConcurrentLinkedQueue; + +import org.onap.portalapp.portal.ueb.EPUebMsgTypes; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.onboarding.ueb.UebMsg; +import org.onap.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"); + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MainUebHandler.class); + + private ConcurrentLinkedQueue inboxQueue = null; + + @Autowired + private FunctionalMenuHandler funcMenuHandler; + + @Autowired + private 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(EPCommonSystemProperties.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, "runHandler interrupted", e); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "runHandler failed", e); + } + } + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/uebhandler/WidgetNotificationHandler.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/uebhandler/WidgetNotificationHandler.java new file mode 100644 index 00000000..f91647e6 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/uebhandler/WidgetNotificationHandler.java @@ -0,0 +1,109 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ +package org.onap.portalapp.uebhandler; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.List; + +import org.onap.portalapp.portal.domain.EPApp; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.logging.aop.EPMetricsLog; +import org.onap.portalapp.portal.service.EPAppService; +import org.onap.portalapp.portal.service.SearchService; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.onboarding.ueb.UebException; +import org.onap.portalsdk.core.onboarding.ueb.UebManager; +import org.onap.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 { + private 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 failed", e); + } + } + } + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "handleWidgetNotification: user " + requestMsg.getUserId() + " not found, source = " + + requestMsg.getSourceTopicName() + + ". This widget notification cannot be posted to other widgets"); + } + } + } + +} -- cgit 1.2.3-korg