summaryrefslogtreecommitdiffstats
path: root/ecomp-portal-BE/src/main
diff options
context:
space:
mode:
Diffstat (limited to 'ecomp-portal-BE/src/main')
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/authentication/LoginStrategy.java27
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/authentication/OpenIdConnectLoginStrategy.java91
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/authentication/SimpleLoginStrategy.java101
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/command/EPLoginBean.java186
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/command/PostSearchBean.java373
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java311
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java60
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java38
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/ECOMPLogoutController.java112
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/EPFusionBaseController.java106
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/EPRestrictedBaseController.java52
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/EPRestrictedRESTfulBaseController.java54
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/EPUnRestrictedBaseController.java42
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/LoginController.java356
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/LoginService.java36
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/OpenCollaborationController.java48
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/PeerBroadcastSocket.java106
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/UserProfileController.java77
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/WelcomeController.java89
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/sessionmgt/SessionCommunicationController.java64
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/controller/KpiDashboardController.java268
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/model/KpiApiStats.java74
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/model/KpiServiceSupported.java60
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/model/KpiUserStoryStats.java107
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/model/KpidashProperties.java33
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/service/KpiDashboardService.java56
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/service/KpiDashboardServiceImpl.java180
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/model/Result.java37
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/AppCatalogController.java124
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/AppContactUsController.java224
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/AppsController.java470
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/DashboardController.java361
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/DashboardSearchResultController.java243
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java128
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/FunctionalMenuController.java436
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/GetAccessController.java70
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/HealthCheckController.java234
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/ManifestController.java93
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java117
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/SharedContextRestController.java335
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java336
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsController.java134
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AdminUserApp.java88
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AdminUserApplications.java96
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AppContactUs.java86
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AppContactUsTransportModel.java84
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AppIdAndNameTransportModel.java63
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AppsResponse.java76
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/EPApp.java319
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/EPRole.java204
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/EPUser.java602
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/EPUserApp.java119
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/EcompApp.java143
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/GetAccessResult.java70
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/GetAccessResultId.java64
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/PersUserAppSelection.java79
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/SharedContext.java161
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/UserIdRoleId.java77
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/UserRole.java91
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/UserRoles.java111
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/Widget.java104
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppCatalogItem.java159
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppCategoryFunctionsItem.java84
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppContactUsItem.java104
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/CommonWidgetsEnum.java36
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/PortalRestResponse.java60
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/PortalRestStatusEnum.java35
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/SearchResultItem.java92
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/interceptor/PortalResourceInterceptor.java95
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/interceptor/SessionTimeoutInterceptor.java97
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/listener/HealthMonitor.java393
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/listener/UserContextListener.java49
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/listener/UserSessionListener.java125
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPAuditLog.java31
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAdvice.java341
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAspect.java204
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPMetricsLog.java31
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/format/ApplicationCodes.properties141
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/format/EPAppMessagesEnum.java260
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/format/EPErrorCodesEnum.java95
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/logic/EPLogUtil.java76
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesService.java52
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesServiceImpl.java318
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AppContactUsService.java55
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AppContactUsServiceImpl.java178
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientService.java28
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientServiceImpl.java267
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheService.java40
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheServiceImple.java104
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/DashboardSearchService.java38
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/DashboardSearchServiceImpl.java238
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPAppService.java164
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPAppServiceImpl.java1218
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPAuditService.java26
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPAuditServiceImpl.java74
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPLdapService.java31
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPLdapServiceImpl.java287
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPLoginService.java42
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPLoginServiceImpl.java235
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPRoleService.java32
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPRoleServiceImpl.java149
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/FunctionalMenuService.java50
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/FunctionalMenuServiceImpl.java862
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/GetAccessService.java32
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/GetAccessServiceImpl.java50
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/ManifestService.java34
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/ManifestServiceImpl.java65
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/PersUserAppService.java24
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/PersUserAppServiceImpl.java117
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminService.java31
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminServiceImpl.java179
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/SearchService.java38
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/SearchServiceImpl.java188
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/SharedContextService.java98
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/SharedContextServiceImpl.java173
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/UserRolesService.java58
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/UserRolesServiceImpl.java656
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/UserService.java34
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/UserServiceImpl.java260
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/WidgetService.java36
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/WidgetServiceImpl.java275
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/AllAppsWithRolesForUser.java40
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/AppCatalogPersonalization.java38
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/AppNameIdIsAdmin.java31
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/AppWithRolesForUser.java34
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/AppsListWithAdminRole.java34
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/CommonWidget.java140
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/CommonWidgetMeta.java50
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/EventWidget.java139
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/EventWidgetMeta.java52
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FavoritesFunctionalMenuItem.java45
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FavoritesFunctionalMenuItemJson.java57
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FieldsValidator.java49
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuItem.java90
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuItemJson.java52
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuRole.java49
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/LocalRole.java42
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java83
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingWidget.java65
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/PortalAdmin.java53
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/PortalAdminUserRole.java48
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/RemoteRole.java28
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/RemoteUserWithRoles.java63
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/RoleInAppForUser.java39
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/RolesInAppForUser.java33
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/UserApplicationRoles.java41
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/UserWithNameSurnameTitle.java39
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java218
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebMsgTypes.java27
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/CustomLoggingFilter.java60
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/EPSystemProperties.java77
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/EcompPortalUtils.java248
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/EcompVersion.java33
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/HashMapFromList.java100
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/ParallelExecutor.java83
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/scheduler/LogJob.java45
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/scheduler/LogRegistry.java57
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/scheduler/Register.java86
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/scheduler/RegistryAdapter.java100
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/scheduler/SessionMgtRegistry.java89
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/AdminAuthExtension.java35
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/EPProfileService.java36
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/EPProfileServiceImpl.java76
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/CoreTimeoutHandler.java166
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/ManageService.java101
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/RemoteWebServiceCallService.java44
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/RemoteWebServiceCallServiceImpl.java83
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/SessionCommunication.java274
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/TimeoutHandler.java252
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/uebhandler/FunctionalMenuHandler.java126
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/uebhandler/InitUebHandler.java75
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/uebhandler/MainUebHandler.java115
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/uebhandler/WidgetNotificationHandler.java93
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/util/EPUserUtils.java308
-rw-r--r--ecomp-portal-BE/src/main/java/org/openecomp/portalapp/util/SessionCookieUtil.java129
-rw-r--r--ecomp-portal-BE/src/main/resources/cache.ccf30
-rw-r--r--ecomp-portal-BE/src/main/resources/logback.xml285
-rw-r--r--ecomp-portal-BE/src/main/resources/openid-connect.properties22
-rw-r--r--ecomp-portal-BE/src/main/resources/openid-keystore.jwks12
-rw-r--r--ecomp-portal-BE/src/main/resources/portal.properties44
180 files changed, 23393 insertions, 0 deletions
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/authentication/LoginStrategy.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/authentication/LoginStrategy.java
new file mode 100644
index 00000000..69bf5ec9
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/authentication/LoginStrategy.java
@@ -0,0 +1,27 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.authentication;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+public interface LoginStrategy {
+ public boolean login(HttpServletRequest request, HttpServletResponse response) throws Exception;
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/authentication/OpenIdConnectLoginStrategy.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/authentication/OpenIdConnectLoginStrategy.java
new file mode 100644
index 00000000..75ade471
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/authentication/OpenIdConnectLoginStrategy.java
@@ -0,0 +1,91 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.authentication;
+
+import java.util.HashSet;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.mitre.openid.connect.model.UserInfo;
+import org.openecomp.portalapp.command.EPLoginBean;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalapp.util.SessionCookieUtil;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.util.StringUtils;
+
+public class OpenIdConnectLoginStrategy implements LoginStrategy {
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(OpenIdConnectLoginStrategy.class);
+
+ private static final String GLOBAL_LOCATION_KEY = "Location";
+
+ @SuppressWarnings("rawtypes")
+ public boolean login(HttpServletRequest request, HttpServletResponse response){
+
+ logger.info("Attempting Login");
+
+ //check both authentication cookie and authentication header
+ UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
+
+ if (userInfo != null && !StringUtils.isEmpty(userInfo.getPreferredUsername())) {
+ //package the userid in the login form for processing
+ EPLoginBean commandBean = new EPLoginBean();
+ commandBean.setOrgUserId(userInfo.getPreferredUsername());
+
+ EPUser user = new EPUser();
+
+ user.setOrgUserId(userInfo.getPreferredUsername());
+ user.setEmail(userInfo.getEmail());
+ user.setFirstName(userInfo.getName());
+ user.setLastName(userInfo.getFamilyName());
+
+ //store the currently logged in user's information in the session
+ EPUserUtils.setUserSession(request, user, new HashSet(), new HashSet(), SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM));
+
+ logger.info(EELFLoggerDelegate.errorLogger, request.getContextPath());
+ SessionCookieUtil.preSetUp(request, response);
+ return true;
+ } else {
+ // in case authentication cookie is missing, send 401 UNAUTHORIZED to client and it will redirect to Logon
+
+ try {
+ String authentication = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM);
+ String loginUrl = SystemProperties.getProperty(EPSystemProperties.LOGIN_URL_NO_RET_VAL);
+ logger.info(EELFLoggerDelegate.errorLogger, "Authentication Mechanism: '" + authentication + "'.");
+
+ if (authentication == null || authentication.equals("") || authentication.trim().equals("OIDC")) {
+ response.sendRedirect("oid-login");
+ } else {
+ logger.info(EELFLoggerDelegate.errorLogger, "No cookies are found, redirecting the request to '" + loginUrl + "'.");
+ response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
+ response.setHeader(GLOBAL_LOCATION_KEY, loginUrl);
+ }
+ } catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in preHandle() while redirecting, Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+ }
+ return false;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/authentication/SimpleLoginStrategy.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/authentication/SimpleLoginStrategy.java
new file mode 100644
index 00000000..eb09dc08
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/authentication/SimpleLoginStrategy.java
@@ -0,0 +1,101 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.authentication;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.command.EPLoginBean;
+import org.openecomp.portalapp.portal.service.EPLoginService;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalapp.util.SessionCookieUtil;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.menu.MenuProperties;
+import org.openecomp.portalsdk.core.onboarding.crossapi.ECOMPSSO;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.util.StringUtils;
+
+public class SimpleLoginStrategy implements LoginStrategy{
+
+ @Autowired
+ private EPLoginService loginService;
+
+ private static final String GLOBAL_LOCATION_KEY = "Location";
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SimpleLoginStrategy.class);
+
+ public boolean login(HttpServletRequest request, HttpServletResponse response) throws Exception{
+ logger.info("Attempting 'Simple' Login");
+
+ //check both authentication cookie and authentication header
+ String orgUserId = null;
+ try{
+ orgUserId = ECOMPSSO.getUserIdFromCookie(request);
+ } catch(Exception ex){
+ logger.error(EELFLoggerDelegate.errorLogger, "Error getting User ID: '" + ex.getLocalizedMessage() + "'.");
+ }
+
+
+ if (!StringUtils.isEmpty(orgUserId)) {
+ // package the userid in the login form for processing
+ EPLoginBean commandBean = new EPLoginBean();
+ commandBean.setOrgUserId(orgUserId);
+ commandBean = loginService.findUser(commandBean, (String)request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), null);
+
+ // in case authentication has passed but user is not in the ECOMP data base, return a Guest User to the home page.
+ if (commandBean.getUser() == null) {
+ }
+ else {
+ // store the currently logged in user's information in the session
+ EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), "");
+ logger.info(EELFLoggerDelegate.debugLogger, commandBean.getUser().getOrgUserId() + " exists in the the system.");
+ }
+
+ logger.info(EELFLoggerDelegate.errorLogger, request.getContextPath());
+ SessionCookieUtil.preSetUp(request, response);
+ return true;
+ } else {
+ // in case authentication cookie is missing, send 401 UNAUTHORIZED to client and it will redirect to Logon
+ try {
+ String authentication = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM);
+ String loginUrl = SystemProperties.getProperty(EPSystemProperties.LOGIN_URL_NO_RET_VAL);
+ logger.info(EELFLoggerDelegate.errorLogger, "Authentication Mechanism: '" + authentication + "'.");
+ if (authentication == null || authentication.equals("") || authentication.trim().equals("BOTH")) {
+
+ logger.info(EELFLoggerDelegate.errorLogger, "No cookies are found, redirecting the request to '" + loginUrl + "'.");
+ response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
+ response.setHeader(GLOBAL_LOCATION_KEY, loginUrl); //returnUrl + "/index.htm");
+ }else {
+ logger.info(EELFLoggerDelegate.errorLogger, "No cookies are found, redirecting the request to '" + loginUrl + "'.");
+ response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
+ response.setHeader(GLOBAL_LOCATION_KEY, loginUrl); //returnUrl + "/index.htm");
+ }
+ } catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in preHandle() while redirecting, Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+ }
+
+ return false;
+
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/command/EPLoginBean.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/command/EPLoginBean.java
new file mode 100644
index 00000000..e3bb1433
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/command/EPLoginBean.java
@@ -0,0 +1,186 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.command;
+
+import java.util.Set;
+
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalsdk.core.domain.support.FusionCommand;
+
+public class EPLoginBean extends FusionCommand {
+ private String loginId;
+ private String loginPwd;
+ private String hrid;
+ private String orgUserId;
+ private String siteAccess;
+ private String loginErrorMessage;
+
+ private EPUser user;
+ private Set<?> menu;
+ private Set<?> businessDirectMenu;
+
+ /**
+ * getLoginId
+ *
+ * @return String
+ */
+ public String getLoginId() {
+ return loginId;
+ }
+
+ /**
+ * getLoginPwd
+ *
+ * @return String
+ */
+ public String getLoginPwd() {
+ return loginPwd;
+ }
+
+ /**
+ * getMenu
+ *
+ * @return Set
+ */
+ public Set<?> getMenu() {
+ return menu;
+ }
+
+ /**
+ * getUser
+ *
+ * @return User
+ */
+ public EPUser getUser() {
+ return user;
+ }
+
+ /**
+ * getHrid
+ *
+ * @return String
+ */
+ public String getHrid() {
+ return hrid;
+ }
+
+ /**
+ * getSiteAccess
+ *
+ * @return String
+ */
+ public String getSiteAccess() {
+ return siteAccess;
+ }
+
+ /**
+ * getBusinessDirectMenu
+ *
+ * @return Set
+ */
+ public Set<?> getBusinessDirectMenu() {
+ return businessDirectMenu;
+ }
+
+ /**
+ * getLoginErrorMessage
+ *
+ * @return String
+ */
+ public String getLoginErrorMessage() {
+ return loginErrorMessage;
+ }
+
+ public String getOrgUserId() {
+ return orgUserId;
+ }
+
+ /**
+ * setLoginId
+ *
+ * @param loginId String
+ */
+ public void setLoginId(String loginId) {
+ this.loginId = loginId;
+ }
+
+ /**
+ * setLoginPwd
+ *
+ * @param loginPwd String
+ */
+ public void setLoginPwd(String loginPwd) {
+ this.loginPwd = loginPwd;
+ }
+
+ public void setMenu(Set<?> menu) {
+ this.menu = menu;
+ }
+
+ /**
+ * setUser
+ *
+ * @param user User
+ */
+ public void setUser(EPUser user) {
+ this.user = user;
+ }
+
+ /**
+ * setHrid
+ *
+ * @param hrid String
+ */
+ public void setHrid(String hrid) {
+ this.hrid = hrid;
+ }
+
+ /**
+ * setSiteAccess
+ *
+ * @param siteAccess String
+ */
+ public void setSiteAccess(String siteAccess) {
+ this.siteAccess = siteAccess;
+ }
+
+ /**
+ * setBusinessDirectMenu
+ *
+ * @param businessDirectMenu Set
+ */
+ public void setBusinessDirectMenu(Set<?> businessDirectMenu) {
+ this.businessDirectMenu = businessDirectMenu;
+ }
+
+ /**
+ * setLoginErrorMessage
+ *
+ * @param loginErrorMessage String
+ */
+ public void setLoginErrorMessage(String loginErrorMessage) {
+ this.loginErrorMessage = loginErrorMessage;
+ }
+
+ public void setOrgUserId(String orgUserId) {
+ this.orgUserId = orgUserId;
+ }
+}
+
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/command/PostSearchBean.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/command/PostSearchBean.java
new file mode 100644
index 00000000..0f58807b
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/command/PostSearchBean.java
@@ -0,0 +1,373 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.command;
+
+import java.util.List;
+
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalsdk.core.command.support.SearchBase;
+
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+
+@JsonSerialize
+public class PostSearchBean extends SearchBase {
+
+ private EPUser user = null;
+ private EPUser userOrig = null;
+ private String[] selected;
+ private String[] postHrid;
+ private String[] postOrgUserId;
+ private String[] postFirstName;
+ private String[] postLastName;
+ private String[] postOrgCode;
+ private String[] postPhone;
+ private String[] postEmail;
+ private String[] postAddress1;
+ private String[] postAddress2;
+ private String[] postCity;
+ private String[] postState;
+ private String[] postZipCode;
+ private String[] postLocationClli;
+ private String[] postBusinessCountryCode;
+ private String[] postBusinessCountryName;
+ private String[] postDepartment;
+ private String[] postDepartmentName;
+ private String[] postBusinessUnit;
+ private String[] postBusinessUnitName;
+ private String[] postJobTitle;
+ private String[] postOrgManagerUserId;
+ private String[] postCommandChain;
+ private String[] postCompanyCode;
+ private String[] postCompany;
+ private String[] postCostCenter;
+ private String[] postSiloStatus;
+ private String[] postFinancialLocCode;
+
+
+ public PostSearchBean() {
+ this(null);
+ } // PostSearchBean
+
+ public PostSearchBean(List<?> items) {
+ super(items);
+
+ user = new EPUser();
+ userOrig = new EPUser();
+
+ setSortBy1("");
+ setSortBy1Orig("");
+
+ //setSortByList(...);
+ } // PostSearchBean
+
+
+ public String getFirstName() { return user.getFirstName(); }
+ public String getLastName() { return user.getLastName(); }
+ public String getHrid() { return user.getHrid(); }
+ public String getOrgUserId() { return user.getOrgUserId(); }
+ public String getOrgCode() { return user.getOrgCode(); }
+ public String getEmail() { return user.getEmail(); }
+ public String getOrgManagerUserId() { return user.getOrgManagerUserId(); }
+
+ public String getFirstNameOrig() { return user.getFirstName(); }
+ public String getLastNameOrig() { return user.getLastName(); }
+ public String getHridOrig() { return user.getHrid(); }
+ public String getOrgUserIdOrig() { return user.getOrgUserId(); }
+ public String getOrgCodeOrig() { return user.getOrgCode(); }
+ public String getEmailOrig() { return user.getEmail(); }
+ public String getOrgManagerUserIdOrig() { return user.getOrgManagerUserId(); }
+
+
+ public EPUser getUser() { return user; }
+
+ public String[] getPostEmail() {
+ return postEmail;
+ }
+
+ public String[] getPostFirstName() {
+ return postFirstName;
+ }
+
+ public String[] getPostHrid() {
+ return postHrid;
+ }
+
+ public String[] getPostLastName() {
+ return postLastName;
+ }
+
+ public String[] getPostOrgCode() {
+ return postOrgCode;
+ }
+
+ public String[] getPostPhone() {
+ return postPhone;
+ }
+
+ public String[] getPostOrgUserId() {
+ return postOrgUserId;
+ }
+
+ public String[] getSelected() {
+ return selected;
+ }
+
+ public String[] getPostAddress1() {
+ return postAddress1;
+ }
+
+ public String[] getPostBusinessCountryCode() {
+ return postBusinessCountryCode;
+ }
+
+ public String[] getPostCity() {
+ return postCity;
+ }
+
+ public String[] getPostCommandChain() {
+ return postCommandChain;
+ }
+
+ public String[] getPostCompany() {
+ return postCompany;
+ }
+
+ public String[] getPostCompanyCode() {
+ return postCompanyCode;
+ }
+
+ public String[] getPostDepartment() {
+ return postDepartment;
+ }
+
+ public String[] getPostDepartmentName() {
+ return postDepartmentName;
+ }
+
+ public String[] getPostBusinessCountryName() {
+ return postBusinessCountryName;
+ }
+
+ public String[] getPostJobTitle() {
+ return postJobTitle;
+ }
+
+ public String[] getPostLocationClli() {
+ return postLocationClli;
+ }
+
+ public String[] getPostManagerUserId() {
+ return postOrgManagerUserId;
+ }
+
+ public String[] getPostState() {
+ return postState;
+ }
+
+ public String[] getPostZipCode() {
+ return postZipCode;
+ }
+
+ public void setFirstName(String value) { user.setFirstName(value); }
+ public void setLastName(String value) { user.setLastName(value); }
+ public void setHrid(String value) { user.setHrid(value); }
+ public void setOrgUserId(String value) { user.setOrgUserId(value); }
+ public void setOrgCode(String value) { user.setOrgCode(value); }
+ public void setEmail(String value) { user.setEmail(value); }
+ public void setOrgManagerUserId(String value) { user.setOrgManagerUserId(value); }
+
+ public void setFirstNameOrig(String value) { userOrig.setFirstName(value); }
+ public void setLastNameOrig(String value) { userOrig.setLastName(value); }
+ public void setHridOrig(String value) { userOrig.setHrid(value); }
+ public void setOrgUserIdOrig(String value) { userOrig.setOrgUserId(value); }
+ public void setOrgCodeOrig(String value) { userOrig.setOrgCode(value); }
+ public void setEmailOrig(String value) { userOrig.setEmail(value); }
+ public void setOrgManagerUserIdOrig(String value) { userOrig.setOrgManagerUserId(value); }
+
+ public void setUser(EPUser value) { this.user = value; }
+
+ public void setPostEmail(String[] postEmail) {
+ this.postEmail = postEmail;
+ }
+
+ public void setPostFirstName(String[] postFirstName) {
+ this.postFirstName = postFirstName;
+ }
+
+ public void setPostHrid(String[] postHrid) {
+ this.postHrid = postHrid;
+ }
+
+ public void setPostLastName(String[] postLastName) {
+ this.postLastName = postLastName;
+ }
+
+ public void setPostOrgCode(String[] postOrgCode) {
+ this.postOrgCode = postOrgCode;
+ }
+
+ public void setPostPhone(String[] postPhone) {
+ this.postPhone = postPhone;
+ }
+
+ public void setPostUserId(String[] postOrgUserId) {
+ this.postOrgUserId = postOrgUserId;
+ }
+
+ public void setSelected(String[] selected) {
+ this.selected = selected;
+ }
+
+ public void setPostAddress1(String[] postAddress1) {
+ this.postAddress1 = postAddress1;
+ }
+
+ public void setPostBusinessCountryCode(String[] postBusinessCountryCode) {
+ this.postBusinessCountryCode = postBusinessCountryCode;
+ }
+
+ public void setPostCity(String[] postCity) {
+ this.postCity = postCity;
+ }
+
+ public void setPostCommandChain(String[] postCommandChain) {
+ this.postCommandChain = postCommandChain;
+ }
+
+ public void setPostCompany(String[] postCompany) {
+ this.postCompany = postCompany;
+ }
+
+ public void setPostCompanyCode(String[] postCompanyCode) {
+ this.postCompanyCode = postCompanyCode;
+ }
+
+ public void setPostDepartment(String[] postDepartment) {
+ this.postDepartment = postDepartment;
+ }
+
+ public void setPostDepartmentName(String[] postDepartmentName) {
+ this.postDepartmentName = postDepartmentName;
+ }
+
+ public void setPostBusinessCountryName(String[] postBusinessCountryName) {
+ this.postBusinessCountryName = postBusinessCountryName;
+ }
+
+ public void setPostJobTitle(String[] postJobTitle) {
+ this.postJobTitle = postJobTitle;
+ }
+
+ public void setPostLocationClli(String[] postLocationClli) {
+ this.postLocationClli = postLocationClli;
+ }
+
+ public void setPostManagerUserId(String[] postOrgManagerUserId) {
+ this.postOrgManagerUserId = postOrgManagerUserId;
+ }
+
+ public void setPostState(String[] postState) {
+ this.postState = postState;
+ }
+
+ public void setPostZipCode(String[] postZipCode) {
+ this.postZipCode = postZipCode;
+ }
+
+ public String[] getPostAddress2() {
+ return postAddress2;
+ }
+
+ public void setPostAddress2(String[] postAddress2) {
+ this.postAddress2 = postAddress2;
+ }
+
+ public EPUser getUserOrig() {
+ return userOrig;
+ }
+
+ public void setUserOrig(EPUser userOrig) {
+ this.userOrig = userOrig;
+ }
+
+ public String[] getPostBusinessUnit() {
+ return postBusinessUnit;
+ }
+
+ public void setPostBusinessUnit(String[] postBusinessUnit) {
+ this.postBusinessUnit = postBusinessUnit;
+ }
+
+ public String[] getPostBusinessUnitName() {
+ return postBusinessUnitName;
+ }
+
+ public void setPostBusinessUnitName(String[] postBusinessUnitName) {
+ this.postBusinessUnitName = postBusinessUnitName;
+ }
+
+ public String[] getPostCostCenter() {
+ return postCostCenter;
+ }
+
+ public void setPostCostCenter(String[] postCostCenter) {
+ this.postCostCenter = postCostCenter;
+ }
+
+ public String[] getPostSiloStatus() {
+ return postSiloStatus;
+ }
+
+ public void setPostSiloStatus(String[] postSiloStatus) {
+ this.postSiloStatus = postSiloStatus;
+ }
+
+ public String[] getPostFinancialLocCode() {
+ return postFinancialLocCode;
+ }
+
+ public void setPostFinancialLocCode(String[] postFinancialLocCode) {
+ this.postFinancialLocCode = postFinancialLocCode;
+ }
+
+ public void resetSearch() {
+ super.resetSearch();
+ setUser(new EPUser());
+ } // resetSearch
+
+
+ public boolean isCriteriaUpdated() {
+ if(user==null&&userOrig==null)
+ return false;
+ else if(user==null||userOrig==null)
+ return true;
+ else
+ return (! (
+ Utilities.nvl(user.getFirstName()).equals(Utilities.nvl(userOrig.getFirstName()))&&
+ Utilities.nvl(user.getLastName()).equals(Utilities.nvl(userOrig.getLastName()))&&
+ //Utilities.nvl(user.getHrid()).equals(Utilities.nvl(userOrig.getHrid()))&&
+ Utilities.nvl(user.getOrgUserId()).equals(Utilities.nvl(userOrig.getOrgUserId()))&&
+ Utilities.nvl(user.getOrgCode()).equals(Utilities.nvl(userOrig.getOrgCode()))&&
+ Utilities.nvl(user.getEmail()).equals(Utilities.nvl(userOrig.getEmail()))&&
+ Utilities.nvl(user.getOrgManagerUserId()).equals(Utilities.nvl(userOrig.getOrgManagerUserId()))&&
+ true));
+ } // isCriteriaUpdated
+
+} // PostSearchBean
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java
new file mode 100644
index 00000000..5bcb4303
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java
@@ -0,0 +1,311 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.conf;
+
+import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY;
+import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID;
+import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
+import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS;
+import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID;
+import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
+
+import java.net.InetAddress;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.List;
+
+import javax.annotation.PostConstruct;
+
+import org.openecomp.portalapp.authentication.LoginStrategy;
+import org.openecomp.portalapp.authentication.OpenIdConnectLoginStrategy;
+import org.openecomp.portalapp.authentication.SimpleLoginStrategy;
+import org.openecomp.portalapp.portal.interceptor.PortalResourceInterceptor;
+import org.openecomp.portalapp.portal.interceptor.SessionTimeoutInterceptor;
+import org.openecomp.portalapp.portal.listener.HealthMonitor;
+import org.openecomp.portalapp.portal.service.EPLoginService;
+import org.openecomp.portalapp.portal.service.EPLoginServiceImpl;
+import org.openecomp.portalapp.portal.ueb.EPUebHelper;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.scheduler.RegistryAdapter;
+import org.openecomp.portalapp.uebhandler.FunctionalMenuHandler;
+import org.openecomp.portalapp.uebhandler.InitUebHandler;
+import org.openecomp.portalapp.uebhandler.MainUebHandler;
+import org.openecomp.portalapp.uebhandler.WidgetNotificationHandler;
+import org.openecomp.portalsdk.core.conf.AppConfig;
+import org.openecomp.portalsdk.core.conf.Configurable;
+import org.openecomp.portalsdk.core.controller.LogoutController;
+import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager;
+import org.openecomp.portalsdk.core.service.DataAccessService;
+import org.openecomp.portalsdk.core.service.FnMenuService;
+import org.openecomp.portalsdk.core.service.FnMenuServiceImpl;
+import org.openecomp.portalsdk.core.util.CacheManager;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.ComponentScan.Filter;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.FilterType;
+import org.springframework.context.annotation.Profile;
+import org.springframework.scheduling.annotation.EnableAsync;
+import org.springframework.scheduling.annotation.EnableScheduling;
+import org.springframework.scheduling.quartz.SchedulerFactoryBean;
+import org.springframework.web.servlet.ViewResolver;
+import org.springframework.web.servlet.config.annotation.EnableWebMvc;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
+
+@Configuration
+@EnableWebMvc
+@ComponentScan(basePackages = {"org.openecomp"}, excludeFilters = {
+ @Filter(value = { LogoutController.class }, type = FilterType.ASSIGNABLE_TYPE) })
+@Profile("src")
+@EnableAsync
+@EnableScheduling
+public class ExternalAppConfig extends AppConfig implements Configurable {
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppConfig.class);
+
+ private RegistryAdapter schedulerRegistryAdapter;
+
+ public ViewResolver viewResolver() {
+ return super.viewResolver();
+ }
+
+ @Override
+ public void addResourceHandlers(ResourceHandlerRegistry registry) {
+ registry.addResourceHandler("/static/**").addResourceLocations("/static/");
+ registry.addResourceHandler("/images/**").addResourceLocations("/images/");
+ registry.addResourceHandler("/**").addResourceLocations("/public/");
+ }
+
+ @PostConstruct
+ private void init() {
+ try {
+ //Loading defaults
+ MDC.put(MDC_SERVICE_NAME, EPSystemProperties.ECOMP_PORTAL_BE);
+ MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
+ MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
+ MDC.put(MDC_SERVICE_INSTANCE_ID, "");
+ MDC.put(MDC_ALERT_SEVERITY, AlarmSeverityEnum.INFORMATIONAL.toString());
+ MDC.put(MDC_INSTANCE_UUID, SystemProperties.getProperty(SystemProperties.INSTANCE_UUID));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+ }
+
+ /*
+ * /
+ *
+ * @PostConstruct // file://${catalina.home}/conf/log4j.properties public
+ * void initLog4j() throws FileNotFoundException { try { URL[] classpathurls
+ * = ((URLClassLoader)
+ * (Thread.currentThread().getContextClassLoader())).getURLs(); for (URL url
+ * : classpathurls) { System.out.println(url.getFile().toString()); }
+ * Log4jConfigurer.initLogging(
+ * "file://${catalina.home}/conf/log4j.properties"); } catch
+ * (FileNotFoundException e) { ((URLClassLoader)
+ * (Thread.currentThread().getContextClassLoader())).getURLs();
+ * Log4jConfigurer.initLogging("classpath:../conf/log4j.properties"); } } /
+ **/
+
+ public DataAccessService dataAccessService() {
+ return super.dataAccessService();
+ }
+
+ public String[] tileDefinitions() {
+ return super.tileDefinitions();
+ }
+
+ public List<String> addTileDefinitions() {
+ List<String> definitions = new ArrayList<String>();
+ definitions.add("/WEB-INF/defs/definitions.xml");
+ return definitions;
+ }
+
+ @Bean
+ public AbstractCacheManager cacheManager() {
+ return new CacheManager();
+ }
+
+ @Bean
+ public SessionTimeoutInterceptor sessionTimeoutInterceptor() {
+ return new SessionTimeoutInterceptor();
+ }
+
+ @Bean
+ public PortalResourceInterceptor portalResourceInterceptor() {
+ return new PortalResourceInterceptor();
+ }
+
+ @Bean
+ public EPLoginService eploginService() {
+ return new EPLoginServiceImpl();
+ }
+
+ @Bean
+ public LoginStrategy loginStrategy(){
+
+ if(SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC"))
+ return new OpenIdConnectLoginStrategy();
+ else
+ return new SimpleLoginStrategy();
+ }
+
+ public FnMenuService fnMenuService(){
+ return new FnMenuServiceImpl();
+ }
+
+
+ @Override
+ public void addInterceptors(InterceptorRegistry registry) {
+ // registry.addInterceptor(new
+ // StaticResourcesInterceptor()).addPathPatterns("/index.htm",
+ // "/applicationsHome", "/widgetsHome", "/admins", "/users",
+ // "/applications", "/widgets");
+ // Excludes login/logout pages and REST endpoints used by other
+ // application servers.
+
+
+ registry.addInterceptor(sessionTimeoutInterceptor()).excludePathPatterns("/oid-login", "/portalApi/healthCheck","/portalApi/healthCheck/",
+ "/portalApi/healthCheckSuspend","/portalApi/healthCheckSuspend/", "/portalApi/healthCheckResume","/portalApi/healthCheckResume/",
+ "/login_external","/login_external.htm*", "login", "/login.htm*", "/auxapi/*", "/context/*",
+ "/api*", "/single_signon.htm", "/single_signon","/dashboard", "/OpenSourceLogin.htm");
+
+ registry.addInterceptor(portalResourceInterceptor());
+
+ }
+
+ /**
+ * Creates and returns a new instance of a {@link SchedulerFactoryBean} and
+ * populates it with triggers.
+ *
+ * @return New instance of {@link SchedulerFactoryBean}
+ * @throws Exception
+ */
+
+ @Bean
+ public EPUebHelper epUebHelper() {
+ return new EPUebHelper();
+ }
+
+ @Bean
+ public HealthMonitor healthMonitor() {
+ return new HealthMonitor();
+ }
+
+ /**
+ * Creates and returns a new instance of a {@link MainUebHandler}.
+ *
+ * @return New instance of {@link MainUebHandler}.
+ */
+ @Bean
+ public MainUebHandler mainUebHandler() {
+ return new MainUebHandler();
+ }
+
+ /**
+ * Creates and returns a new instance of a {@link InitUebHandler}.
+ *
+ * @return New instance of {@link InitUebHandler}.
+ */
+ @Bean
+ public InitUebHandler initUebHandler() {
+ return new InitUebHandler();
+ }
+
+ /**
+ * Creates and returns a new instance of a {@link WidgetNotificationHandler}
+ * .
+ *
+ * @return New instance of {@link WidgetNotificationHandler}.
+ */
+ @Bean
+ public WidgetNotificationHandler widgetNotificationHandler() {
+ return new WidgetNotificationHandler();
+ }
+
+ /**
+ * Creates and returns a new instance of a {@link FunctionalMenuHandler} .
+ *
+ * @return New instance of {@link FunctionalMenuHandler}.
+ */
+ @Bean
+ public FunctionalMenuHandler functionalMenuHandler() {
+ return new FunctionalMenuHandler();
+ }
+
+ /**
+ * Creates and returns a new instance of a {@link SchedulerFactoryBean} and
+ * populates it with triggers.
+ *
+ * @return New instance of {@link SchedulerFactoryBean}
+ * @throws Exception
+ */
+ // APPLICATIONS REQUIRING QUARTZ SHOULD RESTORE ANNOTATION
+ @Bean // ANNOTATION COMMENTED OUT
+ public SchedulerFactoryBean schedulerFactoryBean() throws Exception {
+ SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
+ scheduler.setConfigLocation(appApplicationContext.getResource("WEB-INF/conf/quartz.properties"));
+ scheduler.setDataSource(dataSource());
+ scheduler.setTriggers(schedulerRegistryAdapter.getTriggers());
+ scheduler.setSchedulerName(getScheduleName());
+ return scheduler;
+ }
+
+ protected String getScheduleName() {
+ final String CRON_SITE_NAME = "cron_site_name";
+ String cronSiteVal = "Default";
+ try{
+ cronSiteVal = SystemProperties.getProperty(CRON_SITE_NAME);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ logger.warn(EELFLoggerDelegate.errorLogger, "Cron site name not added in property file, using Default value");
+ }
+
+ String cronSiteName = cronSiteVal != null ? cronSiteVal : "";
+
+ SimpleDateFormat dateFormat = new SimpleDateFormat();
+ dateFormat.applyPattern("YYYYMMdd");
+ String currentDateStr = dateFormat.format(Calendar.getInstance().getTime());
+
+
+ return "Scheduler" + "_" + currentDateStr + "_" + cronSiteName;
+ }
+
+
+ /**
+ * Sets the scheduler registry adapter.
+ *
+ * @param schedulerRegistryAdapter
+ */
+ @Autowired
+ public void setSchedulerRegistryAdapter(final RegistryAdapter schedulerRegistryAdapter) {
+ this.schedulerRegistryAdapter = schedulerRegistryAdapter;
+ }
+
+
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java
new file mode 100644
index 00000000..c1bc7cfa
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java
@@ -0,0 +1,60 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.conf;
+
+import java.util.Arrays;
+
+import org.openecomp.portalsdk.core.conf.AppInitializer;
+
+public class ExternalAppInitializer extends AppInitializer{
+
+
+ @Override
+ protected Class<?>[] getRootConfigClasses() {
+ return super.getRootConfigClasses();
+ }
+
+ @Override
+ protected Class<?>[] getServletConfigClasses() {
+// Class<?>[] configClasses = super.getServletConfigClasses();
+// Class<?>[] additionalConfigClasses = Arrays.copyOf(configClasses, configClasses.length);
+// addConfigClass(additionalConfigClasses, ExternalAppConfig.class);
+// return additionalConfigClasses;
+//
+ return new Class[] {ExternalAppConfig.class};
+ }
+
+ static Class<?>[] addConfigClass(Class<?>[] a, Class<?> e) {
+ a = Arrays.copyOf(a, a.length + 1);
+ a[a.length - 1] = e;
+ return a;
+ }
+
+ /*
+ * URL request will direct to the Spring dispatcher for processing
+ */
+ @Override
+ protected String[] getServletMappings() {
+ return super.getServletMappings();
+ }
+
+}
+
+
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java
new file mode 100644
index 00000000..3eb88f9b
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java
@@ -0,0 +1,38 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.conf;
+
+import org.openecomp.portalsdk.core.conf.HibernateMappingLocatable;
+import org.springframework.context.annotation.Profile;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.core.io.Resource;
+import org.springframework.stereotype.Component;
+
+@Component
+@Profile("src")
+public class HibernateMappingLocations implements HibernateMappingLocatable {
+
+ public Resource[] getMappingLocations() {
+ return new Resource[] { new ClassPathResource("../fusion/orm/Fusion.hbm.xml"),
+ new ClassPathResource("../fusion/orm/EP.hbm.xml"),
+ new ClassPathResource("../fusion/orm/Workflow.hbm.xml") };
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/ECOMPLogoutController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/ECOMPLogoutController.java
new file mode 100644
index 00000000..13242c2e
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/ECOMPLogoutController.java
@@ -0,0 +1,112 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.controller;
+
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+import org.springframework.web.servlet.ModelAndView;
+
+@Controller
+@RequestMapping("/")
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+public class ECOMPLogoutController extends EPUnRestrictedBaseController{
+
+ private EPUser user;
+ private static final String EP_SERVICE = "EPService";
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ECOMPLogoutController.class);
+
+ @EPAuditLog
+ @RequestMapping(value = {"/logout.htm" }, method = RequestMethod.GET)
+ public ModelAndView logOut(HttpServletRequest request,
+ HttpServletResponse response) throws Exception {
+
+ ModelAndView modelView = null;
+
+ chatRoomLogout(request);
+ logger.debug(EELFLoggerDelegate.debugLogger, "ECOMPLogoutController.handleRequestInternal - Logout request received.");
+
+ modelView = new ModelAndView("redirect:login.htm");
+
+ /**
+ if (UserUtils.isClientMobileDevice(request)){
+ modelView.setViewName(modelView.getViewName().concat("?viewType=mobile"));
+ }
+ */
+ String cookieDoamin = EPSystemProperties.getProperty(EPSystemProperties.COOKIE_DOMAIN);
+ Cookie epCookie = new Cookie(EP_SERVICE, "");
+ epCookie.setMaxAge(0);
+ epCookie.setDomain(cookieDoamin);
+ epCookie.setPath("/");
+
+ Cookie appHeaderCookie = new Cookie("show_app_header", "");
+ appHeaderCookie.setMaxAge(0);
+ appHeaderCookie.setDomain(cookieDoamin);
+ appHeaderCookie.setPath("/");
+
+ Cookie appTabCookie = new Cookie("cookieTabs", "");
+ appTabCookie.setMaxAge(0);
+ appTabCookie.setDomain(cookieDoamin);
+ appTabCookie.setPath("/");
+
+ Cookie appVisInvisTabCookie = new Cookie("visInVisCookieTabs", "");
+ appVisInvisTabCookie.setMaxAge(0);
+ appVisInvisTabCookie.setDomain(cookieDoamin);
+ appVisInvisTabCookie.setPath("/");
+
+ response.addCookie(epCookie);
+ response.addCookie(appHeaderCookie);
+ response.addCookie(appTabCookie);
+ response.addCookie(appVisInvisTabCookie);
+ request.getSession().invalidate();
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "ECOMPLogoutController.handleRequestInternal - Successfully processed the logout request.");
+
+ return modelView;
+ }
+
+ @EPMetricsLog
+ public void chatRoomLogout(HttpServletRequest request){
+ request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();
+ setUser(EPUserUtils.getUserSession(request));
+ }
+
+ public EPUser getUser() {
+ return user;
+ }
+
+ public void setUser(EPUser user) {
+ this.user = user;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/EPFusionBaseController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/EPFusionBaseController.java
new file mode 100644
index 00000000..f34fd078
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/EPFusionBaseController.java
@@ -0,0 +1,106 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.controller;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalsdk.core.controller.FusionBaseController;
+import org.openecomp.portalsdk.core.domain.MenuData;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.ModelAttribute;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Controller
+public abstract class EPFusionBaseController extends FusionBaseController {
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPFusionBaseController.class);
+
+
+
+ @Override
+ public boolean isAccessible() {
+ return true;
+ }
+
+ public boolean isRESTfulCall() {
+ return true;
+ }
+
+ @ModelAttribute("menu")
+ public Map<String, Object> messages(HttpServletRequest request) {
+ HttpSession session = null;
+ Map<String, Object> model = new HashMap<String, Object>();
+ session = request.getSession();
+ EPUser user = EPUserUtils.getUserSession(request);
+ if (session != null && user != null) {
+ @SuppressWarnings("unchecked")
+ Set<MenuData> menuResult = (Set<MenuData>) session
+ .getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
+ try {
+ model = setMenu(menuResult);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+ }
+
+ return model;
+ }
+
+ public Map<String, Object> setMenu(Set<MenuData> menuResult) throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ List<List<MenuData>> childItemList = new ArrayList<List<MenuData>>();
+ ;
+ List<MenuData> parentList = new ArrayList<MenuData>();
+ ;
+ Map<String, Object> model = new HashMap<String, Object>();
+ for (MenuData menu : menuResult) {
+ MenuData parentData = new MenuData();
+ parentData.setLabel(menu.getLabel());
+ parentData.setAction(menu.getAction());
+ parentData.setImageSrc(menu.getImageSrc());
+ parentList.add(parentData);
+ List<MenuData> tempList = new ArrayList<MenuData>();
+ for (Object o : menu.getChildMenus()) {
+ MenuData m = (MenuData) o;
+ MenuData data = new MenuData();
+ data.setLabel(m.getLabel());
+ data.setAction(m.getAction());
+ data.setImageSrc(m.getImageSrc());
+ tempList.add(data);
+ }
+ childItemList.add(tempList);
+ }
+ model.put("childItemList", childItemList != null ? mapper.writeValueAsString(childItemList) : "");
+ model.put("parentList", parentList != null ? mapper.writeValueAsString(parentList) : "");
+ return model;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/EPRestrictedBaseController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/EPRestrictedBaseController.java
new file mode 100644
index 00000000..286678cc
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/EPRestrictedBaseController.java
@@ -0,0 +1,52 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.controller;
+
+public class EPRestrictedBaseController extends EPFusionBaseController{
+
+ protected String viewName;
+ private String exceptionView;
+
+ @Override
+ public boolean isAccessible() {
+ return false;
+ }
+
+ @Override
+ public boolean isRESTfulCall(){
+ return false;
+ }
+
+ protected String getViewName() {
+ return viewName;
+ }
+
+ protected void setViewName(String viewName) {
+ this.viewName = viewName;
+ }
+
+ public String getExceptionView() {
+ return (exceptionView == null) ? "runtime_error_handler" : exceptionView;
+ }
+
+ public void setExceptionView(String exceptionView) {
+ this.exceptionView = exceptionView;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/EPRestrictedRESTfulBaseController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/EPRestrictedRESTfulBaseController.java
new file mode 100644
index 00000000..69504a13
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/EPRestrictedRESTfulBaseController.java
@@ -0,0 +1,54 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.controller;
+
+public class EPRestrictedRESTfulBaseController extends EPFusionBaseController{
+
+ protected String viewName;
+ private String exceptionView;
+
+ @Override
+ public boolean isAccessible() {
+ return false;
+ }
+
+ @Override
+ public boolean isRESTfulCall(){
+ return true;
+ }
+
+ protected String getViewName() {
+ return viewName;
+ }
+
+ protected void setViewName(String viewName) {
+ this.viewName = viewName;
+ }
+
+ public String getExceptionView() {
+ return (exceptionView == null) ? "runtime_error_handler" : exceptionView;
+ }
+
+ public void setExceptionView(String exceptionView) {
+ this.exceptionView = exceptionView;
+ }
+
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/EPUnRestrictedBaseController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/EPUnRestrictedBaseController.java
new file mode 100644
index 00000000..7f23ce4c
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/EPUnRestrictedBaseController.java
@@ -0,0 +1,42 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.controller;
+
+public class EPUnRestrictedBaseController extends EPFusionBaseController{
+ protected String viewName;
+
+ @Override
+ public boolean isAccessible() {
+ return true;
+ }
+
+ @Override
+ public boolean isRESTfulCall(){
+ return false;
+ }
+
+ protected String getViewName() {
+ return viewName;
+ }
+
+ protected void setViewName(String viewName) {
+ this.viewName = viewName;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/LoginController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/LoginController.java
new file mode 100644
index 00000000..632f9178
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/LoginController.java
@@ -0,0 +1,356 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.controller;
+
+import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
+
+import java.net.URLDecoder;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.json.JSONObject;
+import org.openecomp.portalapp.command.EPLoginBean;
+import org.openecomp.portalapp.portal.domain.SharedContext;
+import org.openecomp.portalapp.portal.service.EPLoginService;
+import org.openecomp.portalapp.portal.service.SharedContextService;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.service.EPProfileService;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalapp.util.SessionCookieUtil;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.menu.MenuProperties;
+import org.openecomp.portalsdk.core.onboarding.crossapi.PortalTimeoutHandler;
+import org.openecomp.portalsdk.core.util.CipherUtil;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.openecomp.portalsdk.core.web.support.AppUtils;
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.util.StopWatch;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.servlet.ModelAndView;
+import org.springframework.web.util.WebUtils;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Controller
+@RequestMapping("/")
+public class LoginController extends EPUnRestrictedBaseController implements LoginService{
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginController.class);
+
+ public static final String DEFAULT_SUCCESS_VIEW = "applicationsHome";
+ public static final String DEFAULT_FAILURE_VIEW = "login";
+ public static final String ERROR_MESSAGE_KEY = "error";
+ public static final String REDIRECT_URL = "redirectUrl";
+
+ @Autowired
+ EPProfileService service;
+ @Autowired
+ private EPLoginService loginService;
+ @Autowired
+ private SharedContextService sharedContextService;
+
+ String viewName = "login";
+ private String welcomeView;
+
+ public String getWelcomeView() {
+ return welcomeView;
+ }
+
+ public void setWelcomeView(String welcomeView) {
+ this.welcomeView = welcomeView;
+ }
+
+ @RequestMapping(value = {"/login.htm" }, method = RequestMethod.GET)
+ public ModelAndView login(HttpServletRequest request, HttpServletResponse response) {
+ Map<String, Object> model = new HashMap<String, Object>();
+
+ String authentication = SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM);
+
+ String loginPage;
+
+ if (authentication == null || authentication.equals("") || authentication.trim().equals("OIDC"))
+ loginPage = "openIdLogin";
+ else
+ loginPage = getViewName();
+
+ return new ModelAndView(loginPage,"model", model);
+ }
+
+ @SuppressWarnings("rawtypes")
+ @RequestMapping(value = {"/open_source/login" }, method = RequestMethod.POST)
+ public @ResponseBody String loginValidate(HttpServletRequest request, HttpServletResponse response) throws Exception{
+
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+
+ EPLoginBean commandBean = new EPLoginBean();
+ String loginId = root.get("loginId").textValue();
+ String password = root.get("password").textValue();
+ commandBean.setLoginId(loginId);
+ commandBean.setLoginPwd(CipherUtil.encrypt(password));
+ HashMap additionalParamsMap = new HashMap();
+ StringBuilder sbAdditionalInfo = new StringBuilder();
+
+ commandBean = getLoginService().findUser(commandBean, (String)request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY),
+ additionalParamsMap);
+ String fullURL = EPUserUtils.getFullURL(request);
+ if (commandBean.getUser() == null) {
+ String loginErrorMessage = (commandBean.getLoginErrorMessage() != null) ? commandBean.getLoginErrorMessage()
+ : "login.error.external.invalid";
+
+ logger.info(EELFLoggerDelegate.debugLogger, "loginId = " + loginId + " does not exist in the the DB.");
+ logger.info(EELFLoggerDelegate.errorLogger, "loginId = " + loginId + " does not exist in the the DB.");
+ sbAdditionalInfo.append(String.format("But the Login-Id: %s doesn't exist in the Database. Request-URL: %s",
+ loginId, fullURL));
+ return loginErrorMessage;
+ }
+ else {
+ // store the currently logged in user's information in the session
+ EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(),
+ null);
+
+ try{
+ logger.info(EELFLoggerDelegate.debugLogger, "******************* store user info into share context begins");
+ String sessionId = request.getSession().getId();
+ List<SharedContext> existingSC = getSharedContextService().getSharedContexts(sessionId);
+ if(existingSC==null || existingSC.size()==0){
+ getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_FIRST_NAME, commandBean.getUser().getFirstName());
+ getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_LAST_NAME, commandBean.getUser().getLastName());
+ getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_EMAIL, commandBean.getUser().getEmail());
+ getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_ORG_USERID, commandBean.getLoginId());
+ }
+
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ logger.info(EELFLoggerDelegate.errorLogger, "failed the shared context adding process " + e.getMessage());
+ logger.info(EELFLoggerDelegate.debugLogger, "********************** failed the shared context adding process " + e.getMessage());
+ }
+ logger.info(EELFLoggerDelegate.debugLogger, "********************* PresetUp the EP service cookie and intial sessionManagement");
+
+ SessionCookieUtil.preSetUp(request, response);
+ SessionCookieUtil.setUpUserIdCookie(request, response, loginId);
+
+ JSONObject j = new JSONObject("{success: success}");
+
+ return j.toString();
+
+ }
+
+ }
+
+ @RequestMapping(value = {"/processSingleSignOn" }, method = RequestMethod.GET)
+ public ModelAndView processSingelSignOn(HttpServletRequest request, HttpServletResponse response) throws Exception{
+
+ Map<Object, Object> model = new HashMap<Object, Object>();
+ HashMap<Object, Object> additionalParamsMap = new HashMap<Object, Object>();
+ EPLoginBean commandBean = new EPLoginBean();
+ MDC.put(MDC_KEY_REQUEST_ID, EPUserUtils.getRequestId(request));
+ String orgUserId = "";
+ //get userId from cookie
+ orgUserId = SessionCookieUtil.getUserIdFromCookie(request, response);
+ logger.info(EELFLoggerDelegate.debugLogger, "******************** process_singelSignOn process begins");
+ logger.info(EELFLoggerDelegate.debugLogger, "******************* We get the orgUserId " + orgUserId);
+
+ StringBuilder sbAdditionalInfo = new StringBuilder();
+ if ((orgUserId == null || orgUserId.length() == 0)) {
+ model.put(ERROR_MESSAGE_KEY, SystemProperties.MESSAGE_KEY_LOGIN_ERROR_COOKIE_EMPTY);
+ if(request.getParameter("redirectUrl")!=null && request.getParameter("redirectUrl").length()!=0){
+ return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm" + "?redirectUrl=" + request.getParameter("redirectUrl"));
+ }else{
+ return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm");
+ }
+ }
+ else {
+
+ StopWatch stopWatch = new StopWatch("LoginController.Login");
+ stopWatch.start();
+
+ try {
+ logger.info(EELFLoggerDelegate.metricsLogger, "Operation findUser is started to locate " + orgUserId + " in the database.");
+ logger.info(EELFLoggerDelegate.debugLogger, "Operation findUser is started to locate " + orgUserId + " in the database.");
+ commandBean.setLoginId(orgUserId);
+ commandBean.setOrgUserId(orgUserId);
+ commandBean = getLoginService().findUserWithoutPassword(commandBean, (String)request.getAttribute(MenuProperties.MENU_PROPERTIES_FILENAME_KEY), additionalParamsMap);
+
+ stopWatch.stop();
+ MDC.put(EPSystemProperties.MDC_TIMER, stopWatch.getTotalTimeMillis() + "ms");
+ logger.info(EELFLoggerDelegate.metricsLogger, "Operation findUser is completed.");
+ logger.info(EELFLoggerDelegate.debugLogger, "Operation findUser is completed.");
+ } catch(Exception e) {
+ stopWatch.stop();
+ MDC.put(EPSystemProperties.MDC_TIMER, stopWatch.getTotalTimeMillis() + "ms");
+ logger.info(EELFLoggerDelegate.errorLogger, "Exception occurred while performing findUser " + orgUserId + ". Details: " + EcompPortalUtils.getStackTrace(e));
+ logger.info(EELFLoggerDelegate.debugLogger, "Exception occurred while performing findUser " + orgUserId + ". Details: " + EcompPortalUtils.getStackTrace(e));
+ logger.info(EELFLoggerDelegate.metricsLogger, "Operation findUser is failed.");
+ } finally {
+ MDC.remove(EPSystemProperties.MDC_TIMER);
+ }
+
+ sbAdditionalInfo.append("Login attempt is succeeded. ");
+ String fullURL = EPUserUtils.getFullURL(request);
+ if (commandBean.getUser() == null) {
+ logger.info(EELFLoggerDelegate.debugLogger, "loginId = " + orgUserId + " does not exist in the the DB.");
+ logger.info(EELFLoggerDelegate.errorLogger, "loginId = " + orgUserId + " does not exist in the the DB.");
+ logger.info(EELFLoggerDelegate.debugLogger, "loginId = " + orgUserId + " does not exist in the the DB.");
+
+ sbAdditionalInfo.append(String.format("But the Login-Id: %s doesn't exist in the Database. Created a Guest Session. Request-URL: %s",
+ orgUserId, fullURL));
+ if(request.getParameter("redirectUrl")!=null && request.getParameter("redirectUrl").length()!=0){
+ return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm" + "?redirectUrl=" + request.getParameter("redirectUrl"));
+ }else{
+ return new ModelAndView("redirect:" + DEFAULT_FAILURE_VIEW + ".htm");
+ }
+ }
+ else {
+
+ sbAdditionalInfo.append(String.format("Login-Id: %s, Login-Method: %s, Request-URL: %s", orgUserId, "", fullURL));
+ logger.info(EELFLoggerDelegate.debugLogger, "*********************** now set up user session for " + orgUserId);
+
+ EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), "");
+ logger.info(EELFLoggerDelegate.debugLogger, "*********************** now set up user session for " + orgUserId + " finished");
+
+ //Store user's information into share context
+ try{
+ logger.info(EELFLoggerDelegate.debugLogger, "******************* store user info into share context begins");
+
+ String sessionId = request.getSession().getId();
+ List<SharedContext> existingSC = getSharedContextService().getSharedContexts(sessionId);
+ if(existingSC==null || existingSC.size()==0){
+ getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_FIRST_NAME, commandBean.getUser().getFirstName());
+ getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_LAST_NAME, commandBean.getUser().getLastName());
+ getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_EMAIL, commandBean.getUser().getEmail());
+ getSharedContextService().addSharedContext(sessionId, EPSystemProperties.USER_ORG_USERID, commandBean.getLoginId());
+ }
+
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ logger.info(EELFLoggerDelegate.errorLogger, "failed the shared context adding process " + e.getMessage());
+ logger.info(EELFLoggerDelegate.debugLogger, "********************** failed the shared context adding process " + e.getMessage());
+
+ }
+
+ logger.info(EELFLoggerDelegate.debugLogger, "********************* PresetUp the EP service cookie and intial sessionManagement");
+
+ SessionCookieUtil.preSetUp(request, response);
+ SessionCookieUtil.setUpUserIdCookie(request, response, orgUserId);
+ logger.info(EELFLoggerDelegate.debugLogger, "********************* PresetUp the EP service cookie and intial sessionManagement completed");
+ logger.info(EELFLoggerDelegate.errorLogger, commandBean.getUser().getOrgUserId() + " exists in the the system.");
+ logger.info(EELFLoggerDelegate.debugLogger, commandBean.getUser().getOrgUserId() + " exists in the the system.");
+
+ String redirect = "redirectUrl";
+
+ //get redirectUrl from URL parameter
+ if(request.getParameter(redirect)!=null && request.getParameter(redirect).length()!=0){
+ String forwardUrl = URLDecoder.decode(request.getParameter(redirect),"UTF-8");
+ //clean cookie
+ Cookie cookie2 = new Cookie(redirect, "");
+ cookie2.setMaxAge(0);
+ cookie2.setDomain(EPSystemProperties.getProperty(EPSystemProperties.COOKIE_DOMAIN));
+ cookie2.setPath("/");
+ response.addCookie(cookie2);
+ return new ModelAndView("redirect:" + forwardUrl);
+ }
+
+ //first check if redirectUrl exists or not
+ if(WebUtils.getCookie(request, redirect)!=null){
+ String forwardUrl = WebUtils.getCookie(request, redirect).getValue();
+ //clean cookie
+ Cookie cookie2 = new Cookie(redirect, "");
+ cookie2.setMaxAge(0);
+ cookie2.setDomain(EPSystemProperties.getProperty(EPSystemProperties.COOKIE_DOMAIN));
+ cookie2.setPath("/");
+ response.addCookie(cookie2);
+
+ return new ModelAndView("redirect:" + forwardUrl);
+ }
+ }
+ }
+
+ // if user has been authenticated, now take them to the welcome page.
+ //return new ModelAndView("redirect:" + DEFAULT_SUCCESS_VIEW + ".htm");
+ logger.info(EELFLoggerDelegate.debugLogger, "********************** Now return to application home page");
+
+ return new ModelAndView("redirect:" + SystemProperties.getProperty(EPSystemProperties.FE_URL));
+
+ //
+ // Re-enable for BE/FE separation. For 1607, at last minute we decided to go out
+ // without BE/FE separation.
+ //
+ //return new ModelAndView("redirect:" + SystemProperties.getProperty(EPSystemProperties.FE_URL));
+
+ }
+
+ public String getJessionId(HttpServletRequest request){
+
+ return request.getSession().getId();
+ /*
+ Cookie ep = WebUtils.getCookie(request, JSESSIONID);
+ if(ep==null){
+ return request.getSession().getId();
+ }
+ return ep.getValue();
+ */
+ }
+
+
+ protected void initateSessionMgtHandler(HttpServletRequest request) {
+ String jSessionId = getJessionId(request);
+ PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request));
+ }
+
+
+ public String getViewName() {
+ return viewName;
+ }
+ public void setViewName(String viewName) {
+ this.viewName = viewName;
+ }
+ public EPLoginService getLoginService() {
+ return loginService;
+ }
+
+ public void setLoginService(EPLoginService loginService) {
+ this.loginService = loginService;
+ }
+
+ public SharedContextService getSharedContextService() {
+ return sharedContextService;
+ }
+
+ public void setSharedContextService(SharedContextService sharedContextService) {
+ this.sharedContextService = sharedContextService;
+ }
+
+
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/LoginService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/LoginService.java
new file mode 100644
index 00000000..f69916a0
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/LoginService.java
@@ -0,0 +1,36 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.controller;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.servlet.ModelAndView;
+
+public interface LoginService {
+
+ public ModelAndView login(HttpServletRequest request, HttpServletResponse response);
+
+ public @ResponseBody String loginValidate(HttpServletRequest request, HttpServletResponse response) throws Exception;
+
+ public ModelAndView processSingelSignOn(HttpServletRequest request, HttpServletResponse response) throws Exception;
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/OpenCollaborationController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/OpenCollaborationController.java
new file mode 100644
index 00000000..e360cce8
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/OpenCollaborationController.java
@@ -0,0 +1,48 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.controller;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+@Controller
+@RequestMapping("/")
+public class OpenCollaborationController extends RestrictedBaseController{
+
+ @RequestMapping(value = {"/opencollaboration" }, method = RequestMethod.GET)
+ public ModelAndView view(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ EPUser user = (EPUser) EPUserUtils.getUserSession(request);
+
+ model.put("name",(user.getFirstName() + " " + (user.getLastName() != null? user.getLastName().substring(0,1): "" )));
+ return new ModelAndView("collaboration","model", model);
+ }
+
+} \ No newline at end of file
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/PeerBroadcastSocket.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/PeerBroadcastSocket.java
new file mode 100644
index 00000000..92dc9294
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/PeerBroadcastSocket.java
@@ -0,0 +1,106 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.controller;
+
+import java.io.IOException;
+import java.util.Hashtable;
+import java.util.Map;
+
+import javax.websocket.OnClose;
+import javax.websocket.OnMessage;
+import javax.websocket.OnOpen;
+import javax.websocket.Session;
+import javax.websocket.server.ServerEndpoint;
+
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@ServerEndpoint("/opencontact")
+public class PeerBroadcastSocket {
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PeerBroadcastSocket.class);
+
+ public static Map<String, Object> channelMap = new Hashtable<String, Object>();
+ public Map<String, String> sessionMap = new Hashtable<String, String>();
+ ObjectMapper mapper = new ObjectMapper();
+
+ @OnMessage
+ public void message(String message, Session session) {
+ try {
+ // JSONObject jsonObject = new JSONObject(message);
+ @SuppressWarnings("unchecked")
+ Map<String, Object> jsonObject = mapper.readValue(message, Map.class);
+ try {
+ Object from = jsonObject.get("from");
+ if (from != null) {
+ if(channelMap.get(from.toString()) == null) {
+ channelMap.put(from.toString(), session);
+ sessionMap.put(session.getId(), from.toString());
+ }
+ }
+ } catch (Exception je) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to read value" + je.getMessage());
+ }
+
+ try {
+ Object to = jsonObject.get("to");
+ if (to == null)
+ return;
+ Object toSessionObj = channelMap.get(to);
+ if (toSessionObj != null) {
+ Session toSession = null;
+ toSession = (Session) toSessionObj;
+ toSession.getBasicRemote().sendText(message);
+ }
+
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to send text" + ex.getMessage());
+ }
+
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed" + ex.getMessage());
+ }
+
+ }
+
+ @OnOpen
+ public void open(Session session) {
+ logger.info(EELFLoggerDelegate.debugLogger, "Channel opened");
+ }
+
+ @OnClose
+ public void close(Session session) {
+ String channel = sessionMap.get(session.getId());
+ if (channel != null) {
+ Object sessObj = channelMap.get(channel);
+ if (sessObj != null) {
+ try {
+ ((Session) sessObj).close();
+ } catch (IOException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to close" + e.getMessage());
+ }
+ }
+ channelMap.remove(channel);
+ }
+ logger.info(EELFLoggerDelegate.debugLogger, "Channel closed");
+ }
+
+}
+
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/UserProfileController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/UserProfileController.java
new file mode 100644
index 00000000..d7e50ebf
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/UserProfileController.java
@@ -0,0 +1,77 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.controller;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.service.EPProfileService;
+import org.openecomp.portalsdk.core.domain.Profile;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+import com.fasterxml.jackson.core.JsonGenerationException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Controller
+@RequestMapping("/")
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class UserProfileController extends EPRestrictedBaseController {
+
+ @Autowired
+ EPProfileService service;
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserProfileController.class);
+
+ @RequestMapping(value = {"/user_profile" }, method = RequestMethod.GET)
+ public ModelAndView ProfileSearch(HttpServletRequest request) {
+ Map<String, Object> model = new HashMap<String, Object>();
+ ObjectMapper mapper = new ObjectMapper();
+
+ try {
+ List<Profile> profileList = service.findAll();
+ model.put("customerInfo", mapper.writeValueAsString(profileList));
+ } catch (JsonGenerationException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Encountered an JsonGenerationException while performing the ProfileSearch, Details:" + EcompPortalUtils.getStackTrace(e));
+ } catch (JsonMappingException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Encountered an JsonMappingException while performing the ProfileSearch, Details:" + EcompPortalUtils.getStackTrace(e));
+ } catch (IOException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Encountered an IOException while performing the ProfileSearch, Details:" + EcompPortalUtils.getStackTrace(e));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Encountered an Exception while performing the ProfileSearch, Details:" + EcompPortalUtils.getStackTrace(e));
+ }
+
+ return new ModelAndView("user_profile", "model", model);
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/WelcomeController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/WelcomeController.java
new file mode 100644
index 00000000..264f0f59
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/WelcomeController.java
@@ -0,0 +1,89 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.controller;
+
+import java.security.Principal;
+import java.util.Set;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.mitre.openid.connect.client.SubjectIssuerGrantedAuthority;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.servlet.ModelAndView;
+
+@Controller
+@RequestMapping("/")
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class WelcomeController extends EPRestrictedBaseController{
+ String viewName;
+
+ @RequestMapping(value = {"/welcome" }, method = RequestMethod.GET)
+ public ModelAndView welcome(HttpServletRequest request) {
+ return new ModelAndView(getViewName());
+ }
+
+ @RequestMapping(value = "/index.htm", method = RequestMethod.GET)
+ public String getIndexPage(HttpServletRequest request) {
+ return "/index";
+ }
+
+ @RequestMapping(value = {"/applicationsHome", "/dashboard", "/widgetsHome", "/kpidash*", "/admins", "/users", "/portalAdmins", "/applications", "/widgets", "/functionalMenu", "/contactUs", "/getAccess","/appCatalog" }, method = RequestMethod.GET)
+ public String getEcompSinglePage(HttpServletRequest request, HttpServletResponse response) {
+ return "forward:/index.html";
+ }
+
+ protected String getViewName() {
+ return viewName;
+ }
+
+ protected void setViewName(String viewName) {
+ this.viewName = viewName;
+ }
+
+
+ @Resource(name = "namedAdmins")
+ private Set<SubjectIssuerGrantedAuthority> admins;
+
+ @RequestMapping("/user")
+ public String user(Principal p) {
+ return "oid-user";
+ }
+
+ @RequestMapping("/admin")
+ public String admin(Model model, Principal p) {
+
+ model.addAttribute("admins", admins);
+
+ return "oid-admin";
+ }
+ @RequestMapping("/oid-login")
+ public ModelAndView login(Principal p) {
+ return new ModelAndView("openIdLogin");
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/sessionmgt/SessionCommunicationController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/sessionmgt/SessionCommunicationController.java
new file mode 100644
index 00000000..0348fb8d
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/controller/sessionmgt/SessionCommunicationController.java
@@ -0,0 +1,64 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.controller.sessionmgt;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.controller.EPRestrictedRESTfulBaseController;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.service.sessionmgt.ManageService;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+
+@RestController
+@RequestMapping("/auxapi")
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class SessionCommunicationController extends EPRestrictedRESTfulBaseController {
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SessionCommunicationController.class);
+
+ @Autowired
+ ManageService manageService;
+
+ protected boolean isAuxRESTfulCall(){
+ return true;
+ }
+
+ @RequestMapping(value={"/getSessionSlotCheckInterval"}, method = RequestMethod.GET, produces = "application/json")
+ public Integer getSessionSlotCheckInterval(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ return manageService.fetchSessionSlotCheckInterval();
+ }
+
+ @RequestMapping(value={"/extendSessionTimeOuts"}, method = RequestMethod.POST)
+ public Boolean extendSessionTimeOuts(HttpServletRequest request, HttpServletResponse response, @RequestParam String sessionMap) throws Exception {
+ manageService.extendSessionTimeOuts(sessionMap);
+
+ return true;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/controller/KpiDashboardController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/controller/KpiDashboardController.java
new file mode 100644
index 00000000..b3a4f0cb
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/controller/KpiDashboardController.java
@@ -0,0 +1,268 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.kpidash.controller;
+
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.kpidash.model.KpiApiStats;
+import org.openecomp.portalapp.kpidash.model.KpiServiceSupported;
+import org.openecomp.portalapp.kpidash.model.KpiUserStoryStats;
+import org.openecomp.portalapp.kpidash.service.KpiDashboardService;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+//@RequestMapping("/")
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+//public class KpiDashboardController extends EPUnRestrictedBaseController {
+public class KpiDashboardController extends EPRestrictedBaseController {
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(KpiDashboardController.class);
+
+ @Autowired
+ KpiDashboardService service;
+
+ @SuppressWarnings("unchecked")
+ @RequestMapping(value = { "/portalApi/get_user_stories_stats" }, method = RequestMethod.GET, produces = "application/json")
+ public List<KpiUserStoryStats> getUserStories(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<KpiUserStoryStats> userStories = null;
+
+ try {
+ if (user == null) {
+ EcompPortalUtils.setBadPermissions(user, response, "getUserApps");
+ } else {
+ userStories = (List<KpiUserStoryStats>) service.getUserStories();
+ EcompPortalUtils.logAndSerializeObject("/portalApi/get_user_stories_stats", "GET result =", userStories);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing getUserApps operation, Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+ return userStories;
+ }
+
+ @RequestMapping(value = { "/portalApi/save_user_stories_stats" }, method = RequestMethod.GET, produces = "application/json")
+ public void saveUserStories(@RequestBody KpiUserStoryStats kpiUserStoryStats) {
+ service.saveUserStories(kpiUserStoryStats);
+ }
+
+ @SuppressWarnings("unchecked")
+ @RequestMapping(value = { "/portalApi/update_user_stories_stats" }, method = RequestMethod.POST)
+ public List<KpiUserStoryStats> updateUserStories(@RequestBody KpiUserStoryStats kpiUserStoryStats) {
+ service.updateUserStories(kpiUserStoryStats);
+ return (List<KpiUserStoryStats>) service.getUserStories();
+ }
+
+ @SuppressWarnings("unchecked")
+ @RequestMapping(value = { "/portalApi/get_user_api_stats" }, method = RequestMethod.GET, produces = "application/json")
+ public List<KpiApiStats> getUserApis(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<KpiApiStats> apiStats = null;
+
+ try {
+ if (user == null) {
+ EcompPortalUtils.setBadPermissions(user, response, "getUserApps");
+ } else {
+ apiStats = (List<KpiApiStats>) service.getUserApis();
+ EcompPortalUtils.logAndSerializeObject("/portalApi/get_user_api_stats", "GET result =", apiStats);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing getUserApps operation, Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+ return apiStats;
+ }
+
+ @SuppressWarnings("unchecked")
+ @RequestMapping(value = { "/portalApi/get_kpi_service_supported" }, method = RequestMethod.GET, produces = "application/json")
+ public List<KpiServiceSupported> getKpiServiceSupported(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<KpiServiceSupported> kpiServiceSupported = null;
+
+ try {
+ if (user == null) {
+ EcompPortalUtils.setBadPermissions(user, response, "getUserApps");
+ } else {
+ kpiServiceSupported = (List<KpiServiceSupported>) service.getKpiServiceSupported();
+ EcompPortalUtils.logAndSerializeObject("/portalApi/get_kpi_service_supported", "GET result =", kpiServiceSupported);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing getUserApps operation, Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+ return kpiServiceSupported;
+// return (List<KpiServiceSupported>) service.getKpiServiceSupported();
+ }
+
+ @SuppressWarnings("unchecked")
+ @RequestMapping(value = { "/portalApi/update_user_api_stats" }, method = RequestMethod.POST)
+ public List<KpiApiStats> updateUserApis(@RequestBody KpiApiStats kpiApiStats) {
+ service.updateUserApis(kpiApiStats);
+ return (List<KpiApiStats>) service.getUserApis();
+ }
+
+ @SuppressWarnings("unchecked")
+ @RequestMapping(value = { "/portalApi/execute_get_published_delivered" }, method = RequestMethod.GET, produces = "application/json")
+ public List<String> getPublishedDelivered(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<String> publishedDelivered = null;
+
+ try {
+ if (user == null) {
+ EcompPortalUtils.setBadPermissions(user, response, "getUserApps");
+ } else {
+ publishedDelivered = service.executeGetBytesPublishedDelivered();
+ EcompPortalUtils.logAndSerializeObject("/portalApi/execute_get_published_delivered", "GET result =", publishedDelivered);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing getLOCStatsCat operation, Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+ return publishedDelivered;
+ // return service.executeGetBytesPublishedDelivered();
+ }
+
+ @SuppressWarnings("unchecked")
+ @RequestMapping(value = { "/portalApi/execute_get_feed_stats" }, method = RequestMethod.GET, produces = "application/json")
+ public List<Long> getFeedStats(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<Long> feedStats= null;
+
+ try {
+ if (user == null) {
+ EcompPortalUtils.setBadPermissions(user, response, "getUserApps");
+ } else {
+ feedStats = service.executeGetFeedStats();
+ EcompPortalUtils.logAndSerializeObject("/portalApi/execute_get_feed_stats", "GET result =", feedStats);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing getLOCStatsCat operation, Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+ return feedStats;
+// return service.executeGetFeedStats();
+ }
+
+ @SuppressWarnings("unchecked")
+ @RequestMapping(value = { "/portalApi/get_loc_stats_cat" }, method = RequestMethod.GET, produces = "application/json")
+ public List<String> getLOCStatsCat(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<String> LOCStatsCat = null;
+
+ try {
+ if (user == null) {
+ EcompPortalUtils.setBadPermissions(user, response, "getUserApps");
+ } else {
+ LOCStatsCat = service.getLOCStatsCat();
+ EcompPortalUtils.logAndSerializeObject("/portalApi/get_loc_stats_cat", "GET result =", LOCStatsCat);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing getLOCStatsCat operation, Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+ return LOCStatsCat;
+ }
+
+ @SuppressWarnings("unchecked")
+ @RequestMapping(value = { "/portalApi/get_loc_stats" }, method = RequestMethod.GET, produces = "application/json")
+ public List<Long> getLOCStats(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<Long> LOCStats = null;
+
+ try {
+ if (user == null) {
+ EcompPortalUtils.setBadPermissions(user, response, "getUserApps");
+ } else {
+ LOCStats = service.getLOCStats();
+ EcompPortalUtils.logAndSerializeObject("/portalApi/get_loc_stats", "GET result =", LOCStats);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing getLOCStats operation, Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+ return LOCStats;
+ }
+
+ @RequestMapping(value = { "/portalApi/get_geo_map_url" }, method = RequestMethod.GET, produces = "text/plain")
+ public String getGeoMapUrl(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ String geoMapUrl = null;
+
+ try {
+ if (user == null) {
+ EcompPortalUtils.setBadPermissions(user, response, "getUserApps");
+ } else {
+ geoMapUrl = service.getGeoMapUrl();
+ EcompPortalUtils.logAndSerializeObject("/portalApi/get_geo_map_url", "GET result =", geoMapUrl);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing getGeoMapUrl operation, Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+
+ return geoMapUrl;
+ }
+
+ @RequestMapping(value = { "/portalApi/get_rcloud_a_url" }, method = RequestMethod.GET, produces = "text/plain")
+ public String getRCloudAUrl(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ String rcloudUrl = null;
+
+ try {
+ if (user == null) {
+ EcompPortalUtils.setBadPermissions(user, response, "getUserApps");
+ } else {
+ rcloudUrl = service.getRCloudAUrl();
+ EcompPortalUtils.logAndSerializeObject("/portalApi/get_rcloud_a_url", "GET result =", rcloudUrl);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing getGeoMapUrl operation, Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+
+ return rcloudUrl;
+ }
+
+ @RequestMapping(value = { "/portalApi/get_geo_map_api_url" }, method = RequestMethod.GET, produces = "text/plain")
+ public String getGeoMapApiUrl(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ String geoMapApiUrl = null;
+
+ try {
+ if (user == null) {
+ EcompPortalUtils.setBadPermissions(user, response, "getUserApps");
+ } else {
+ geoMapApiUrl = service.getGeoMapApiUrl();
+ EcompPortalUtils.logAndSerializeObject("/portalApi/get_geo_map_api_url", "GET result =", geoMapApiUrl);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing getGeoMapApiUrl operation, Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+
+ return geoMapApiUrl;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/model/KpiApiStats.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/model/KpiApiStats.java
new file mode 100644
index 00000000..fb646ef5
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/model/KpiApiStats.java
@@ -0,0 +1,74 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.kpidash.model;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+import org.openecomp.portalsdk.core.domain.support.DomainVo;
+
+@Entity
+@Table(name = "kpi_api_stats")
+public class KpiApiStats extends DomainVo {
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @Column(name = "api_type")
+ private String apiType;
+
+ @Column(name = "total_api")
+ private Long totalApi;
+
+ @Column(name = "comment")
+ private String comment;
+
+ public KpiApiStats() {
+ }
+
+ public String getApiType() {
+ return apiType;
+ }
+
+ public void setApiType(String apiType) {
+ this.apiType = apiType;
+ }
+
+ public Long getTotalApi() {
+ return totalApi;
+ }
+
+ public void setTotalApi(Long totalApi) {
+ this.totalApi = totalApi;
+ }
+
+ public String getComment() {
+ return comment;
+ }
+
+ public void setComment(String comment) {
+ this.comment = comment;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/model/KpiServiceSupported.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/model/KpiServiceSupported.java
new file mode 100644
index 00000000..1e768390
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/model/KpiServiceSupported.java
@@ -0,0 +1,60 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.kpidash.model;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+import org.openecomp.portalsdk.core.domain.support.DomainVo;
+
+@Entity
+@Table(name = "kpi_service_supported")
+public class KpiServiceSupported extends DomainVo {
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @Column(name = "service_type")
+ private String serviceType;
+
+ @Column(name = "total_count")
+ private Long totalCount;
+
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ public Long getTotalCount() {
+ return totalCount;
+ }
+
+ public void setTotalCount(Long totalCount) {
+ this.totalCount = totalCount;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/model/KpiUserStoryStats.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/model/KpiUserStoryStats.java
new file mode 100644
index 00000000..e4337cca
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/model/KpiUserStoryStats.java
@@ -0,0 +1,107 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.kpidash.model;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+import org.openecomp.portalsdk.core.domain.support.DomainVo;
+
+@Entity
+@Table(name = "kpi_user_story_stats1")
+public class KpiUserStoryStats extends DomainVo {
+ /**
+ *
+ */
+ private static final long serialVersionUID = -1193197465342848502L;
+
+ @Id
+ @Column(name = "release_key")
+ private String releaseKey;
+
+ @Column(name = "delivered")
+ private Long delivered;
+
+ @Column(name = "in_progress")
+ private Long inProgress;
+
+ @Column(name = "IST_progress_readiness")
+ private String ISTProgressReadiness;
+
+ @Column(name = "E2E_progress_readiness")
+ private String E2EProgressReadiness;
+
+ @Column(name = "Key_Highlights")
+ private String KeyHighlights;
+
+ public KpiUserStoryStats() {
+ }
+
+ public String getReleaseKey() {
+ return releaseKey;
+ }
+
+ public void setReleaseKey(String releaseKey) {
+ this.releaseKey = releaseKey;
+ }
+
+ public Long getDelivered() {
+ return delivered;
+ }
+
+ public void setDelivered(Long delivered) {
+ this.delivered = delivered;
+ }
+
+ public Long getInProgress() {
+ return inProgress;
+ }
+
+ public void setInProgress(Long inProgress) {
+ this.inProgress = inProgress;
+ }
+
+ public String getISTProgressReadiness() {
+ return ISTProgressReadiness;
+ }
+
+ public void setISTProgressReadiness(String iSTProgressReadiness) {
+ ISTProgressReadiness = iSTProgressReadiness;
+ }
+
+ public String getE2EProgressReadiness() {
+ return E2EProgressReadiness;
+ }
+
+ public void setE2EProgressReadiness(String e2eProgressReadiness) {
+ E2EProgressReadiness = e2eProgressReadiness;
+ }
+
+ public String getKeyHighlights() {
+ return KeyHighlights;
+ }
+
+ public void setKeyHighlights(String keyHighlights) {
+ KeyHighlights = keyHighlights;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/model/KpidashProperties.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/model/KpidashProperties.java
new file mode 100644
index 00000000..a6f81f4f
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/model/KpidashProperties.java
@@ -0,0 +1,33 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.kpidash.model;
+
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.PropertySource;
+
+@Configuration
+@PropertySource(value = { "${container.classpath:}/WEB-INF/conf/kpidash.properties" })
+
+public class KpidashProperties extends SystemProperties {
+ public static final String GEO_MAP_URL = "url.sectiona";
+ public static final String RCLOUD_A_URL = "url.sectionb";
+ public static final String GEO_API_URL = "url.geomapapiurl";
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/service/KpiDashboardService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/service/KpiDashboardService.java
new file mode 100644
index 00000000..14892f67
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/service/KpiDashboardService.java
@@ -0,0 +1,56 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.kpidash.service;
+
+import java.util.List;
+
+import org.openecomp.portalapp.kpidash.model.KpiApiStats;
+import org.openecomp.portalapp.kpidash.model.KpiUserStoryStats;
+
+@SuppressWarnings("rawtypes")
+public interface KpiDashboardService {
+ public List getUserStories();
+
+ public void saveUserStories(KpiUserStoryStats kpiUserStoryStats);
+
+ public void updateUserStories(KpiUserStoryStats kpiUserStoryStats);
+
+ public List getUserApis();
+
+ public void saveUserApis(KpiApiStats kpiApiStats);
+
+ public void updateUserApis(KpiApiStats kpiApiStats);
+
+ public List getKpiServiceSupported();
+
+ public List executeGetBytesPublishedDelivered();
+
+ public List executeGetFeedStats();
+
+ public List getLOCStatsCat();
+
+ public List getLOCStats();
+
+ public String getGeoMapUrl();
+
+ public String getRCloudAUrl();
+
+ public String getGeoMapApiUrl();
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/service/KpiDashboardServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/service/KpiDashboardServiceImpl.java
new file mode 100644
index 00000000..edbc54af
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/kpidash/service/KpiDashboardServiceImpl.java
@@ -0,0 +1,180 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.kpidash.service;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.openecomp.portalapp.kpidash.model.KpiApiStats;
+import org.openecomp.portalapp.kpidash.model.KpiServiceSupported;
+import org.openecomp.portalapp.kpidash.model.KpiUserStoryStats;
+import org.openecomp.portalapp.kpidash.model.KpidashProperties;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.service.DataAccessService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@SuppressWarnings("rawtypes")
+@Service("kpiDashboardService")
+@Transactional
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class KpiDashboardServiceImpl implements KpiDashboardService {
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(KpiDashboardServiceImpl.class);
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ @Override
+ public void saveUserStories(KpiUserStoryStats kpiUserStoryStats) {
+ dataAccessService.saveDomainObject(kpiUserStoryStats, null);
+ }
+
+ @Override
+ public void updateUserStories(KpiUserStoryStats kpiUserStoryStats) {
+ dataAccessService.saveDomainObject(kpiUserStoryStats, null);
+ }
+
+ @Override
+ public List getUserStories() {
+ return dataAccessService.getList(KpiUserStoryStats.class, null);
+ }
+
+ @Override
+ public List getUserApis() {
+ return dataAccessService.getList(KpiApiStats.class, null);
+ }
+
+ @Override
+ public void saveUserApis(KpiApiStats kpiApiStats) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void updateUserApis(KpiApiStats kpiApiStats) {
+ dataAccessService.saveDomainObject(kpiApiStats, null);
+ }
+
+ @Override
+ public List getKpiServiceSupported() {
+ return dataAccessService.getList(KpiServiceSupported.class, null);
+ }
+
+ @Override
+ public List<String> executeGetBytesPublishedDelivered() {
+ List list = dataAccessService.executeNamedQuery("getBytesPublishedDelivered", null, null);
+ List<String> newStringList = new ArrayList<String>();
+ if (list != null && list.size() > 0) {
+ Object[] retunVals = (Object[]) list.get(0); // current entry in
+ // VSPEntAdmin table
+ newStringList.add((String) retunVals[0]);
+ newStringList.add((String) retunVals[1]);
+ }
+ return newStringList;
+ }
+
+ @Override
+ public List<Long> executeGetFeedStats() {
+ List list = dataAccessService.executeNamedQuery("getDataRouterFeedStats", null, null);
+ List<Long> newLongList = new ArrayList<Long>();
+ if (list != null && list.size() > 0) {
+ Object[] retunVals = (Object[]) list.get(0); // current entry in
+ // VSPEntAdmin table
+ newLongList.add((Long) retunVals[0]);
+ newLongList.add((Long) retunVals[1]);
+ newLongList.add((Long) retunVals[2]);
+ }
+ return newLongList;
+ }
+
+ @Override
+ public List<String> getLOCStatsCat() {
+ List list = dataAccessService.executeNamedQuery("getLOCStatsCat", null, null);
+ List<String> newStringList = new ArrayList<String>();
+ if (list != null && list.size() > 0) {
+ for (int i = 0; i < list.size(); i++) {
+ /* Object[] retunVals = (Object[]) list.get(i); */// current
+ // entry in
+ // VSPEntAdmin
+ // table
+ newStringList.add((String) list.get(i));
+ }
+ }
+ return newStringList;
+ };
+
+ @Override
+ public List<Long> getLOCStats() {
+ List list = dataAccessService.executeNamedQuery("getLOCStats", null, null);
+ List<Long> newLongList = new ArrayList<Long>();
+ if (list != null && list.size() > 0) {
+ for (int i = 0; i < list.size(); i++) {
+ /* Object[] retunVals = (Object[]) list.get(i); */// current
+ // entry in
+ // VSPEntAdmin
+ // table
+ newLongList.add(((BigDecimal) list.get(i)).longValue());
+ }
+ }
+ return newLongList;
+ };
+
+ @Override
+ public String getGeoMapUrl() {
+ String newURL = "";
+ try {
+ newURL = KpidashProperties.getProperty(KpidashProperties.GEO_MAP_URL);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+ return newURL;
+ }
+
+ @Override
+ public String getRCloudAUrl() {
+ String newURL = "";
+ try {
+ newURL = KpidashProperties.getProperty(KpidashProperties.RCLOUD_A_URL);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+ return newURL;
+ }
+
+ @Override
+ public String getGeoMapApiUrl() {
+ String newURL = "";
+ try {
+ newURL = KpidashProperties.getProperty(KpidashProperties.GEO_API_URL);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+ return newURL;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/model/Result.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/model/Result.java
new file mode 100644
index 00000000..009d0fb3
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/model/Result.java
@@ -0,0 +1,37 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.model;
+
+public class Result {
+ private String result;
+
+ public Result(String result) {
+ this.result = result;
+ }
+
+ public String getResult() {
+ return result;
+ }
+
+ public void setResult(String result) {
+ this.result = result;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/AppCatalogController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/AppCatalogController.java
new file mode 100644
index 00000000..684c299f
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/AppCatalogController.java
@@ -0,0 +1,124 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.io.IOException;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.portal.domain.EPApp;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.AdminRolesService;
+import org.openecomp.portalapp.portal.service.EPAppService;
+import org.openecomp.portalapp.portal.service.PersUserAppService;
+import org.openecomp.portalapp.portal.transport.AppCatalogPersonalization;
+import org.openecomp.portalapp.portal.transport.FieldsValidator;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.portal.ecomp.model.AppCatalogItem;
+import org.openecomp.portalapp.util.EPUserUtils;
+
+@RestController
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class AppCatalogController extends EPRestrictedBaseController {
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppCatalogController.class);
+
+ @Autowired
+ AdminRolesService adminRolesService;
+ @Autowired
+ EPAppService appService;
+ @Autowired
+ PersUserAppService persUserAppService;
+
+ /**
+ * RESTful service method to fetch all enabled applications, with details
+ * about which are accessible to the current user, selected by the current
+ * user.
+ *
+ * @return List of items suitable for display
+ */
+ @RequestMapping(value = { "/portalApi/appCatalog" }, method = RequestMethod.GET, produces = "application/json")
+ public List<AppCatalogItem> getAppCatalog(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<AppCatalogItem> appCatalog = null;
+ try {
+ if (user == null) {
+ EcompPortalUtils.setBadPermissions(user, response, "getAppCatalog");
+ } else {
+ if (adminRolesService.isSuperAdmin(user))
+ appCatalog = appService.getAdminAppCatalog(user);
+ else
+ appCatalog = appService.getUserAppCatalog(user);
+ EcompPortalUtils.logAndSerializeObject("/portalApi/getAppCatalog", "GET result =", appCatalog);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed in getAppCatalog", e);
+ response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
+ }
+ return appCatalog;
+ }
+
+ /**
+ * RESTful service to accept a user's action made on the application
+ * catalog.
+ *
+ * @param request
+ * @param selectRequest
+ * JSON with data including application ID
+ * @param response
+ * @return FieldsValidator
+ * @throws IOException
+ */
+ @RequestMapping(value = { "/portalApi/appCatalog" }, method = RequestMethod.PUT, produces = "application/json")
+ public FieldsValidator putAppCatalogSelection(HttpServletRequest request,
+ @RequestBody AppCatalogPersonalization persRequest, HttpServletResponse response) throws IOException {
+ FieldsValidator result = new FieldsValidator();
+ EPApp app = appService.getApp(persRequest.getAppId());
+ EPUser user = EPUserUtils.getUserSession(request);
+ try {
+ if (app == null || user == null) {
+ EcompPortalUtils.setBadPermissions(user, response, "putAppCatalogSelection");
+ } else {
+ persUserAppService.setPersUserAppValue(user, app, persRequest.getSelect(), persRequest.getPending());
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed in putAppCatalogSelection", e);
+ response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
+ }
+ result.httpStatusCode = new Long(HttpServletResponse.SC_OK);
+ return result;
+ }
+
+} \ No newline at end of file
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/AppContactUsController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/AppContactUsController.java
new file mode 100644
index 00000000..308ab2f2
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/AppContactUsController.java
@@ -0,0 +1,224 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.json.JSONObject;
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.portal.ecomp.model.AppCategoryFunctionsItem;
+import org.openecomp.portalapp.portal.ecomp.model.AppContactUsItem;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.AppContactUsService;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/portalApi/contactus")
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class AppContactUsController extends EPRestrictedBaseController {
+
+ static final String FAILURE = "failure";
+
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppContactUsController.class);
+
+ @Autowired
+ private AppContactUsService contactUsService;
+
+ /**
+ * Answers a JSON object with three items from the system.properties file:
+ * user self-help ticket URL, email for feedback, and Portal info link.
+ *
+ * @param request
+ * @return
+ */
+ @RequestMapping(value = "/feedback", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<String> getPortalDetails(HttpServletRequest request) {
+ PortalRestResponse<String> portalRestResponse = null;
+ try {
+ final String ticketUrl = SystemProperties.getProperty(EPSystemProperties.USH_TICKET_URL);
+ final String portalInfoUrl = SystemProperties.getProperty(EPSystemProperties.PORTAL_INFO_URL);
+ final String feedbackEmail = SystemProperties.getProperty(EPSystemProperties.FEEDBACK_EMAIL_ADDRESS);
+ HashMap<String, String> map = new HashMap<String, String>();
+ map.put(EPSystemProperties.USH_TICKET_URL, ticketUrl);
+ map.put(EPSystemProperties.PORTAL_INFO_URL, portalInfoUrl);
+ map.put(EPSystemProperties.FEEDBACK_EMAIL_ADDRESS, feedbackEmail);
+ JSONObject j = new JSONObject(map);
+ String contactUsPortalResponse = j.toString();
+ portalRestResponse = new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
+ contactUsPortalResponse);
+ } catch (Exception e) {
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, FAILURE, e.getMessage());
+ }
+ return portalRestResponse;
+ }
+
+ /**
+ * Answers the contents of the contact-us table, extended with the
+ * application name.
+ *
+ * @param request
+ * @return
+ */
+ @RequestMapping(value = "/list", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<List<AppContactUsItem>> getAppContactUsList(HttpServletRequest request) {
+ PortalRestResponse<List<AppContactUsItem>> portalRestResponse = null;
+ try {
+ List<AppContactUsItem> contents = contactUsService.getAppContactUs();
+ portalRestResponse = new PortalRestResponse<List<AppContactUsItem>>(PortalRestStatusEnum.OK, "success",
+ contents);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getAppContactUsList failed", e);
+ portalRestResponse = new PortalRestResponse<List<AppContactUsItem>>(PortalRestStatusEnum.ERROR,
+ e.getMessage(), null);
+ }
+ return portalRestResponse;
+ }
+
+ /**
+ * Answers a list of objects, one per application, extended with available
+ * data on how to contact that app's organization (possibly none).
+ *
+ * @param request
+ * @return
+ */
+ @RequestMapping(value = "/allapps", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<List<AppContactUsItem>> getAppsAndContacts(HttpServletRequest request) {
+ PortalRestResponse<List<AppContactUsItem>> portalRestResponse = null;
+ try {
+ List<AppContactUsItem> contents = contactUsService.getAppsAndContacts();
+ portalRestResponse = new PortalRestResponse<List<AppContactUsItem>>(PortalRestStatusEnum.OK, "success",
+ contents);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getAllAppsAndContacts failed", e);
+ portalRestResponse = new PortalRestResponse<List<AppContactUsItem>>(PortalRestStatusEnum.ERROR,
+ e.getMessage(), null);
+ }
+ return portalRestResponse;
+ }
+
+ /**
+ * Sorts by category name.
+ */
+ private Comparator<AppCategoryFunctionsItem> appCategoryFunctionsItemComparator = new Comparator<AppCategoryFunctionsItem>() {
+ @Override
+ public int compare(AppCategoryFunctionsItem o1, AppCategoryFunctionsItem o2) {
+ return o1.getCategory().compareTo(o2.getCategory());
+ }
+ };
+
+ /**
+ * Answers a list of objects with category-application-function details. Not
+ * all applications participate in the functional menu.
+ *
+ * @param request
+ * @return
+ */
+ @RequestMapping(value = "/functions", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<List<AppCategoryFunctionsItem>> getAppCategoryFunctions(HttpServletRequest request) {
+ PortalRestResponse<List<AppCategoryFunctionsItem>> portalRestResponse = null;
+ try {
+ List<AppCategoryFunctionsItem> contents = contactUsService.getAppCategoryFunctions();
+ // logger.debug(EELFLoggerDelegate.debugLogger,
+ // "getAppCategoryFunctions: result list size is " +
+ // contents.size());
+ Collections.sort(contents, appCategoryFunctionsItemComparator);
+ portalRestResponse = new PortalRestResponse<List<AppCategoryFunctionsItem>>(PortalRestStatusEnum.OK,
+ "success", contents);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getAppCategoryFunctions failed", e);
+ // TODO build JSON error
+ portalRestResponse = new PortalRestResponse<List<AppCategoryFunctionsItem>>(PortalRestStatusEnum.ERROR,
+ e.getMessage(), null);
+ }
+ return portalRestResponse;
+ }
+
+ /**
+ * Accepts a new application's contact us details.
+ *
+ * @param contactUs
+ * @return
+ */
+ @RequestMapping(value = "/save", method = RequestMethod.POST, produces = "application/json")
+ public PortalRestResponse<String> save(@RequestBody AppContactUsItem contactUs) {
+
+ if (contactUs == null || contactUs.getAppName() == null)
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, FAILURE,
+ "AppName cannot be null or empty");
+
+ String saveAppContactUs = FAILURE;
+ try {
+ saveAppContactUs = contactUsService.saveAppContactUs(contactUs);
+ } catch (Exception e) {
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, saveAppContactUs, e.getMessage());
+ }
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, saveAppContactUs, "");
+ }
+
+ @RequestMapping(value = "/saveAll", method = RequestMethod.POST, produces = "application/json")
+ public PortalRestResponse<String> save(@RequestBody List<AppContactUsItem> contactUsList) {
+
+ String saveAppContactUs = FAILURE;
+ try {
+ saveAppContactUs = contactUsService.saveAppContactUs(contactUsList);
+ } catch (Exception e) {
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, saveAppContactUs, e.getMessage());
+ }
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, saveAppContactUs, "");
+ }
+
+ /**
+ * Deletes the specified application's contact-us details entry from the
+ * table.
+ *
+ * @param id
+ * @return
+ */
+ @RequestMapping(value = "/delete/{appid}", method = RequestMethod.POST, produces = "application/json")
+ public PortalRestResponse<String> delete(@PathVariable("appid") Long id) {
+
+ String saveAppContactUs = FAILURE;
+ try {
+ saveAppContactUs = contactUsService.deleteContactUs(id);
+ } catch (Exception e) {
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, saveAppContactUs, e.getMessage());
+ }
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, saveAppContactUs, "");
+ }
+
+} \ No newline at end of file
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/AppsController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/AppsController.java
new file mode 100644
index 00000000..f460ce4d
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/AppsController.java
@@ -0,0 +1,470 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.json.JSONObject;
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.portal.domain.AdminUserApplications;
+import org.openecomp.portalapp.portal.domain.AppIdAndNameTransportModel;
+import org.openecomp.portalapp.portal.domain.AppsResponse;
+import org.openecomp.portalapp.portal.domain.EPApp;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.domain.EcompApp;
+import org.openecomp.portalapp.portal.domain.UserRole;
+import org.openecomp.portalapp.portal.domain.UserRoles;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.AdminRolesService;
+import org.openecomp.portalapp.portal.service.EPAppService;
+import org.openecomp.portalapp.portal.service.PersUserAppService;
+import org.openecomp.portalapp.portal.service.UserService;
+import org.openecomp.portalapp.portal.transport.FieldsValidator;
+import org.openecomp.portalapp.portal.transport.LocalRole;
+import org.openecomp.portalapp.portal.transport.OnboardingApp;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.util.EPUserUtils;
+
+@RestController
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class AppsController extends EPRestrictedBaseController {
+
+ static final String FAILURE = "failure";
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsController.class);
+
+ @Autowired
+ AdminRolesService adminRolesService;
+ @Autowired
+ EPAppService appService;
+ @Autowired
+ PersUserAppService persUserAppService;
+ @Autowired
+ UserService userService;
+
+ /**
+ * RESTful service method to fetch all Applications available to watch for
+ * current user
+ *
+ * @return
+ */
+ @RequestMapping(value = { "/portalApi/userApps" }, method = RequestMethod.GET, produces = "application/json")
+ public List<EcompApp> getUserApps(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<EcompApp> ecompApps = null;
+
+ try {
+ if (user == null) {
+ EcompPortalUtils.setBadPermissions(user, response, "getUserApps");
+ } else {
+ ecompApps = appService.transformAppsToEcompApps(appService.getUserApps(user));
+ EcompPortalUtils.logAndSerializeObject("/portalApi/userApps", "GET result =", ecompApps);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while performing getUserApps operation, Details: "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+
+ return ecompApps;
+ }
+
+ /**
+ * Create new application's contact us details.
+ *
+ * @param contactUs
+ * @return
+ */
+ @RequestMapping(value = "/portalApi/saveNewUser", method = RequestMethod.POST, produces = "application/json")
+ public PortalRestResponse<String> saveNewUser(HttpServletRequest request,@RequestBody EPUser newUser) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ if (newUser == null)
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, FAILURE,
+ "New User cannot be null or empty");
+
+ if (!(adminRolesService.isSuperAdmin(user) || adminRolesService.isAccountAdmin(user))){
+ if(!user.getLoginId().equalsIgnoreCase(newUser.getLoginId()))
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, FAILURE,
+ "UnAuthorized");
+ }
+
+ String checkDuplicate = request.getParameter("isCheck");
+ String saveNewUser = FAILURE;
+ try {
+ saveNewUser = userService.saveNewUser(newUser,checkDuplicate);
+ } catch (Exception e) {
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, saveNewUser, e.getMessage());
+ }
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, saveNewUser, "");
+ }
+
+ /**
+ * RESTful service method to fetch all applications accessible to the
+ * current user, with personalizations.
+ *
+ * @return
+ */
+ @RequestMapping(value = { "/portalApi/persUserApps" }, method = RequestMethod.GET, produces = "application/json")
+ public List<EcompApp> getPersUserApps(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<EcompApp> ecompApps = null;
+ try {
+ if (user == null) {
+ EcompPortalUtils.setBadPermissions(user, response, "getPersUserApps");
+ } else {
+ List<EPApp> apps = null;
+ if (adminRolesService.isSuperAdmin(user))
+ apps = appService.getPersAdminApps(user);
+ else
+ apps = appService.getPersUserApps(user);
+ ecompApps = appService.transformAppsToEcompApps(apps);
+ EcompPortalUtils.logAndSerializeObject("/portalApi/userPersApps", "GET result =", ecompApps);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed in getPersUserApps", e);
+ response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
+ }
+ return ecompApps;
+ }
+
+ /**
+ * RESTful service method to fetch applications for which the current user
+ * is an Administrator
+ *
+ * @return
+ */
+ @RequestMapping(value = { "/portalApi/adminApps" }, method = RequestMethod.GET, produces = "application/json")
+ public List<AppIdAndNameTransportModel> getAdminApps(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<AppIdAndNameTransportModel> adminApps = null;
+
+ try {
+ if (!adminRolesService.isAccountAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "getAdminApps");
+ } else {
+ adminApps = appService.getAdminApps(user);
+ EcompPortalUtils.logAndSerializeObject("/portalApi/adminApps", "GET result =", adminApps);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while performing getAdminApps operation, Details: "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+
+ return adminApps;
+ }
+
+ /**
+ * RESTful service method to fetch Applications in which the logged in user
+ * is an Administrator
+ *
+ * @return
+ */
+ @RequestMapping(value = {
+ "/portalApi/appsForSuperAdminAndAccountAdmin" }, method = RequestMethod.GET, produces = "application/json")
+ public List<AppIdAndNameTransportModel> getAppsForSuperAdminAndAccountAdmin(HttpServletRequest request,
+ HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<AppIdAndNameTransportModel> adminApps = null;
+
+ try {
+ if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "getAdminApps");
+ } else {
+ adminApps = appService.getAppsForSuperAdminAndAccountAdmin(user);
+ EcompPortalUtils.logAndSerializeObject("/portalApi/appsForSuperAdminAndAccountAdmin", "GET result =",
+ adminApps);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while performing getAppsForSuperAdminAndAccountAdmin operation, Details: "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+
+ return adminApps;
+ }
+
+ /**
+ * RESTful service method to fetch Application Administrators to Super
+ * Administrator user. Attention: Users which have Super Administrator roles
+ * only are not included!
+ *
+ * @return
+ */
+ @RequestMapping(value = { "/portalApi/accountAdmins" }, method = RequestMethod.GET, produces = "application/json")
+ public List<AdminUserApplications> getAppsAdministrators(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<AdminUserApplications> admins = null;
+
+ try {
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "getAppsAdministrators");
+ } else {
+ admins = appService.getAppsAdmins();
+ EcompPortalUtils.logAndSerializeObject("/portalApi/accountAdmins", "GET result =", admins);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while performing getAppsAdministrators operation, Details: "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+
+ return admins;
+ }
+
+ @RequestMapping(value = { "/portalApi/availableApps" }, method = RequestMethod.GET, produces = "application/json")
+ public List<AppsResponse> getApps(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<AppsResponse> apps = null;
+ try {
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "getApps");
+ } else {
+ apps = appService.getAllApps(false);
+ EcompPortalUtils.logAndSerializeObject("/portalApi/availableApps", "GET result =", apps);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while performing getApps operation, Details: "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+
+ return apps;
+ }
+
+ /**
+ * Gets all apps, both active and inactive; i.e., all on-boarded apps,
+ * regardless of enabled status.
+ *
+ * @param request
+ * @param response
+ * @return List of applications
+ */
+ // This API returns
+ @RequestMapping(value = {
+ "/portalApi/allAvailableApps" }, method = RequestMethod.GET, produces = "application/json")
+ public List<AppsResponse> getAllApps(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<AppsResponse> apps = null;
+ try {
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "getApps");
+ } else {
+ apps = appService.getAllApps(true);
+ EcompPortalUtils.logAndSerializeObject("/portalApi/availableApps", "GET result =", apps);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed in getAllApps", e);
+ }
+
+ return apps;
+ }
+
+ @RequestMapping(value = { "/portalApi/appsFullList" }, method = RequestMethod.GET, produces = "application/json")
+ public List<EcompApp> getAppsFullList(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<EcompApp> ecompApps = null;
+ if (user == null) {
+ EcompPortalUtils.setBadPermissions(user, response, "getAppsFullList");
+ } else {
+ ecompApps = appService.getEcompAppAppsFullList();
+ EcompPortalUtils.logAndSerializeObject("/portalApi/appsFullList", "GET result =", ecompApps);
+ }
+
+ return ecompApps;
+ }
+
+ @RequestMapping(value = { "/portalApi/userProfile" }, method = RequestMethod.GET, produces = "application/json")
+ public UserRoles getUserProfile(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ UserRoles userAndRoles = null;
+ try {
+ if (user == null) {
+ EcompPortalUtils.setBadPermissions(user, response, "getUserProfile");
+ } else {
+ // Check database.
+ userAndRoles = appService.getUserProfile(user.getLoginId());
+ // If no roles are defined, treat this user as a guest.
+ if (user.isGuest() || userAndRoles == null) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfile: treating user {} as guest",
+ user.getLoginId());
+ UserRole userRole = new UserRole();
+ userRole.setOrgUserId(user.getLoginId());
+ userRole.setFirstName(user.getFirstName());
+ userRole.setLastName(user.getLastName());
+ userRole.setRoleId(-1L);
+ userRole.setRoleName("Guest");
+ userRole.setUser_Id(-1L);
+ userAndRoles = new UserRoles(userRole);
+ }
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to get user names and roles", e);
+ }
+
+ EcompPortalUtils.logAndSerializeObject("/portalApi/userProfile", "getUserProfile result =", userAndRoles);
+ return userAndRoles;
+ }
+
+ @RequestMapping(value = { "/portalApi/currentUserProfile/{loginId}" }, method = RequestMethod.GET, produces = "application/json")
+ public String getCurrentUserProfile(HttpServletRequest request, @PathVariable("loginId") String loginId) {
+
+ Map<String,String> map = new HashMap<String,String>();
+ EPUser user = null;
+ try {
+ user = (EPUser) userService.getUserByUserId(loginId).get(0);
+ map.put("firstName", user.getFirstName());
+ map.put("lastName", user.getLastName());
+ map.put("email", user.getEmail());
+ map.put("loginId", user.getLoginId());
+ map.put("loginPwd",user.getLoginPwd());
+ map.put("middleInitial",user.getMiddleInitial());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to get user info", e);
+ }
+
+ JSONObject j = new JSONObject(map);;
+ return j.toString();
+ }
+
+ @RequestMapping(value = { "/portalApi/appRoles/{appId}" }, method = {
+ RequestMethod.GET }, produces = "application/json")
+ public List<LocalRole> getAppRoles(HttpServletRequest request, @PathVariable("appId") Long appId) {
+ List<LocalRole> roleList = null;
+ try {
+ roleList = appService.getAppRoles(appId);
+ EcompPortalUtils.logAndSerializeObject("/portalApi/appRoles/" + appId, "GET result =", roleList);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while performing getAppRoles operation, Details: "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+
+ return roleList;
+ }
+
+ @RequestMapping(value = { "/portalApi/onboardingApps" }, method = RequestMethod.GET, produces = "application/json")
+ public List<OnboardingApp> getOnboardingApps(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<OnboardingApp> onboardingApps = null;
+ try {
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "getOnboardingApps");
+ } else {
+ onboardingApps = appService.getOnboardingApps();
+ EcompPortalUtils.logAndSerializeObject("/portalApi/onboardingApps", "GET result =",
+ "onboardingApps of size " + onboardingApps.size());
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while performing getOnboardingApps operation, Details: "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+
+ return onboardingApps;
+ }
+
+ @RequestMapping(value = { "/portalApi/onboardingApps" }, method = RequestMethod.PUT, produces = "application/json")
+ public FieldsValidator putOnboardingApp(HttpServletRequest request,
+ @RequestBody OnboardingApp modifiedOnboardingApp, HttpServletResponse response) {
+ FieldsValidator fieldsValidator = null;
+ try {
+ EPUser user = EPUserUtils.getUserSession(request);
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "putOnboardingApp");
+ } else {
+ modifiedOnboardingApp.normalize();
+ fieldsValidator = appService.modifyOnboardingApp(modifiedOnboardingApp, user);
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while performing putOnboardingApps operation, Details: "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+
+ EcompPortalUtils.logAndSerializeObject("/portalApi/onboardingApps", "PUT result =", response.getStatus());
+ return fieldsValidator;
+ }
+
+ @RequestMapping(value = { "/portalApi/onboardingApps" }, method = RequestMethod.POST, produces = "application/json")
+ public FieldsValidator postOnboardingApp(HttpServletRequest request, @RequestBody OnboardingApp newOnboardingApp,
+ HttpServletResponse response) {
+ FieldsValidator fieldsValidator = null;
+ try {
+ EPUser user = EPUserUtils.getUserSession(request);
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "postOnboardingApps");
+ } else {
+ newOnboardingApp.normalize();
+ fieldsValidator = appService.addOnboardingApp(newOnboardingApp, user);
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Exception occurred while performing postOnboardingApps operation, Details: "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+
+ EcompPortalUtils.logAndSerializeObject("/portalApi/onboardingApps", "POST result =", response.getStatus());
+ return fieldsValidator;
+ }
+
+ @RequestMapping(value = { "/portalApi/onboardingApps/{appId}" }, method = {
+ RequestMethod.DELETE }, produces = "application/json")
+ public FieldsValidator deleteOnboardingApp(HttpServletRequest request, @PathVariable("appId") Long appId,
+ HttpServletResponse response) {
+ FieldsValidator fieldsValidator = null;
+ ;
+ try {
+ EPUser user = EPUserUtils.getUserSession(request);
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "deleteOnboardingApps");
+ } else {
+ fieldsValidator = appService.deleteOnboardingApp(user, appId);
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+
+ EcompPortalUtils.logAndSerializeObject("/portalApi/onboardingApps" + appId, "DELETE result =",
+ response.getStatus());
+ return fieldsValidator;
+ }
+} \ No newline at end of file
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/DashboardController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/DashboardController.java
new file mode 100644
index 00000000..74b85acb
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/DashboardController.java
@@ -0,0 +1,361 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem;
+import org.openecomp.portalapp.portal.service.DashboardSearchService;
+import org.openecomp.portalapp.portal.transport.CommonWidget;
+import org.openecomp.portalapp.portal.transport.CommonWidgetMeta;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalsdk.core.domain.support.CollaborateList;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+
+/**
+ * Controller supplies data to Angular services on the dashboard page.
+ */
+@RestController
+@RequestMapping("/portalApi/dashboard")
+public class DashboardController extends EPRestrictedBaseController {
+
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardController.class);
+
+ @Autowired
+ private DashboardSearchService searchService;
+
+ public enum WidgetCategory {
+ EVENTS, NEWS, IMPORTANTRESOURCES;
+ }
+
+ /**
+ * Validates the resource type parameter.
+ *
+ * @param resourceType
+ * @return True if known in the enum WidgetCategory, else false.
+ */
+ private boolean isValidResourceType(String resourceType) {
+ if (resourceType == null)
+ return false;
+ for (WidgetCategory wc : WidgetCategory.values())
+ if (wc.name().equals(resourceType))
+ return true;
+ return false;
+ }
+
+ /**
+ * Gets all widgets of the specified resource type.
+ *
+ * @param request
+ * @param resourceType
+ * Request parameter.
+ * @return Rest response wrapped around a CommonWidgetMeta object.
+ */
+ @RequestMapping(value = "/widgetData", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<CommonWidgetMeta> getWidgetData(HttpServletRequest request,
+ @RequestParam String resourceType) {
+ if (!isValidResourceType(resourceType))
+ return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.ERROR,
+ "Unexpected resource type " + resourceType, null);
+ return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.OK, "success",
+ searchService.getWidgetData(resourceType));
+ }
+
+ /**
+ * Saves a batch of events, news or resources.
+ *
+ * @param commonWidgetMeta
+ * read from POST body.
+ * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
+ */
+ @RequestMapping(value = "/widgetDataBulk", method = RequestMethod.POST, produces = "application/json")
+ public PortalRestResponse<String> saveWidgetDataBulk(@RequestBody CommonWidgetMeta commonWidgetMeta) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetDataBulk: argument is {}", commonWidgetMeta);
+ if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals(""))
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR",
+ "Category cannot be null or empty");
+ if (!isValidResourceType(commonWidgetMeta.getCategory()))
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+ "Unexpected resource type " + commonWidgetMeta.getCategory(), null);
+ // validate dates
+ for (CommonWidget cw : commonWidgetMeta.getItems()) {
+ String err = validateCommonWidget(cw);
+ if (err != null)
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
+ }
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
+ searchService.saveWidgetDataBulk(commonWidgetMeta));
+ }
+
+ /**
+ * Saves one: event, news or resource
+ *
+ * @param commonWidget
+ * read from POST body
+ * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
+ */
+ @RequestMapping(value = "/widgetData", method = RequestMethod.POST, produces = "application/json")
+ public PortalRestResponse<String> saveWidgetData(@RequestBody CommonWidget commonWidget) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget);
+ if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().equals(""))
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR",
+ "Category cannot be null or empty");
+ String err = validateCommonWidget(commonWidget);
+ if (err != null)
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
+ searchService.saveWidgetData(commonWidget));
+ }
+
+ /**
+ * Used by the validate function
+ */
+ private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
+
+ /**
+ * Validates the content of a common widget.
+ *
+ * @param cw
+ * @return null on success; an error message if validation fails.
+ * @throws Exception
+ */
+ private String validateCommonWidget(CommonWidget cw) {
+ if (!isValidResourceType(cw.getCategory()))
+ return "Invalid category: " + cw.getCategory();
+ if (cw.getTitle() == null || cw.getTitle().trim().length() == 0)
+ return "Title is missing";
+ if (cw.getHref() == null || cw.getHref().trim().length() == 0)
+ return "HREF is missing";
+ if (!cw.getHref().toLowerCase().startsWith("http"))
+ return "HREF does not start with http";
+ if (cw.getSortOrder() == null)
+ return "Sort order is null";
+ if (WidgetCategory.EVENTS.name().equals(cw.getCategory())) {
+ if (cw.getEventDate() == null || cw.getEventDate().trim().length() == 0)
+ return "Date is missing";
+ try {
+ yearMonthDayFormat.setLenient(false);
+ Date date = yearMonthDayFormat.parse(cw.getEventDate());
+ if (date == null)
+ return "Failed to parse date " + cw.getEventDate();
+ } catch (ParseException ex) {
+ return ex.toString();
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Deletes one: event, news or resource
+ *
+ * @param commonWidget
+ * read from POST body
+ * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
+ */
+ @RequestMapping(value = "/deleteData", method = RequestMethod.POST, produces = "application/json")
+ public PortalRestResponse<String> deleteWidgetData(@RequestBody CommonWidget commonWidget) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget);
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
+ searchService.deleteWidgetData(commonWidget));
+ }
+
+ /**
+ * Searches all portal for the input string.
+ *
+ * @param request
+ * @param searchString
+ * @return Rest response wrapped around a Map of String to List of Search
+ * Result Item.
+ */
+ @RequestMapping(value = "/search", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
+ @RequestParam String searchString) {
+
+ if (searchString != null)
+ searchString = searchString.trim();
+ EPUser user = EPUserUtils.getUserSession(request);
+ try {
+ if (user == null) {
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+ "searchPortal: User object is null? - check logs",
+ new HashMap<String, List<SearchResultItem>>());
+ } else if (searchString == null || searchString.length() == 0) {
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null",
+ new HashMap<String, List<SearchResultItem>>());
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
+ user.getLoginId(), searchString);
+ Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
+ searchString);
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
+ new HashMap<String, List<SearchResultItem>>());
+ }
+ }
+
+ /**
+ * Gets all active users.
+ *
+ * @param request
+ * @return Rest response wrapped around a list of String
+ */
+ @RequestMapping(value = "/activeUsers", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<List<Object[]>> getActiveUsers(HttpServletRequest request) {
+ List<Object[]> activeUsers = null;
+ List<Object[]> onlineUsers = new ArrayList<>();
+ try {
+ EPUser user = EPUserUtils.getUserSession(request);
+ String userId = user.getOrgUserId();
+
+ activeUsers = searchService.getRelatedUserVOs(userId);
+ HashSet<String> usersSet = CollaborateList.getInstance().getAllUserName();
+ for (Object[] users : activeUsers) {
+ if (usersSet.contains(users[0])) {
+ onlineUsers.add(users);
+ }
+ }
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", onlineUsers);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
+ }
+ // return onlineUsers;
+ }
+
+ /**
+ * Gets the refresh interval and duration of a cycle of continuous refreshing for the online users side panel, both in milliseconds.
+ *
+ * @param request
+ * @return Rest response wrapped around a number that is the number of milliseconds.
+ */
+ @RequestMapping(value = "/onlineUserUpdateRate", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<Map<String, String>> getOnlineUserUpdateRate(HttpServletRequest request) {
+ PortalRestResponse<String> portalRestResponse = null;
+ try {
+ String updateRate = SystemProperties.getProperty(EPSystemProperties.ONLINE_USER_UPDATE_RATE);
+ String updateDuration = SystemProperties.getProperty(EPSystemProperties.ONLINE_USER_UPDATE_DURATION);
+ Integer rateInMiliSec = Integer.valueOf(updateRate)*1000;
+ Integer durationInMiliSec = Integer.valueOf(updateDuration)*1000;
+ Map<String, String> results = new HashMap<String,String>();
+ results.put("onlineUserUpdateRate", String.valueOf(rateInMiliSec));
+ results.put("onlineUserUpdateDuration", String.valueOf(durationInMiliSec));
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getOnlineUserUpdateRate failed", e);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
+ }
+ }
+
+ /**
+ * Gets the window width threshold for collapsing right menu from system.properties.
+ *
+ * @param request
+ * @return Rest response wrapped around a number that is the window width threshold to collapse right menu.
+ */
+ @RequestMapping(value = "/windowWidthThresholdRightMenu", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForRightMenu(HttpServletRequest request) {
+ PortalRestResponse<String> portalRestResponse = null;
+ try {
+ String windowWidthString = SystemProperties.getProperty(EPSystemProperties.WINDOW_WIDTH_THRESHOLD_RIGHT_MENU);
+ Integer windowWidth = Integer.valueOf(windowWidthString);
+ Map<String, String> results = new HashMap<String,String>();
+ results.put("windowWidth", String.valueOf(windowWidth));
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForRightMenu failed", e);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
+ }
+ }
+
+
+ /**
+ * Gets the window width threshold for collapsing left menu from system.properties.
+ *
+ * @param request
+ * @return Rest response wrapped around a number that is the window width threshold to collapse the left menu.
+ */
+ @RequestMapping(value = "/windowWidthThresholdLeftMenu", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<Map<String, String>> getWindowWidthThresholdForLeftMenu(HttpServletRequest request) {
+ PortalRestResponse<String> portalRestResponse = null;
+ try {
+ String windowWidthString = SystemProperties.getProperty(EPSystemProperties.WINDOW_WIDTH_THRESHOLD_LEFT_MENU);
+ Integer windowWidth = Integer.valueOf(windowWidthString);
+ Map<String, String> results = new HashMap<String,String>();
+ results.put("windowWidth", String.valueOf(windowWidth));
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getWindowWidthThresholdForLeftMenu failed", e);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
+ }
+ }
+
+
+
+ /**
+ * Gets only those users that are 'related' to the currently logged-in user.
+ *
+ * @param request
+ * @return Rest response wrapped around a List of String
+ */
+ @RequestMapping(value = "/relatedUsers", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ try {
+ if (user == null) {
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
+ new ArrayList<>());
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
+ searchService.getRelatedUsers(user.getLoginId()));
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
+ new ArrayList<>());
+ }
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/DashboardSearchResultController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/DashboardSearchResultController.java
new file mode 100644
index 00000000..d6052bcb
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/DashboardSearchResultController.java
@@ -0,0 +1,243 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem;
+import org.openecomp.portalapp.portal.service.DashboardSearchService;
+import org.openecomp.portalapp.portal.transport.CommonWidget;
+import org.openecomp.portalapp.portal.transport.CommonWidgetMeta;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalsdk.core.domain.support.CollaborateList;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/portalApi/search")
+public class DashboardSearchResultController extends EPRestrictedBaseController {
+
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardSearchResultController.class);
+
+ @Autowired
+ private DashboardSearchService searchService;
+
+ /**
+ * Gets all widgets by type: NEW or RESOURCE
+ *
+ * @param request
+ * @param resourceType
+ * Request parameter.
+ * @return Rest response wrapped around a CommonWidgetMeta object.
+ */
+ @RequestMapping(value = "/widgetData", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<CommonWidgetMeta> getWidgetData(HttpServletRequest request,
+ @RequestParam String resourceType) {
+ return new PortalRestResponse<CommonWidgetMeta>(PortalRestStatusEnum.OK, "success",
+ searchService.getWidgetData(resourceType));
+ }
+
+ /**
+ * Saves all: news and resources
+ *
+ * @param commonWidgetMeta
+ * read from POST body.
+ * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
+ */
+ @RequestMapping(value = "/widgetDataBulk", method = RequestMethod.POST, produces = "application/json")
+ public PortalRestResponse<String> saveWidgetDataBulk(@RequestBody CommonWidgetMeta commonWidgetMeta) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetDataBulk: argument is {}", commonWidgetMeta);
+ if (commonWidgetMeta.getCategory() == null || commonWidgetMeta.getCategory().trim().equals(""))
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR",
+ "Category cannot be null or empty");
+ // validate dates
+ for (CommonWidget cw : commonWidgetMeta.getItems()) {
+ String err = validateCommonWidget(cw);
+ if (err != null)
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
+ }
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
+ searchService.saveWidgetDataBulk(commonWidgetMeta));
+ }
+
+ /**
+ * Saves one: news or resource
+ *
+ * @param commonWidget
+ * read from POST body
+ * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
+ */
+ @RequestMapping(value = "/widgetData", method = RequestMethod.POST, produces = "application/json")
+ public PortalRestResponse<String> saveWidgetData(@RequestBody CommonWidget commonWidget) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget);
+ if (commonWidget.getCategory() == null || commonWidget.getCategory().trim().equals(""))
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "ERROR",
+ "Cateogry cannot be null or empty");
+ String err = validateCommonWidget(commonWidget);
+ if (err != null)
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, err, null);
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
+ searchService.saveWidgetData(commonWidget));
+ }
+
+ /**
+ * Used by the validate function
+ */
+ private final SimpleDateFormat yearMonthDayFormat = new SimpleDateFormat("yyyy-MM-dd");
+
+ /**
+ * Validates the content of a common widget.
+ *
+ * @param cw
+ * @return null on success; an error message if validation fails.
+ * @throws Exception
+ */
+ private String validateCommonWidget(CommonWidget cw) {
+ try {
+ if (cw.getEventDate() != null && cw.getEventDate().trim().length() > 0)
+ yearMonthDayFormat.parse(cw.getEventDate());
+ } catch (ParseException ex) {
+ return ex.toString();
+ }
+ return null;
+ }
+
+ /**
+ * Deletes one: news or resource
+ *
+ * @param commonWidget
+ * read from POST body
+ * @return Rest response wrapped around a String; e.g., "success" or "ERROR"
+ */
+ @RequestMapping(value = "/deleteData", method = RequestMethod.POST, produces = "application/json")
+ public PortalRestResponse<String> deleteWidgetData(@RequestBody CommonWidget commonWidget) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "deleteWidgetData: argument is {}", commonWidget);
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "success",
+ searchService.deleteWidgetData(commonWidget));
+ }
+
+ /**
+ * Searches all portal for the input string.
+ *
+ * @param request
+ * @param searchString
+ * @return Rest response wrapped around a Map of String to List of Search
+ * Result Item.
+ */
+ @RequestMapping(value = "/allPortal", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<Map<String, List<SearchResultItem>>> searchPortal(HttpServletRequest request,
+ @RequestParam String searchString) {
+
+ EPUser user = EPUserUtils.getUserSession(request);
+ try {
+ if (user == null) {
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+ "searchPortal: User object is null? - check logs",
+ new HashMap<String, List<SearchResultItem>>());
+ } else if (searchString == null || searchString.trim().length() == 0) {
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "searchPortal: String string is null",
+ new HashMap<String, List<SearchResultItem>>());
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "searchPortal: user {}, search string '{}'",
+ user.getLoginId(), searchString);
+ Map<String, List<SearchResultItem>> results = searchService.searchResults(user.getLoginId(),
+ searchString);
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", results);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "searchPortal failed", e);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
+ new HashMap<String, List<SearchResultItem>>());
+ }
+ }
+
+ /**
+ * Gets all active users.
+ *
+ * TODO: should only the superuser be allowed to use this API?
+ *
+ * @param request
+ * @return Rest response wrapped around a list of String
+ */
+ @RequestMapping(value = "/activeUsers", method = RequestMethod.GET, produces = "application/json")
+ public List<String> getActiveUsers(HttpServletRequest request) {
+ List<String> activeUsers = null;
+ List<String> onlineUsers = new ArrayList<>();
+ try {
+ EPUser user = EPUserUtils.getUserSession(request);
+ String userId = user.getOrgUserId();
+
+ activeUsers = searchService.getRelatedUsers(userId);
+ HashSet<String> usersSet = CollaborateList.getInstance().getAllUserName();
+ for (String users : activeUsers) {
+ if (usersSet.contains(users)) {
+ onlineUsers.add(users);
+ }
+ }
+
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getActiveUsers failed", e);
+ }
+ return onlineUsers;
+ }
+
+ /**
+ * Gets only those users that are 'related' to the currently logged-in user.
+ *
+ * @param request
+ * @return Rest response wrapped around a List of String
+ */
+ @RequestMapping(value = "/relatedUsers", method = RequestMethod.GET, produces = "application/json")
+ public PortalRestResponse<List<String>> activeUsers(HttpServletRequest request) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ try {
+ if (user == null) {
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "User object is null? - check logs",
+ new ArrayList<>());
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "activeUsers: searching for user {}", user.getLoginId());
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success",
+ searchService.getRelatedUsers(user.getLoginId()));
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "activeUsers failed", e);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage() + " - check logs.",
+ new ArrayList<>());
+ }
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java
new file mode 100644
index 00000000..08804a07
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulController.java
@@ -0,0 +1,128 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.io.IOException;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.controller.EPRestrictedRESTfulBaseController;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.AdminRolesService;
+import org.openecomp.portalapp.portal.service.EPLoginService;
+import org.openecomp.portalapp.portal.service.FunctionalMenuService;
+import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson;
+import org.openecomp.portalapp.portal.transport.FieldsValidator;
+import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/auxapi")
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class ExternalAppsRestfulController extends EPRestrictedRESTfulBaseController {
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppsRestfulController.class);
+
+ @Autowired
+ FunctionalMenuService functionalMenuService;
+
+ @Autowired
+ EPLoginService epLoginService;
+
+ @Autowired
+ AdminRolesService adminRolesService;
+
+ @RequestMapping(value={"/getFavorites"}, method = RequestMethod.GET,produces = "application/json")
+ public List<FavoritesFunctionalMenuItemJson> getFavoritesForUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ String loginId = "";
+ String userAgent = "";
+ List<FavoritesFunctionalMenuItemJson> favorites = null;
+
+ loginId = request.getHeader(EPSystemProperties.MDC_LOGIN_ID);
+ userAgent = MDC.get(EPSystemProperties.PARTNER_NAME);
+
+ EPUser epUser = epLoginService.findUserWithoutPwd(loginId);
+ logger.info(EELFLoggerDelegate.errorLogger, "getFavorites request was received from " + userAgent + " for the user " + loginId + ".");
+ if (epUser==null || epUser.getId()==null) {
+ logger.error(EELFLoggerDelegate.errorLogger, "No User record found for the LoginId '" + loginId + "' in the database.");
+ throw new Exception("Received null for Login-Id.");
+ } else {
+ favorites = functionalMenuService.getFavoriteItems(epUser.getId());
+ FieldsValidator fieldsValidator = new FieldsValidator();
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+
+ EcompPortalUtils.logAndSerializeObject("/auxapi/getFavorites", "result = ", favorites);
+ }
+
+ return favorites;
+ }
+
+ @RequestMapping(value={"/functionalMenuItemsForUser"}, method = RequestMethod.GET,produces = "application/json")
+ public List<FunctionalMenuItem> getFunctionalMenuItemsForUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ String loginId = "";
+ String userAgent = "";
+ List<FunctionalMenuItem> fnMenuItems = null;
+
+ loginId = request.getHeader("LoginId");
+ userAgent = MDC.get(EPSystemProperties.PARTNER_NAME);
+
+ EPUser epUser = epLoginService.findUserWithoutPwd(loginId);
+ logger.info(EELFLoggerDelegate.errorLogger, "getFunctionalMenuItemsForUser request was received from " + userAgent + " for the user " + loginId + ".");
+ if (epUser==null || epUser.getId()==null) {
+ logger.error(EELFLoggerDelegate.errorLogger, "No User record found for the LoginId '" + loginId + "' in the database.");
+ throw new Exception("Received null for Login-Id.");
+ } else if (adminRolesService.isSuperAdmin(epUser)) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "FunctionalMenuHandler: SuperUser, about to call getFunctionalMenuItems()");
+ fnMenuItems = functionalMenuService.getFunctionalMenuItems();
+ }
+ else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "getMenuItemsForAuthUser: about to call getFunctionalMenuItemsForUser()");
+ fnMenuItems = functionalMenuService.getFunctionalMenuItemsForUser(epUser.getOrgUserId());
+ }
+
+ FieldsValidator fieldsValidator = new FieldsValidator();
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+
+ EcompPortalUtils.logAndSerializeObject("/auxapi/functionalMenuItemsForUser", "result = ", fnMenuItems);
+
+ return fnMenuItems;
+ }
+
+ @ExceptionHandler(Exception.class)
+ protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException {
+ logger.warn(EELFLoggerDelegate.errorLogger, "Handling bad request", e);
+ response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/FunctionalMenuController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/FunctionalMenuController.java
new file mode 100644
index 00000000..6c69fde9
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/FunctionalMenuController.java
@@ -0,0 +1,436 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.cxf.transport.http.HTTPException;
+import org.json.JSONObject;
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.domain.SharedContext;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.AdminRolesService;
+import org.openecomp.portalapp.portal.service.FunctionalMenuService;
+import org.openecomp.portalapp.portal.service.SearchService;
+import org.openecomp.portalapp.portal.service.SharedContextService;
+import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItem;
+import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson;
+import org.openecomp.portalapp.portal.transport.FieldsValidator;
+import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
+import org.openecomp.portalapp.portal.transport.FunctionalMenuItemJson;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.service.UserProfileService;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+
+@RestController
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class FunctionalMenuController extends EPRestrictedBaseController {
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FunctionalMenuController.class);
+
+ @Autowired
+ AdminRolesService adminRolesService;
+ @Autowired
+ FunctionalMenuService functionalMenuService;
+ @Autowired
+ SharedContextService sharedContextService;
+
+ @Autowired
+ UserProfileService service;
+
+ @Autowired
+ SearchService searchService;
+
+ /**
+ * RESTful service method to fetch all the FunctionalMenuItems.
+ *
+ * @return
+ */
+ @RequestMapping(value = { "/portalApi/functionalMenu" }, method = RequestMethod.GET, produces = "application/json")
+ public List<FunctionalMenuItem> getMenuItems(HttpServletRequest request, HttpServletResponse response) {
+ // TODO: should only the superuser be allowed to use this API?
+ List<FunctionalMenuItem> menuItems = null;
+ try{
+ menuItems = functionalMenuService.getFunctionalMenuItems();
+ functionalMenuService.assignHelpURLs(menuItems);
+ EcompPortalUtils.logAndSerializeObject("/portalApi/functionalMenu", "result =", menuItems);
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while calling functionalMenu. Details: " +
+ EcompPortalUtils.getStackTrace(e));
+ }
+ return menuItems;
+ }
+
+
+ /**
+ * RESTful service method to fetch all the FunctionalMenuItems, both active and inactive,
+ * for the EditFunctionalMenu feature.
+ * Can only be accessed by the portal admin.
+ *
+ * @return
+ */
+ @RequestMapping(value = { "/portalApi/functionalMenuForEditing" }, method = RequestMethod.GET, produces = "application/json")
+ public List<FunctionalMenuItem> getMenuItemsForEditing(HttpServletRequest request, HttpServletResponse response) {
+ // TODO: should only the superuser be allowed to use this API?
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<FunctionalMenuItem> menuItems = null;
+ try{
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "getFunctionalMenuItemDetails");
+ } else {
+ menuItems = functionalMenuService.getFunctionalMenuItems(true);
+ }
+ EcompPortalUtils.logAndSerializeObject("/portalApi/functionalMenuForEditing", "result =", menuItems);
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while calling functionalMenuForEditing. Details: " +
+ EcompPortalUtils.getStackTrace(e));
+ }
+ return menuItems;
+ }
+
+ /**
+ * RESTful service method to fetch all FunctionalMenuItems associated with an application.
+ *
+ * @return
+ */
+ @RequestMapping(value = { "/portalApi/functionalMenuForApp/{appId}" }, method = RequestMethod.GET, produces = "application/json")
+ public List<FunctionalMenuItem> getMenuItemsForApp(HttpServletRequest request, @PathVariable("appId") Integer appId) throws HTTPException {
+ // TODO: should only the superuser be allowed to use this API?
+ List<FunctionalMenuItem> menuItems = null;
+ try{
+ menuItems = functionalMenuService.getFunctionalMenuItemsForApp(appId);
+ functionalMenuService.assignHelpURLs(menuItems);
+ EcompPortalUtils.logAndSerializeObject("/portalApi/functionalMenuForApp/"+appId, "result =", menuItems);
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while calling functionalMenuForApp. Details: " +
+ EcompPortalUtils.getStackTrace(e));
+ }
+ return menuItems;
+ }
+
+ /**
+ * RESTful service method to fetch all FunctionalMenuItems associated with the applications
+ * and roles that a user has access to.
+ *
+ * @return
+ */
+
+ @RequestMapping(value = { "/portalApi/functionalMenuForUser/{userId}" }, method = RequestMethod.GET, produces = "application/json")
+ public List<FunctionalMenuItem> getMenuItemsForUser(HttpServletRequest request, @PathVariable("userId") String userId) throws HTTPException {
+ // TODO: should only the superuser be allowed to use this API?
+ List<FunctionalMenuItem> menuItems = null;
+ try{
+ menuItems = functionalMenuService.getFunctionalMenuItemsForUser(userId);
+ functionalMenuService.assignHelpURLs(menuItems);
+ EcompPortalUtils.logAndSerializeObject("/portalApi/functionalMenuForUser/"+userId, "result =", menuItems);
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while calling functionalMenuForUser. Details: " +
+ EcompPortalUtils.getStackTrace(e));
+ }
+
+ return menuItems;
+ }
+
+ /**
+ * RESTful service method to fetch all FunctionalMenuItems associated with the applications
+ * and roles that the authenticated user has access to.
+ *
+ * @return
+ */
+
+ @RequestMapping(value = { "/portalApi/functionalMenuForAuthUser" }, method = RequestMethod.GET, produces = "application/json")
+ public List<FunctionalMenuItem> getMenuItemsForAuthUser(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<FunctionalMenuItem> menuItems = null;
+ try{
+ if (user == null) {
+ EcompPortalUtils.setBadPermissions(user, response, "getMenuItemsForAuthUser");
+ } else if (adminRolesService.isSuperAdmin(user)) {
+ menuItems = functionalMenuService.getFunctionalMenuItems();
+ } else {
+ // calculate the menu items
+ String orgUserId = user.getOrgUserId();
+ menuItems = functionalMenuService.getFunctionalMenuItemsForUser(orgUserId);
+ EcompPortalUtils.logAndSerializeObject("/portalApi/functionalMenuForUser/"+orgUserId, "result =", menuItems);
+ }
+ functionalMenuService.assignHelpURLs(menuItems);
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while calling getMenuItemsForAuthUser. Details: " +
+ EcompPortalUtils.getStackTrace(e));
+ }
+ return menuItems;
+ }
+
+ /**
+ * RESTful service method to fetch the details for a functional menu item.
+ * Requirement: you must be the Ecomp portal super admin user.
+ *
+ * @return
+ */
+
+ @RequestMapping(value = { "/portalApi/functionalMenuItemDetails/{menuId}" }, method = RequestMethod.GET, produces = "application/json")
+ public FunctionalMenuItem getFunctionalMenuItemDetails(HttpServletRequest request, @PathVariable("menuId") Integer menuId, HttpServletResponse response) throws HTTPException {
+ // TODO: return FunctionalMenuItemJson
+ // TODO: modify FunctionalMenuItem to not include the transient fields
+ FunctionalMenuItem menuItem = null;
+ try{
+ EPUser user = EPUserUtils.getUserSession(request);
+
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "getFunctionalMenuItemDetails");
+ } else {
+ menuItem = functionalMenuService.getFunctionalMenuItemDetails(menuId);
+ EcompPortalUtils.logAndSerializeObject("/portalApi/functionalMenuItemDetails/"+menuId, "result =", menuItem);
+ }
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while calling functionalMenuItemDetails. Details: " +
+ EcompPortalUtils.getStackTrace(e));
+ }
+
+ return menuItem;
+ }
+
+ /**
+ * RESTful service method to create a new menu item.
+ * Requirement: you must be the Ecomp portal super admin user.
+ */
+
+ @RequestMapping(value={"/portalApi/functionalMenuItem"}, method = RequestMethod.POST)
+ public FieldsValidator createFunctionalMenuItem(HttpServletRequest request, @RequestBody FunctionalMenuItemJson menuItemJson, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ FieldsValidator fieldsValidator = null;
+ if (!adminRolesService.isSuperAdmin(user)) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "FunctionalMenuController.createFunctionalMenuItem bad permissions");
+ EcompPortalUtils.setBadPermissions(user, response, "createFunctionalMenuItem");
+ } else {
+ fieldsValidator = functionalMenuService.createFunctionalMenuItem(menuItemJson);
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ EcompPortalUtils.logAndSerializeObject("/portalApi/functionalMenuItem", "POST result =", response.getStatus());
+ }
+
+ return fieldsValidator;
+ }
+
+ /**
+ * RESTful service method to update an existing menu item
+ * Requirement: you must be the Ecomp portal super admin user.
+ */
+
+ @RequestMapping(value={"/portalApi/functionalMenuItem"}, method = RequestMethod.PUT)
+ public FieldsValidator editFunctionalMenuItem(HttpServletRequest request, @RequestBody FunctionalMenuItemJson menuItemJson, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ FieldsValidator fieldsValidator = null;
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "editFunctionalMenuItem");
+ } else {
+ fieldsValidator = functionalMenuService.editFunctionalMenuItem(menuItemJson);
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ EcompPortalUtils.logAndSerializeObject("/portalApi/functionalMenuItem", "PUT result =", response.getStatus());
+ }
+
+ return fieldsValidator;
+ }
+
+ @RequestMapping(value={"/portalApi/functionalMenuItem/{menuId}"}, method = RequestMethod.DELETE)
+ public FieldsValidator deleteFunctionalMenuItem(HttpServletRequest request, @PathVariable("menuId") Long menuId, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ FieldsValidator fieldsValidator = null;
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "deleteFunctionalMenuItem");
+ } else {
+ fieldsValidator = functionalMenuService.deleteFunctionalMenuItem(menuId);
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ EcompPortalUtils.logAndSerializeObject("/portalApi/functionalMenuItem", "DELETE result =", response.getStatus());
+ }
+
+ return fieldsValidator;
+ }
+
+ @RequestMapping(value = {"/portalApi/regenerateFunctionalMenuAncestors" }, method = RequestMethod.GET)
+ public FieldsValidator regenerateAncestorTable(HttpServletRequest request, HttpServletResponse response) {
+ // TODO: should only the superuser be allowed to use this API?
+ EPUser user = EPUserUtils.getUserSession(request);
+ FieldsValidator fieldsValidator = null;
+
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "deleteFunctionalMenuItem");
+ } else {
+ fieldsValidator = functionalMenuService.regenerateAncestorTable();
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ EcompPortalUtils.logAndSerializeObject("/portalApi/regenerateAncestorTable", "GET result =", response.getStatus());
+ }
+
+ return fieldsValidator;
+ }
+
+
+ @RequestMapping(value={"/portalApi/setFavoriteItem"}, method = RequestMethod.POST)
+ public FieldsValidator addFavoriteItem(HttpServletRequest request, @RequestBody FavoritesFunctionalMenuItem menuItemJson, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ FieldsValidator fieldsValidator = null;
+ menuItemJson.userId = user.getId();
+ fieldsValidator = functionalMenuService.setFavoriteItem(menuItemJson);
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ EcompPortalUtils.logAndSerializeObject("/portalApi/setFavoriteItem", "Post result =", response.getStatus());
+
+ return fieldsValidator;
+ }
+
+
+ @RequestMapping(value={"/portalApi/getFavoriteItems"}, method = RequestMethod.GET,produces = "application/json")
+ public List<FavoritesFunctionalMenuItemJson> getFavoritesForUser(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<FavoritesFunctionalMenuItemJson> favorites = functionalMenuService.getFavoriteItems(user.getId());
+ FieldsValidator fieldsValidator = new FieldsValidator();
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ EcompPortalUtils.logAndSerializeObject("/portalApi/getFavoriteItems", "GET result =", response.getStatus());
+
+ return favorites;
+ }
+
+ @RequestMapping(value={"/portalApi/removeFavoriteItem/{menuId}"}, method = RequestMethod.DELETE)
+ public FieldsValidator deleteFavoriteItem(HttpServletRequest request, @PathVariable("menuId") Long menuId, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ FieldsValidator fieldsValidator = null;
+ Long userId = user.getId();
+ fieldsValidator = functionalMenuService.removeFavoriteItem(userId,menuId);
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ EcompPortalUtils.logAndSerializeObject("/deleteFavoriteItem", "DELETE result =", response.getStatus());
+
+ return fieldsValidator;
+ }
+
+ @RequestMapping(value = {"/portalApi/functionalMenuStaticInfo" }, method = RequestMethod.GET,produces = "application/json")
+ public String functionalMenuStaticInfo(HttpServletRequest request, HttpServletResponse response) {
+
+ /*Getting first name, last name, and email from session*/
+ logger.debug(EELFLoggerDelegate.debugLogger, "getting functionalMenuStaticInfo values from session");
+ Map<String,String> map = new HashMap<String,String>();
+ String sessionId = request.getSession().getId();
+ SharedContext userIdSC = null , firstNameSC = null, lastNameSC = null, emailSC = null;
+ String userIdStr= null, firstNameStr= null, lastNameStr = null, emailStr = null;
+ EPUser user = EPUserUtils.getUserSession(request);
+ String contact_us_link = null;
+ String last_login = null;
+ try{
+ contact_us_link = SystemProperties.getProperty(EPSystemProperties.CONTACT_US_URL);
+ SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
+ Date lastLoginDate = user.getLastLoginDate();
+ last_login =sdf.format(lastLoginDate);// sdf.parse(lastLoginDate.);
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "CONTACT_US_URL is missing in property file! Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+
+ try{
+ if (user!=null) {
+ firstNameStr = user.getFirstName();
+ lastNameStr = user.getLastName();
+ userIdStr = user.getOrgUserId();
+ emailStr = user.getEmail();
+ /*if(emailStr==null || emailStr.equals("")){
+ EPUser userResult = searchService.searchUsersByUserId(user); //.searchUserByUserId(userIdStr);
+ emailStr = userResult.getEmail();
+ } */
+ } else {
+ logger.warn(EELFLoggerDelegate.errorLogger, "Unable to locate the user information in the session. LoginId: " + MDC.get(EPSystemProperties.MDC_LOGIN_ID));
+ }
+
+ /*If failed getting from session, then get the values from Shared Context*/
+ if(firstNameStr==null)
+ firstNameSC = sharedContextService.getSharedContext(sessionId,EPSystemProperties.USER_FIRST_NAME);
+ if(lastNameStr==null)
+ lastNameSC = sharedContextService.getSharedContext(sessionId,EPSystemProperties.USER_LAST_NAME);
+ if(emailStr==null)
+ emailSC = sharedContextService.getSharedContext(sessionId,EPSystemProperties.USER_EMAIL);
+ if(userIdStr==null)
+ userIdSC = sharedContextService.getSharedContext(sessionId,EPSystemProperties.USER_ORG_USERID);
+
+ /*Getting Contact Us link from properties file*/
+
+ map.put("firstName", firstNameStr!=null?firstNameStr:(firstNameSC!=null?firstNameSC.getCvalue():null));
+ map.put("lastName", lastNameStr!=null?lastNameStr:(lastNameSC!=null?lastNameSC.getCvalue():null));
+ map.put("email", emailStr!=null?emailStr:(emailSC!=null?emailSC.getCvalue():null));
+ map.put("userId", userIdStr!=null?userIdStr:(userIdSC!=null?userIdSC.getCvalue():null));
+ map.put("last_login",last_login);
+ map.put("contact_us_link",contact_us_link);
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while getting values : " + EcompPortalUtils.getStackTrace(e));
+ }
+
+ JSONObject j = new JSONObject(map);
+ String fnMenuStaticResponse = "";
+ try {
+ fnMenuStaticResponse = j.toString();
+ // response.getWriter().write(fnMenuStaticResponse);
+ EcompPortalUtils.logAndSerializeObject("/portalApi/functionalMenuStaticInfo", "GET result =", fnMenuStaticResponse);
+ } catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while writing the result to the HttpServletResponse object. Details: " +
+ EcompPortalUtils.getStackTrace(e));
+ }
+ return fnMenuStaticResponse;
+ }
+
+ @RequestMapping(value = {"/portalApi/resetFunctionalMenuStaticInfo" }, method = RequestMethod.GET,produces = "application/json")
+ public PortalRestResponse<Map<String, String>> resetFunctionalMenuStaticInfo(HttpServletRequest request, HttpServletResponse response) {
+ PortalRestResponse<String> portalRestResponse = null;
+ try {
+ // get current user
+ EPUser user = EPUserUtils.getUserSession(request);
+ String userId = user.getOrgUserId();
+ StringBuffer criteria = new StringBuffer();
+ criteria.append(" where org_user_id = '").append(userId).append("'");
+ // retrieve latest user info from EPUser
+ List list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null);
+ EPUser updatedUser = (EPUser)list.get(0);
+ EPUserUtils.setUserSession(request, updatedUser, new HashSet(), new HashSet(), SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM));
+ return new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", null);
+ }
+ catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getOnlineUserUpdateRate failed", e);
+ return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.toString(), null);
+ }
+
+ }
+}
+
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/GetAccessController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/GetAccessController.java
new file mode 100644
index 00000000..5fe22194
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/GetAccessController.java
@@ -0,0 +1,70 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.openecomp.portalapp.controller.EPUnRestrictedBaseController;
+import org.openecomp.portalapp.portal.domain.GetAccessResult;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.GetAccessService;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+
+@RestController
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class GetAccessController extends EPUnRestrictedBaseController {
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(GetAccessController.class);
+
+ @Autowired
+ GetAccessService getAccessService;
+
+ /**
+ * Sorts the list by ECOMP function name.
+ */
+ private Comparator<GetAccessResult> getAccessComparator = new Comparator<GetAccessResult>() {
+ public int compare(GetAccessResult o1, GetAccessResult o2) {
+ return o1.getEcompFunction().compareTo(o2.getEcompFunction());
+ }
+ };
+
+ @RequestMapping(value = { "/portalApi/getAppList" }, method = RequestMethod.GET, produces = "application/json")
+ public List<GetAccessResult> getAppList(HttpServletRequest request) throws IOException {
+ List<GetAccessResult> appsList = null;
+ appsList = getAccessService.getAppAccessList();
+ Collections.sort(appsList, getAccessComparator);
+ EcompPortalUtils.logAndSerializeObject("/portalApi/getAppList", "result =", appsList);
+ return appsList;
+ }
+} \ No newline at end of file
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/HealthCheckController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/HealthCheckController.java
new file mode 100644
index 00000000..a3870517
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/HealthCheckController.java
@@ -0,0 +1,234 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.portal.listener.HealthMonitor;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
+import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.slf4j.MDC;
+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 com.google.gson.Gson;
+
+/*
+ * This controller checks the health status and returns JSON response.
+ * It does not require
+ */
+@RestController
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class HealthCheckController extends EPRestrictedBaseController {
+
+ private class HealthStatus {
+ public int statusCode;
+ @SuppressWarnings("unused")
+ public String body;
+
+ public HealthStatus(int code, String body) {
+ this.statusCode = code;
+ this.body = body;
+ }
+ }
+
+ private class HealthStatusInfo {
+ HealthStatusInfo(String healthCheckComponent) {
+ this.healthCheckComponent = healthCheckComponent;
+ this.healthCheckStatus = statusUp; // Default value
+ this.version = "";
+ this.description = statusOk; // Default value
+ this.hostName = "";
+ this.ipAddress = "";
+ this.dbClusterStatus = "";
+ this.dbPermissions = "";
+ }
+
+ @SuppressWarnings("unused")
+ public String healthCheckComponent;
+ @SuppressWarnings("unused")
+ public String healthCheckStatus;
+ @SuppressWarnings("unused")
+ public String version;
+ @SuppressWarnings("unused")
+ public String description;
+ @SuppressWarnings("unused")
+ public String hostName;
+ @SuppressWarnings("unused")
+ public String ipAddress;
+ @SuppressWarnings("unused")
+ public String dbClusterStatus;
+ @SuppressWarnings("unused")
+ public String dbPermissions;
+ }
+
+ private final String statusUp = "UP";
+ private final String statusDown = "DOWN";
+ private final String statusOk = "OK";
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HealthCheckController.class);
+
+ @RequestMapping(value = { "/portalApi/healthCheck" }, method = RequestMethod.GET, produces = "application/json")
+ public HealthStatus healthCheck(HttpServletRequest request, HttpServletResponse response) {
+ HealthStatus healthStatus = new HealthStatus(500, "");
+
+ // Return the status as 500 if it suspended due to manual fail over
+ if (HealthMonitor.isSuspended) {
+ healthStatus.body = "Suspended";
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ MDC.put(EPSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
+ return healthStatus;
+ }
+
+ try {
+ boolean overallStatus = true;
+
+ List<HealthStatusInfo> statusCollection = new ArrayList<HealthStatusInfo>();
+
+ HealthStatusInfo beInfo = new HealthStatusInfo("BE");
+ beInfo.hostName = EcompPortalUtils.getMyHostName();
+ beInfo.ipAddress = EcompPortalUtils.getMyIpAdddress();
+ if (!HealthMonitor.isBackEndUp()) {
+ overallStatus = false;
+ beInfo.healthCheckStatus = statusDown;
+ beInfo.description = "Check the logs for more details";
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeHealthCheckError);
+ }
+ statusCollection.add(beInfo);
+
+ HealthStatusInfo feInfo = new HealthStatusInfo("FE");
+ if (!HealthMonitor.isFrontEndUp()) {
+ overallStatus = false;
+ feInfo.healthCheckStatus = statusDown;
+ feInfo.description = "Check the logs for more details";
+ EPLogUtil.logEcompError(EPAppMessagesEnum.FeHealthCheckError);
+ }
+ statusCollection.add(feInfo);
+
+ HealthStatusInfo dbInfo = new HealthStatusInfo("DB");
+ if (!HealthMonitor.isDatabaseUp()) {
+ overallStatus = false;
+ dbInfo.healthCheckStatus = statusDown;
+ dbInfo.description = "Check the logs for more details";
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ }
+
+ if (!HealthMonitor.isClusterStatusOk()) {
+ dbInfo.dbClusterStatus = "Problem, check the logs for more details";
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ }
+ else {
+ dbInfo.dbClusterStatus = statusOk;
+ }
+
+ if (!HealthMonitor.isDatabasePermissionsOk()) {
+ dbInfo.dbPermissions = "Problem, check the logs for more details";
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ }
+ else {
+ dbInfo.dbPermissions = statusOk;
+ }
+ statusCollection.add(dbInfo);
+
+ HealthStatusInfo uebInfo = new HealthStatusInfo("UEB");
+ if (!HealthMonitor.isUebUp()) {
+ uebInfo.healthCheckStatus = statusDown;
+ uebInfo.description = "Check the logs for more details";
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeUebConnectionError);
+ }
+ statusCollection.add(uebInfo);
+
+ String json = "";
+ try {
+ json = new Gson().toJson(statusCollection);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput);
+ }
+ logger.info(EELFLoggerDelegate.debugLogger, json);
+
+ if (overallStatus) {
+ healthStatus = new HealthStatus(200, json);
+ } else {
+ healthStatus = new HealthStatus(500, json);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+ MDC.put(EPSystemProperties.RESPONSE_CODE, Integer.toString(healthStatus.statusCode));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing the healthcheck. Details: "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+
+ EcompPortalUtils.logAndSerializeObject("/portalApi/healthCheck", "GET result =", response.getStatus());
+
+ return healthStatus;
+ }
+
+ @RequestMapping(value = {
+ "/portalApi/healthCheckSuspend" }, method = RequestMethod.GET, produces = "application/json")
+ public HealthStatus healthCheckSuspend(HttpServletRequest request, HttpServletResponse response) {
+ HealthStatus healthStatus = new HealthStatus(500, "Suspended for manual failover mechanism");
+
+ HealthMonitor.isSuspended = true;
+ healthStatus.statusCode = 200;
+
+ EcompPortalUtils.logAndSerializeObject("/portalApi/healthCheckSuspend", "GET result =",
+ response.getStatus());
+
+ return healthStatus;
+ }
+
+ @RequestMapping(value = {
+ "/portalApi/healthCheckResume" }, method = RequestMethod.GET, produces = "application/json")
+ public HealthStatus healthCheckResume(HttpServletRequest request, HttpServletResponse response) {
+ HealthStatus healthStatus = new HealthStatus(500, "Resumed from manual failover mechanism");
+
+ HealthMonitor.isSuspended = false;
+ healthStatus.statusCode = 200;
+ EcompPortalUtils.logAndSerializeObject("/portalApi/healthCheckResume", "GET result =",
+ response.getStatus());
+ return healthStatus;
+ }
+
+
+
+ @RequestMapping(value = {
+ "/portalApi/ping" }, method = RequestMethod.GET, produces = "application/json")
+ public HealthStatus ping(HttpServletRequest request, HttpServletResponse response) {
+ HealthStatus healthStatus = new HealthStatus(200, "OK");
+ EcompPortalUtils.logAndSerializeObject("/portalApi/ping", "GET result =",
+ response.getStatus());
+
+ return healthStatus;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/ManifestController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/ManifestController.java
new file mode 100644
index 00000000..ae8dc57b
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/ManifestController.java
@@ -0,0 +1,93 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.jar.Attributes;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.ManifestService;
+import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.RestController;
+
+
+
+/**
+ * This controller responds to a request for the web application manifest,
+ * returning a JSON with the information that was created at build time.
+ *
+ * Manifest entries have names with hyphens, which means Javascript code can't
+ * simply use the shorthand object.key; instead use object['key'].
+ */
+@RestController
+@Configuration
+@EnableAspectJAutoProxy
+@RequestMapping("/")
+@EPAuditLog
+@Controller
+public class ManifestController extends RestrictedBaseController {
+
+ private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ManifestController.class);
+
+ @Autowired
+ ManifestService manifestService;
+
+ /**
+ * Gets the webapp manifest contents as a JSON object.
+ *
+ * @param request
+ * @return A map of key-value pairs. On success:
+ *
+ * <pre>
+ * { "manifest" : { "key1": "value1", "key2": "value2" } }
+ * </pre>
+ *
+ * On failure:
+ *
+ * <pre>
+ * { "error": "message" }
+ * </pre>
+ */
+ @RequestMapping(value = { "/portalApi/manifest" }, method = RequestMethod.GET, produces = "application/json")
+ @ResponseBody
+ public Map<String, Object> getManifest(HttpServletRequest request) {
+ Map<String, Object> response = new HashMap<String, Object>();
+ try {
+ Attributes attributes = manifestService.getWebappManifest();
+ response.put("manifest", attributes);
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getManifest: failed to read manifest", ex);
+ response.put("error", "failed to get manifest: " + ex.toString());
+ }
+ return response;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java
new file mode 100644
index 00000000..951c0534
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/PortalAdminController.java
@@ -0,0 +1,117 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.AdminRolesService;
+import org.openecomp.portalapp.portal.service.PortalAdminService;
+import org.openecomp.portalapp.portal.transport.FieldsValidator;
+import org.openecomp.portalapp.portal.transport.PortalAdmin;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class PortalAdminController extends EPRestrictedBaseController {
+ @Autowired
+ PortalAdminService portalAdminService;
+ @Autowired
+ AdminRolesService adminRolesService;
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalAdminController.class);
+
+ @RequestMapping(value = { "/portalApi/portalAdmins" }, method = RequestMethod.GET, produces = "application/json")
+ public List<PortalAdmin> getPortalAdmins(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<PortalAdmin> portalAdmins = null;
+ if (user == null) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.getPortalAdmins, null user");
+ EcompPortalUtils.setBadPermissions(user, response, "getPortalAdmins");
+ } else if (!adminRolesService.isSuperAdmin(user)) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.getPortalAdmins, bad permissions");
+ EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin");
+ } else {
+ // return the list of portal admins
+ portalAdmins = portalAdminService.getPortalAdmins();
+ logger.debug(EELFLoggerDelegate.debugLogger, "portalAdmins: called getPortalAdmins()");
+ EcompPortalUtils.logAndSerializeObject("/portalApi/getPortalAdmins", "result =", portalAdmins);
+ }
+
+ return portalAdmins;
+ }
+
+ /**
+ * RESTful service method to create a new portal admin. Requirement: you
+ * must be the Ecomp portal super admin user.
+ */
+
+ @RequestMapping(value = { "/portalApi/portalAdmin" }, method = RequestMethod.POST)
+ public FieldsValidator createPortalAdmin(HttpServletRequest request, @RequestBody String userid,
+ HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ FieldsValidator fieldsValidator = null;
+ if (user == null) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin, null user");
+ EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin");
+ } else if (!adminRolesService.isSuperAdmin(user)) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin bad permissions");
+ EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin");
+ } else {
+ fieldsValidator = portalAdminService.createPortalAdmin(userid);
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ }
+ EcompPortalUtils.logAndSerializeObject("/portalAdmin", "POST result =", response.getStatus());
+
+ return fieldsValidator;
+ }
+
+ @RequestMapping(value = { "/portalApi/portalAdmin/{orgUserId}" }, method = RequestMethod.DELETE)
+ public FieldsValidator deletePortalAdmin(HttpServletRequest request, @PathVariable("orgUserId") Long orgUserId,
+ HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ FieldsValidator fieldsValidator = null;
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "deletePortalAdmin");
+ } else {
+ fieldsValidator = portalAdminService.deletePortalAdmin(orgUserId);
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ }
+ EcompPortalUtils.logAndSerializeObject("/portalAdmin", "DELETE result =", response.getStatus());
+
+ return fieldsValidator;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/SharedContextRestController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/SharedContextRestController.java
new file mode 100644
index 00000000..d2f94e52
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/SharedContextRestController.java
@@ -0,0 +1,335 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.controller.EPRestrictedRESTfulBaseController;
+import org.openecomp.portalapp.portal.domain.SharedContext;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.SharedContextService;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+/**
+ * The shared-context feature allows onboarded applications to share data among
+ * themselves easily for a given session. It basically implements a Java map:
+ * put or get a key-value pair within a map identified by a session ID.
+ *
+ * This REST endpoint listens on the Portal app server and answers requests made
+ * by back-end application servers. Reads and writes values to the database
+ * using a Hibernate service to ensure all servers in a high-availability
+ * cluster see the same data.
+ *
+ * TODO: This extends EPRestrictedRESTfulBaseController which is an exact copy
+ * of org.openecomp.portalsdk.core.controller.RestrictedRESTfulBaseController.
+ */
+
+@RestController
+@RequestMapping("/context")
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class SharedContextRestController extends EPRestrictedRESTfulBaseController {
+ /**
+ * Access to the database
+ */
+ @Autowired
+ SharedContextService contextService;
+
+ /**
+ * Logger for debug etc.
+ */
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextRestController.class);
+
+ /**
+ * Reusable JSON (de)serializer
+ */
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ /**
+ * Gets a value for the specified context and key (RESTful service method).
+ *
+ * @param ctxtId
+ * ID that identifies the context, usually the ECOMP Portal
+ * session key.
+ * @param ckey
+ * Key for the key-value pair to fetch
+ * @return JSON with shared context object; response=null if not found.
+ */
+ @RequestMapping(value = { "/get" }, method = RequestMethod.GET, produces = "application/json")
+ public String getContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey) throws Exception {
+ String jsonResponse = "";
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "getContext for ID " + context_id + ", key " + ckey);
+ if (context_id == null || ckey == null) {
+ throw new Exception("Received null for context_id and/or ckey");
+ }
+
+ SharedContext context = contextService.getSharedContext(context_id, ckey);
+ if (context == null) {
+ jsonResponse = convertResponseToJSON(context);
+ } else {
+ jsonResponse = mapper.writeValueAsString(context);
+ }
+
+ return jsonResponse;
+ }
+
+ /**
+ * Gets user information for the specified context (RESTful service method).
+ *
+ * @param ctxtId
+ * ID that identifies the context, usually the ECOMP Portal
+ * session key.
+ *
+ * @return JSON with user's first name, last name and email address; null if
+ * none found
+ */
+ @RequestMapping(value = { "/get_user" }, method = RequestMethod.GET, produces = "application/json")
+ public String getUserContext(HttpServletRequest request, @RequestParam String context_id) throws Exception {
+ String jsonResponse = "";
+ List<SharedContext> listSharedContext = new ArrayList<SharedContext>();
+ try{
+ logger.debug(EELFLoggerDelegate.debugLogger, "getUserContext for ID " + context_id);
+ if (context_id == null) {
+ throw new Exception("Received null for contextId");
+ }
+ try{
+ SharedContext firstNameContext = contextService.getSharedContext(context_id, EPSystemProperties.USER_FIRST_NAME);
+ SharedContext lastNameContext = contextService.getSharedContext(context_id, EPSystemProperties.USER_LAST_NAME);
+ SharedContext emailContext = contextService.getSharedContext(context_id, EPSystemProperties.USER_EMAIL);
+ SharedContext userIdContext = contextService.getSharedContext(context_id, EPSystemProperties.USER_ORG_USERID);
+ if (firstNameContext != null)
+ listSharedContext.add(firstNameContext);
+ if (lastNameContext != null)
+ listSharedContext.add(lastNameContext);
+ if (emailContext != null)
+ listSharedContext.add(emailContext);
+ if (userIdContext != null)
+ listSharedContext.add(userIdContext);
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "Error while getting SharedContext values from database ... ",e);
+ }
+ jsonResponse = convertResponseToJSON(listSharedContext);
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "Error while running getUserContext request ... ", e);
+ }
+ return jsonResponse;
+ }
+
+ /**
+ * Tests for presence of the specified key in the specified context (RESTful
+ * service method).
+ *
+ * @param context_id
+ * ID that identifies the context, usually the ECOMP Portal
+ * session key.
+ * @param ckey
+ * Key for the key-value pair to test
+ * @return JSON with result indicating whether the context and key were
+ * found.
+ */
+ @RequestMapping(value = { "/check" }, method = RequestMethod.GET, produces = "application/json")
+ public String checkContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey) throws Exception {
+ String jsonResponse = "";
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "checkContext for " + context_id + ", key " + ckey);
+ if (context_id == null || ckey == null) {
+ throw new Exception("Received null for contextId and/or key");
+ }
+
+ String response = null;
+ SharedContext context = contextService.getSharedContext(context_id, ckey);
+ if (context != null)
+ response = "exists";
+
+ jsonResponse = convertResponseToJSON(response);
+
+ return jsonResponse;
+ }
+
+ /**
+ * Removes the specified key in the specified context (RESTful service
+ * method).
+ *
+ * @param context_id
+ * ID that identifies the context, usually the ECOMP Portal
+ * session key.
+ * @param ckey
+ * Key for the key-value pair to remove
+ * @return JSON with result indicating whether the context and key were
+ * found.
+ */
+ @RequestMapping(value = { "/remove" }, method = RequestMethod.GET, produces = "application/json")
+ public String removeContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey) throws Exception {
+ String jsonResponse = "";
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "removeContext for " + context_id + ", key " + ckey);
+ if (context_id == null || ckey == null) {
+ throw new Exception("Received null for contextId and/or key");
+ }
+
+ SharedContext context = contextService.getSharedContext(context_id, ckey);
+ String response = null;
+ if (context != null) {
+ contextService.deleteSharedContext(context);
+ response = "removed";
+ }
+
+ jsonResponse = convertResponseToJSON(response);
+
+ return jsonResponse;
+ }
+
+ /**
+ * Clears all key-value pairs in the specified context (RESTful service
+ * method).
+ *
+ * @param context_id
+ * ID that identifies the context, usually the ECOMP Portal
+ * session key.
+ * @return JSON with result indicating the number of key-value pairs removed.
+ */
+ @RequestMapping(value = { "/clear" }, method = RequestMethod.GET, produces = "application/json")
+ public String clearContext(HttpServletRequest request, @RequestParam String context_id) throws Exception {
+ String jsonResponse = "";
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "clearContext for " + context_id);
+ if (context_id == null) {
+ throw new Exception("Received null for contextId");
+ }
+
+ int count = contextService.deleteSharedContexts(context_id);
+ jsonResponse = convertResponseToJSON(Integer.toString(count));
+
+ return jsonResponse;
+ }
+
+ /**
+ * Sets a context value for the specified context and key (RESTful service
+ * method). Creates the context if no context with the specified ID-key pair
+ * exists, overwrites the value if it exists already.
+ *
+ * @param userJson
+ * JSON block with these tag-value pairs:
+ * <UL>
+ * <LI>context_id: ID that identifies the context
+ * <LI>ckey: Key for the key-value pair to store
+ * <LI>cvalue: Value to store
+ * </UL>
+ * @return JSON with result indicating whether the value was added (key not
+ * previously known) or replaced (key previously known).
+ */
+ @RequestMapping(value = { "/set" }, method = RequestMethod.POST, produces = "application/json")
+ public String setContext(HttpServletRequest request, @RequestBody String userJson) throws Exception {
+ String jsonResponse = "";
+
+ @SuppressWarnings("unchecked")
+ Map<String, Object> userData = mapper.readValue(userJson, Map.class);
+ // Use column names as JSON tags
+ final String contextId = (String) userData.get("context_id");
+ final String key = (String) userData.get("ckey");
+ final String value = (String) userData.get("cvalue");
+ if (contextId == null || key == null) {
+ throw new Exception("Received null for contextId and/or key");
+ }
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "setContext for ID " + contextId + ", key " + key + "->" + value);
+ String response = null;
+ SharedContext existing = contextService.getSharedContext(contextId, key);
+ if (existing == null) {
+ contextService.addSharedContext(contextId, key, value);
+ } else {
+ existing.setCvalue(value);
+ contextService.saveSharedContext(existing);
+ }
+ response = existing == null ? "added" : "replaced";
+ jsonResponse = convertResponseToJSON(response);
+
+ return jsonResponse;
+ }
+
+ /**
+ * Creates a two-element JSON object tagged "response".
+ *
+ * @param responseBody
+ * @return
+ * @throws JsonProcessingException
+ */
+ private String convertResponseToJSON(String responseBody) throws JsonProcessingException {
+ Map<String, String> responseMap = new HashMap<String, String>();
+ responseMap.put("response", responseBody);
+ String response = mapper.writeValueAsString(responseMap);
+ return response;
+ }
+
+ /**
+ * Converts list of SharedContext objects to a JSON array.
+ *
+ * @param contextList
+ * @return
+ * @throws JsonProcessingException
+ */
+ private String convertResponseToJSON(List<SharedContext> contextList) throws JsonProcessingException {
+ String jsonArray = mapper.writeValueAsString(contextList);
+ return jsonArray;
+ }
+
+ /**
+ * Creates a JSON object with the content of the shared context; null is ok.
+ *
+ * @param responseBody
+ * @return tag "response" with collection of context object's fields
+ * @throws JsonProcessingException
+ */
+ private String convertResponseToJSON(SharedContext context) throws JsonProcessingException {
+ Map<String, Object> responseMap = new HashMap<String, Object>();
+ responseMap.put("response", context);
+ String responseBody = mapper.writeValueAsString(responseMap);
+ return responseBody;
+ }
+
+ @ExceptionHandler(Exception.class)
+ protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException {
+ logger.warn(EELFLoggerDelegate.errorLogger, "Handling bad request", e);
+ response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java
new file mode 100644
index 00000000..24370fbb
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java
@@ -0,0 +1,336 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.cxf.transport.http.HTTPException;
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.portal.domain.EPRole;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse;
+import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.AdminRolesService;
+import org.openecomp.portalapp.portal.service.ApplicationsRestClientService;
+import org.openecomp.portalapp.portal.service.SearchService;
+import org.openecomp.portalapp.portal.service.UserRolesService;
+import org.openecomp.portalapp.portal.transport.AppNameIdIsAdmin;
+import org.openecomp.portalapp.portal.transport.AppWithRolesForUser;
+import org.openecomp.portalapp.portal.transport.AppsListWithAdminRole;
+import org.openecomp.portalapp.portal.transport.FieldsValidator;
+import org.openecomp.portalapp.portal.transport.RoleInAppForUser;
+import org.openecomp.portalapp.portal.transport.UserApplicationRoles;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.restful.domain.EcompRole;
+import org.openecomp.portalsdk.core.service.RoleService;
+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.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class UserRolesController extends EPRestrictedBaseController {
+
+ static final String FAILURE = "failure";
+
+ @Autowired
+ SearchService searchService;
+ @Autowired
+ AdminRolesService adminRolesService;
+ @Autowired
+ UserRolesService userRolesService;
+ @Autowired
+ ApplicationsRestClientService applicationsRestClientService;
+ @Autowired
+ RoleService roleService;
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesController.class);
+
+ /**
+ * RESTful service method to fetch users in the WebPhone external service
+ *
+ * @return array of found users as json
+ */
+ @RequestMapping(value = { "/portalApi/queryUsers" }, method = RequestMethod.GET, produces = "application/json")
+ public String getPhoneBookSearchResult(HttpServletRequest request, @RequestParam("search") String searchString, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ String searchResult = null;
+ if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "getPhoneBookSearchResult");
+ } else {
+ searchString = searchString.trim();
+ if (searchString.length() > 0) {
+ //searchResult = searchService.searchUsersInPhoneBook(searchString);
+ searchResult = searchService.searchUsersInFnTable(searchString);
+ } else {
+ logger.info(EELFLoggerDelegate.errorLogger, "getPhoneBookSearchResult - too short search string: " + searchString);
+ }
+ }
+ EcompPortalUtils.logAndSerializeObject("/portalApi/queryUsers", "result =", searchResult);
+
+ return searchResult;
+ }
+
+ /**
+ * RESTful service method to fetch applications where user is admin
+ *
+ * @return for GET: array of all applications with boolean isAdmin=true/false for each application
+ */
+ @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = { RequestMethod.GET }, produces = "application/json")
+ public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(HttpServletRequest request, @RequestParam("orgUserId") String orgUserId,
+ HttpServletResponse response) {
+
+ EPUser user = EPUserUtils.getUserSession(request);
+ AppsListWithAdminRole result = null;
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "getAppsWithAdminRoleStateForUser");
+ } else {
+ if (EcompPortalUtils.legitimateUserId(orgUserId)) {
+ result = adminRolesService.getAppsWithAdminRoleStateForUser(orgUserId);
+ } else {
+ logger.info(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser - parms error, no orgUserId");
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ }
+ }
+
+ StringBuilder adminAppRoles = new StringBuilder();
+ if(result != null && result.appsRoles.size() >= 1) {
+ adminAppRoles.append("User '" + result.orgUserId + "' has admin role to the apps = {");
+ for(AppNameIdIsAdmin adminAppRole : result.appsRoles) {
+ if (adminAppRole.isAdmin) {
+ adminAppRoles.append(adminAppRole.appName + ", ");
+ }
+ }
+ adminAppRoles.append("}.");
+ } else {
+ adminAppRoles.append("User '" + result.orgUserId + "' has no Apps with Admin Role.");
+ }
+ logger.info(EELFLoggerDelegate.errorLogger, adminAppRoles.toString());
+
+ EcompPortalUtils.logAndSerializeObject("/portalApi/adminAppsRoles", "get result =", result);
+
+ return result;
+ }
+
+ @RequestMapping(value = { "/portalApi/adminAppsRoles" }, method = { RequestMethod.PUT }, produces = "application/json")
+ public FieldsValidator putAppsWithAdminRoleStateForUser(HttpServletRequest request, @RequestBody AppsListWithAdminRole newAppsListWithAdminRoles,
+ HttpServletResponse response) {
+
+ //newAppsListWithAdminRoles.appsRoles
+ FieldsValidator fieldsValidator = new FieldsValidator();
+ StringBuilder newAppRoles = new StringBuilder();
+ if(newAppsListWithAdminRoles != null && newAppsListWithAdminRoles.appsRoles.size() >= 1) {
+ newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has admin role to the apps = {");
+ for(AppNameIdIsAdmin adminAppRole : newAppsListWithAdminRoles.appsRoles) {
+ if (adminAppRole.isAdmin) {
+ newAppRoles.append(adminAppRole.appName + ", ");
+ }
+ }
+ newAppRoles.append("}.");
+ } else {
+ newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has no Apps with Admin Role.");
+ }
+ logger.info(EELFLoggerDelegate.errorLogger, newAppRoles.toString());
+
+ EPUser user = EPUserUtils.getUserSession(request);
+ boolean changesApplied = false;
+
+ if (!adminRolesService.isSuperAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "putAppsWithAdminRoleStateForUser");
+ } else {
+ changesApplied = adminRolesService.setAppsWithAdminRoleStateForUser(newAppsListWithAdminRoles);
+ }
+ EcompPortalUtils.logAndSerializeObject("/portalApi/adminAppsRoles", "put result =", changesApplied);
+
+ return fieldsValidator;
+ }
+
+ @RequestMapping(value = { "/portalApi/userAppRoles" }, method = { RequestMethod.GET }, produces = "application/json")
+ public List<RoleInAppForUser> getAppRolesForUser(HttpServletRequest request, @RequestParam("orgUserId") String orgUserId, @RequestParam("app") Long appid, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<RoleInAppForUser> result = null;
+ String feErrorString = "";
+ if (!adminRolesService.isAccountAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "getAppRolesForUser");
+ feErrorString = EcompPortalUtils.getFEErrorString(true, response.getStatus());
+ } else {
+ if (EcompPortalUtils.legitimateUserId(orgUserId)) {
+ result = userRolesService.getAppRolesForUser(appid, orgUserId);
+ int responseCode = EcompPortalUtils.getExternalAppResponseCode();
+ if (responseCode != 0 && responseCode != 200) {
+ // external error
+ response.setStatus(responseCode);
+ feErrorString = EcompPortalUtils.getFEErrorString(false, responseCode);
+ } else if (result == null) {
+ // If the result is null, there was an internal ecomp error in the service call.
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ feErrorString = EcompPortalUtils.getFEErrorString(true, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+ } else {
+ logger.info(EELFLoggerDelegate.errorLogger, "getAppRolesForUser - no userId");
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ feErrorString = EcompPortalUtils.getFEErrorString(true, HttpServletResponse.SC_BAD_REQUEST);
+ }
+ }
+
+ StringBuilder sbUserApps = new StringBuilder();
+ if (result!=null && result.size()>=1) {
+ sbUserApps.append("User '" + orgUserId + "' has Roles={");
+ for(RoleInAppForUser appRole : result) {
+ if (appRole.isApplied) {
+ sbUserApps.append(appRole.roleName + ", ");
+ }
+ }
+ sbUserApps.append("} assigned to the appId '" + appid + "'.");
+ } else {
+ if (result==null) {
+ result = new ArrayList<RoleInAppForUser>();
+ }
+ sbUserApps.append("User '" + orgUserId + "' and appid " + appid + " has no roles");
+ }
+ logger.info(EELFLoggerDelegate.errorLogger, sbUserApps.toString());
+
+ EcompPortalUtils.logAndSerializeObject("/portalApi/userAppRoles", "get result =", result);
+ if (feErrorString != "") {
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: FEErrorString to header: "+feErrorString);
+
+ response.addHeader("FEErrorString", feErrorString);
+ response.addHeader("Access-Control-Expose-Headers", "FEErrorString");
+ }
+ return result;
+ }
+
+ @RequestMapping(value = { "/portalApi/userAppRoles" }, method = { RequestMethod.PUT }, produces = "application/json")
+ public FieldsValidator putAppWithUserRoleStateForUser(HttpServletRequest request, @RequestBody AppWithRolesForUser newAppRolesForUser,
+ HttpServletResponse response) {
+ FieldsValidator fieldsValidator = new FieldsValidator();
+ StringBuilder sbUserApps = new StringBuilder();
+ if (newAppRolesForUser!=null) {
+ sbUserApps.append("User '" + newAppRolesForUser.orgUserId);
+ if (newAppRolesForUser.appRoles!=null && newAppRolesForUser.appRoles.size()>=1) {
+ sbUserApps.append("' has roles = {");
+ for(RoleInAppForUser appRole : newAppRolesForUser.appRoles) {
+ if (appRole.isApplied) {
+ sbUserApps.append(appRole.roleName + ", ");
+ }
+ }
+ sbUserApps.append("} assigned for the app '" + newAppRolesForUser.appName + "'.");
+ } else {
+ sbUserApps.append("' has no roles assigned for the app '" + newAppRolesForUser.appName + "'.");
+ }
+ }
+ logger.info(EELFLoggerDelegate.errorLogger, sbUserApps.toString());
+
+ EPUser user = EPUserUtils.getUserSession(request);
+
+ boolean changesApplied = false;
+ if (!adminRolesService.isAccountAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, "putAppWithUserRoleStateForUser");
+ } else {
+ changesApplied = userRolesService.setAppWithUserRoleStateForUser(user, newAppRolesForUser);
+ if (changesApplied == false) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "putAppWithUserRoleStateForUser - Set new User Roles failure");
+ }
+ }
+
+ EcompPortalUtils.logAndSerializeObject("/portalApi/userAppRoles", "put result =", changesApplied);
+
+ return fieldsValidator;
+ }
+
+ @RequestMapping(value = { "/portalApi/updateRemoteUserProfile" }, method = { RequestMethod.GET }, produces = "application/json")
+ public PortalRestResponse<String> updateRemoteUserProfile(HttpServletRequest request,HttpServletResponse response) {
+
+ String updateRemoteUserFlag = FAILURE;
+ try {
+ //saveNewUser = userService.saveNewUser(newUser);
+ String orgUserId = request.getParameter("loginId");
+ Long appId = Long.parseLong(request.getParameter("appId"));
+ userRolesService.updateRemoteUserProfile(orgUserId, appId);
+
+ } catch (Exception e) {
+ return new PortalRestResponse<String>(PortalRestStatusEnum.OK, updateRemoteUserFlag, e.getMessage());
+ }
+ return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, updateRemoteUserFlag, "");
+
+ }
+
+ @RequestMapping(value = { "/portalApi/app/{appId}/users" }, method = { RequestMethod.GET }, produces = "application/json")
+ public List<UserApplicationRoles> getUsersFromAppEndpoint(HttpServletRequest request, @PathVariable("appId") Long appId) throws HTTPException {
+ try {
+ List<UserApplicationRoles> appUsers = userRolesService.getUsersFromAppEndpoint(appId);
+ return appUsers;
+ } catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing UserRolesController.getUsersFromAppEndpoint. Details: " + EcompPortalUtils.getStackTrace(e));
+ return new ArrayList<UserApplicationRoles>();
+ }
+ }
+
+ @RequestMapping(value = { "/portalApi/app/{appId}/roles" }, method = { RequestMethod.GET }, produces = "application/json")
+ public List<EcompRole> testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId) throws HTTPException {
+ EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
+ List<EcompRole> rolesList = Arrays.asList(appRoles);
+ EcompPortalUtils.logAndSerializeObject("/portalApi/app/{appId}/roles", "response for appId=" + appId, rolesList);
+
+ return rolesList;
+ }
+
+ @RequestMapping(value = { "/portalApi/admin/import/app/{appId}/roles" }, method = { RequestMethod.GET }, produces = "application/json")
+ public List<EPRole> importRolesFromRemoteApplication(HttpServletRequest request, @PathVariable("appId") Long appId) throws HTTPException {
+ List<EPRole> rolesList = userRolesService.importRolesFromRemoteApplication(appId);
+ EcompPortalUtils.logAndSerializeObject("/portalApi/admin/import/app/{appId}/roles", "response for appId=" + appId, rolesList);
+
+ return rolesList;
+ }
+
+ @RequestMapping(value = { "/portalApi/app/{appId}/user/{orgUserId}/roles" }, method = { RequestMethod.GET }, produces = "application/json")
+ public EcompRole testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId, @PathVariable("orgUserId") String orgUserId) throws Exception {
+ if (!EcompPortalUtils.legitimateUserId(orgUserId)) {
+ String msg = "Error /user/<user>/roles not legitimate orgUserId = " + orgUserId;
+ logger.error(EELFLoggerDelegate.errorLogger, msg);
+ throw new Exception(msg);
+ }
+ EcompRole[] roles = applicationsRestClientService.get(EcompRole[].class, appId, String.format("/user/%s/roles", orgUserId));
+ if (roles.length != 1) {
+ String msg = "Error /user/<user>/roles returned array. expected size 1 recieved size = " + roles.length;
+ logger.error(EELFLoggerDelegate.errorLogger, msg);
+ throw new Exception(msg);
+ }
+
+ EcompPortalUtils.logAndSerializeObject("/portalApi/app/{appId}/user/{orgUserId}/roles", "response for appId='" + appId + "' and orgUserId='" + orgUserId + "'", roles[0]);
+ return roles[0];
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsController.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsController.java
new file mode 100644
index 00000000..ddadef93
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/controller/WidgetsController.java
@@ -0,0 +1,134 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.controller;
+
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.cxf.common.util.StringUtils;
+import org.openecomp.portalapp.controller.EPRestrictedBaseController;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.AdminRolesService;
+import org.openecomp.portalapp.portal.service.WidgetService;
+import org.openecomp.portalapp.portal.transport.FieldsValidator;
+import org.openecomp.portalapp.portal.transport.OnboardingWidget;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class WidgetsController extends EPRestrictedBaseController {
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetsController.class);
+
+ @Autowired
+ AdminRolesService adminRolesService;
+ @Autowired
+ WidgetService widgetService;
+
+ @RequestMapping(value = { "/portalApi/widgets" }, method = RequestMethod.GET, produces = "application/json")
+ public List<OnboardingWidget> getOnboardingWidgets(HttpServletRequest request, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ List<OnboardingWidget> onboardingWidgets = null;
+
+ if (user == null || user.isGuest()) {
+ EcompPortalUtils.setBadPermissions(user, response, "getOnboardingWidgets");
+ } else {
+ String getType = request.getHeader("X-Widgets-Type");
+ if (!StringUtils.isEmpty(getType) && (getType.equals("managed") || getType.equals("all"))) {
+ onboardingWidgets = widgetService.getOnboardingWidgets(user, getType.equals("managed"));
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "WidgetsController.getOnboardingApps - request must contain header 'X-Widgets-Type' with 'all' or 'managed'");
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ }
+ }
+
+ EcompPortalUtils.logAndSerializeObject("/portalApi/widgets", "GET result =", response.getStatus());
+ return onboardingWidgets;
+ }
+
+ private boolean userHasPermissions(EPUser user, HttpServletResponse response, String invocator) {
+ if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdmin(user)) {
+ EcompPortalUtils.setBadPermissions(user, response, invocator);
+ return false;
+ }
+ return true;
+ }
+
+ // Attention: real json has all OnboardingWidget fields except "id", we use OnboardingWidget for not to create new class for parsing
+ @RequestMapping(value = { "/portalApi/widgets/{widgetId}" }, method = { RequestMethod.PUT }, produces = "application/json")
+ public FieldsValidator putOnboardingWidget(HttpServletRequest request, @PathVariable("widgetId") Long widgetId,
+ @RequestBody OnboardingWidget onboardingWidget, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ FieldsValidator fieldsValidator = null;
+ if (userHasPermissions(user, response, "putOnboardingWidget")) {
+ onboardingWidget.id = widgetId; // !
+ onboardingWidget.normalize();
+ fieldsValidator = widgetService.setOnboardingWidget(user, onboardingWidget);
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ }
+ EcompPortalUtils.logAndSerializeObject("/portalApi/widgets/" + widgetId, "GET result =", response.getStatus());
+
+ return fieldsValidator;
+ }
+
+ // Attention: real json has all OnboardingWidget fields except "id", we use OnboardingWidget for not to create new class for parsing
+ @RequestMapping(value = { "/portalApi/widgets" }, method = { RequestMethod.POST }, produces = "application/json")
+ public FieldsValidator postOnboardingWidget(HttpServletRequest request, @RequestBody OnboardingWidget onboardingWidget, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ FieldsValidator fieldsValidator = null; ;
+
+ if (userHasPermissions(user, response, "postOnboardingWidget")) {
+ onboardingWidget.id = null; // !
+ onboardingWidget.normalize();
+ fieldsValidator = widgetService.setOnboardingWidget(user, onboardingWidget);
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ }
+
+ EcompPortalUtils.logAndSerializeObject("/portalApi/widgets", "POST result =", response.getStatus());
+ return fieldsValidator;
+ }
+
+ @RequestMapping(value = { "/portalApi/widgets/{widgetId}" }, method = { RequestMethod.DELETE }, produces = "application/json")
+ public FieldsValidator deleteOnboardingWidget(HttpServletRequest request, @PathVariable("widgetId") Long widgetId, HttpServletResponse response) {
+ EPUser user = EPUserUtils.getUserSession(request);
+ FieldsValidator fieldsValidator = null; ;
+
+ if (userHasPermissions(user, response, "deleteOnboardingWidget")) {
+ fieldsValidator = widgetService.deleteOnboardingWidget(user, widgetId);
+ response.setStatus(fieldsValidator.httpStatusCode.intValue());
+ }
+
+ EcompPortalUtils.logAndSerializeObject("/portalApi/widgets/" + widgetId, "DELETE result =", response.getStatus());
+ return fieldsValidator;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AdminUserApp.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AdminUserApp.java
new file mode 100644
index 00000000..ae55f6f2
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AdminUserApp.java
@@ -0,0 +1,88 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.domain;
+
+import java.io.Serializable;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+@Entity
+public class AdminUserApp implements Serializable{
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @Column(name="USER_ID")
+ private Long user_Id;
+
+ @Column(name="FIRST_NAME")
+ private String firstName;
+
+ @Column(name="LAST_NAME")
+ private String lastName;
+
+ @Column(name="ORG_USER_ID")
+ private String orgUserId;
+
+ @Id
+ @Column(name="APP_ID")
+ private Long appId;
+
+ @Column(name="APP_NAME")
+ private String appName;
+
+ public Long getAppId() {
+ return appId;
+ }
+ public void setAppId(Long appId) {
+ this.appId = appId;
+ }
+ public Long getUser_Id() {
+ return user_Id;
+ }
+ public void setUserId(Long user_Id) {
+ this.user_Id = user_Id;
+ }
+ public String getFirstName() {
+ return firstName;
+ }
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+ public String getLastName() {
+ return lastName;
+ }
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+ public String getOrgUserId() {
+ return orgUserId;
+ }
+ public void setOrgUserId(String orgUserId) {
+ this.orgUserId = orgUserId;
+ }
+ public String getAppName() {
+ return appName;
+ }
+ public void setAppName(String appName) {
+ this.appName = appName;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AdminUserApplications.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AdminUserApplications.java
new file mode 100644
index 00000000..3b4179d9
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AdminUserApplications.java
@@ -0,0 +1,96 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class AdminUserApplications {
+ private List<Application> apps = new ArrayList<Application>();
+
+ private Long user_Id;
+ private String firstName;
+ private String lastName;
+ private String orgUserId;
+
+ public AdminUserApplications(AdminUserApp app) {
+ setUser_Id(app.getUser_Id());
+ setOrgUserId(app.getOrgUserId());
+ setFirstName(app.getFirstName());
+ setLastName(app.getLastName());
+
+ addApp(app.getAppId(), app.getAppName());
+ }
+ public Long getUser_Id() {
+ return user_Id;
+ }
+ public void setUser_Id(Long user_Id) {
+ this.user_Id = user_Id;
+ }
+ public String getFirstName() {
+ return firstName;
+ }
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+ public String getLastName() {
+ return lastName;
+ }
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+ public String getOrgUserId() {
+ return orgUserId;
+ }
+ public void setOrgUserId(String orgUserId) {
+ this.orgUserId = orgUserId;
+ }
+ public List<Application> getApps() {
+ return apps;
+ }
+ public void setApps(List<Application> apps) {
+ this.apps = apps;
+ }
+ public void addApp(Long otherAppId, String otherAppName) {
+ apps.add(new Application(otherAppId, otherAppName));
+ }
+
+ public class Application {
+ private Long appId;
+ private String appName;
+
+ public Application(Long otherAppId, String otherAppName) {
+ setAppId(otherAppId);
+ setAppName(otherAppName);
+ }
+ public Long getAppId() {
+ return appId;
+ }
+ public void setAppId(Long appId) {
+ this.appId = appId;
+ }
+ public String getAppName() {
+ return appName;
+ }
+ public void setAppName(String appName) {
+ this.appName = appName;
+ }
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AppContactUs.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AppContactUs.java
new file mode 100644
index 00000000..cb5303c4
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AppContactUs.java
@@ -0,0 +1,86 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.domain;
+
+import org.openecomp.portalsdk.core.domain.support.DomainVo;
+
+/**
+ * Models rows in the fn_app_contact_us table added for 1610.1.
+ */
+public class AppContactUs extends DomainVo {
+
+ private static final long serialVersionUID = -2742197830465055134L;
+
+ private EPApp app;
+ private String description;
+ private String contactEmail;
+ private String contactName;
+ private String url;
+ private String activeYN;
+
+ public EPApp getApp() {
+ return app;
+ }
+
+ public void setApp(EPApp app) {
+ this.app = app;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getContactEmail() {
+ return contactEmail;
+ }
+
+ public void setContactEmail(String contactEmail) {
+ this.contactEmail = contactEmail;
+ }
+
+ public String getContactName() {
+ return contactName;
+ }
+
+ public void setContactName(String contactName) {
+ this.contactName = contactName;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public String getActiveYN() {
+ return activeYN;
+ }
+
+ public void setActiveYN(String activeYN) {
+ this.activeYN = activeYN;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AppContactUsTransportModel.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AppContactUsTransportModel.java
new file mode 100644
index 00000000..e348311f
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AppContactUsTransportModel.java
@@ -0,0 +1,84 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.domain;
+
+/**
+ * An easily serializable-as-JSON version of
+ * {@link org.openecomp.portalapp.portal.domain.AppContactUs}, with the
+ * application ID instead of the EPApp object.
+ */
+public class AppContactUsTransportModel {
+
+ private Long appId;
+ private String appName;
+ private String description;
+ private String contactEmail;
+ private String url;
+ private String activeYN;
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getContactEmail() {
+ return contactEmail;
+ }
+
+ public void setContactEmail(String contactEmail) {
+ this.contactEmail = contactEmail;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public String getActiveYN() {
+ return activeYN;
+ }
+
+ public void setActiveYN(String activeYN) {
+ this.activeYN = activeYN;
+ }
+
+ public String getAppName() {
+ return appName;
+ }
+
+ public void setAppName(String appName) {
+ this.appName = appName;
+ }
+
+ public Long getAppId() {
+ return appId;
+ }
+
+ public void setAppId(Long appId) {
+ this.appId = appId;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AppIdAndNameTransportModel.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AppIdAndNameTransportModel.java
new file mode 100644
index 00000000..52005e88
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AppIdAndNameTransportModel.java
@@ -0,0 +1,63 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.domain;
+
+import java.io.Serializable;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+@Entity
+public class AppIdAndNameTransportModel implements Serializable{
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @Column(name="APP_ID")
+ private Long id;
+
+ @Column(name="APP_NAME")
+ private String name;
+
+ @Column(name="APP_TYPE")
+ private Integer appType;
+
+ 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;
+ }
+
+ public Boolean isRestrictedApp() {
+ return (this.appType == 2 ? true : false);
+ }
+
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AppsResponse.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AppsResponse.java
new file mode 100644
index 00000000..90d8e964
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/AppsResponse.java
@@ -0,0 +1,76 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.domain;
+
+public class AppsResponse {
+
+ public AppsResponse(Long id, String name, Boolean restrictedApp, Boolean enabled) {
+ this.index = id;
+ this.title = this.value = name;
+ this.restrictedApp = restrictedApp;
+ this.enabled = enabled;
+ }
+
+ public Long getIndex() {
+ return index;
+ }
+
+ public void setIndex(Long index) {
+ this.index = index;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ // Hide the implementation of restricted and normal app from the front end.
+ // The json sent and received will include restrictedApp but not appType.
+
+ public void setRestrictedApp(Boolean restrictedApp) {
+ this.restrictedApp = restrictedApp;
+ }
+
+ public Boolean getEnabled() {
+ return enabled;
+ }
+
+ public void setEnabled(Boolean enabled) {
+ this.enabled = enabled;
+ }
+
+ private Long index;
+ private String title;
+ private String value;
+ public Boolean restrictedApp;
+ public Boolean enabled;
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/EPApp.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/EPApp.java
new file mode 100644
index 00000000..8897151c
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/EPApp.java
@@ -0,0 +1,319 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.domain;
+
+import javax.persistence.Lob;
+
+import org.apache.commons.lang.StringUtils;
+import org.openecomp.portalsdk.core.domain.support.DomainVo;
+
+
+public class EPApp extends DomainVo {
+
+ private static final long serialVersionUID = 1L;
+
+ private String name;
+ private String imageUrl;
+ private String description;
+ private String notes;
+ private String url;
+ private String alternateUrl;
+ private String appRestEndpoint;
+ private String mlAppName;
+ private String mlAppAdminId;
+ private Long motsId;
+ private String username;
+ private String appPassword;
+ @Lob
+ private byte[] thumbnail;
+ private Boolean open;
+ private Boolean enabled;
+ private String uebTopicName;
+ private String uebKey;
+ private String uebSecret;
+ private Integer appType;
+
+ private AppContactUs contactUs;
+
+
+/*
+ private SortedSet<Widget> widgets = new TreeSet<Widget>();
+*/
+
+ public EPApp() {
+ // Attention!!!
+ // We set here all default values. We also place protection
+ // into setters for fields with default values.
+ // If we don't use such protection we are able to place null
+ // to these fields and save such fields into DB even if DB has
+ // default values for these fields.
+ this.name = "";
+ this.mlAppName = "";
+ this.mlAppAdminId = "";
+ this.username = "";
+ this.appPassword = "";
+ this.open = new Boolean(false);
+ this.enabled = new Boolean(true);
+ this.uebTopicName = "";
+ this.uebKey = "";
+ this.uebSecret = "";
+ this.appType = 1;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ if (StringUtils.isEmpty(name)) {
+ name = "";
+ }
+ this.name = name;
+ }
+
+ public String getImageUrl() {
+ return imageUrl;
+ }
+
+ public void setImageUrl(String imageUrl) {
+ this.imageUrl = imageUrl;
+ }
+
+ public byte[] getThumbnail() {
+ return this.thumbnail;
+ }
+
+ public void setThumbnail(byte[] thumbnail) {
+ this.thumbnail = thumbnail;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getNotes() {
+ return notes;
+ }
+
+ public void setNotes(String notes) {
+ this.notes = notes;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public String getAlternateUrl() {
+ return alternateUrl;
+ }
+
+ public void setAlternateUrl(String alternateUrl) {
+ this.alternateUrl = alternateUrl;
+ }
+
+ public String getAppRestEndpoint() {
+ return appRestEndpoint;
+ }
+
+ public void setAppRestEndpoint(String appRestEndpoint) {
+ this.appRestEndpoint = appRestEndpoint;
+ }
+
+ public String getMlAppName() {
+ return mlAppName;
+ }
+
+ public void setMlAppName(String mlAppName) {
+ if (StringUtils.isEmpty(mlAppName)) {
+ mlAppName = "";
+ }
+ this.mlAppName = mlAppName;
+ }
+
+ public String getMlAppAdminId() {
+ return mlAppAdminId;
+ }
+
+ public void setMlAppAdminId(String mlAppAdminId) {
+ if (StringUtils.isEmpty(mlAppAdminId)) {
+ mlAppAdminId = "";
+ }
+ this.mlAppAdminId = mlAppAdminId;
+ }
+
+ public Long getMotsId() {
+ return motsId;
+ }
+
+ public void setMotsId(Long motsId) {
+ this.motsId = motsId;
+ }
+
+ public String getUsername() {
+ return username;
+ }
+
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ public String getAppPassword() {
+ return appPassword;
+ }
+
+ public void setAppPassword(String appPassword) {
+ if (StringUtils.isEmpty(appPassword)) {
+ appPassword = "";
+ }
+ this.appPassword = appPassword;
+ }
+
+ public Boolean getOpen() {
+ return open;
+ }
+
+ public void setOpen(Boolean open) {
+ if (open == null) {
+ open = new Boolean(false);
+ }
+ this.open = open;
+ }
+
+ public Boolean getEnabled() {
+ return enabled;
+ }
+
+ public void setEnabled(Boolean enabled) {
+ if (enabled == null) {
+ enabled = new Boolean(true);
+ }
+ this.enabled = enabled;
+ }
+
+ public Integer getAppType() {
+ return appType;
+ }
+
+ public void setAppType(Integer appType) {
+ if (appType == null) {
+ appType = new Integer(1);
+ }
+ this.appType = appType;
+ }
+
+ public void setRestrictedApp(Boolean restrictedApp) {
+ Integer result = 1;
+ if (restrictedApp) {
+ result = 2;
+ }
+ this.appType = result;
+ }
+
+ public Boolean isRestrictedApp() {
+ return (this.appType == 2 ? true : false);
+ }
+
+ /*
+ public SortedSet<Widget> getWidgets() {
+ return widgets;
+ }
+
+ public void setWidgets(SortedSet<Widget> widgets) {
+ this.widgets = widgets;
+ }
+
+ public void addWidget(Widget widget) {
+ this.widgets.add(widget);
+ }
+
+ public void removeWidget(Long widgetId) {
+ for (Widget widget: widgets) {
+ if (widget.getId().equals(widgetId)) {
+ widgets.remove(widget);
+ break;
+ }
+ }
+ }
+ */
+
+ public int compareTo(Object obj) {
+ Long c1 = getId();
+ Long c2 = ((EPApp) obj).getId();
+
+ return c1.compareTo(c2);
+ }
+
+ public String getUebTopicName() {
+ return this.uebTopicName;
+ }
+
+ public void setUebTopicName(String topicName) {
+ if (StringUtils.isEmpty(topicName)) {
+ this.uebTopicName = "";
+ }
+ this.uebTopicName = topicName;
+ }
+
+ public String getUebKey() {
+ return this.uebKey;
+ }
+
+ public void setUebKey(String uebKey) {
+ if (StringUtils.isEmpty(uebKey)) {
+ this.uebKey = "";
+ }
+ this.uebKey = uebKey;
+ }
+
+ public String getUebSecret() {
+ return this.uebSecret;
+ }
+
+ public void setUebSecret(String uebSecret) {
+ if (StringUtils.isEmpty(uebSecret)) {
+ this.uebSecret = "";
+ }
+ this.uebSecret = uebSecret;
+ }
+
+ public AppContactUs getContactUs() {
+ return contactUs;
+ }
+
+ public void setContactUs(AppContactUs contactUs) {
+ this.contactUs = contactUs;
+ }
+
+ @Override
+ public String toString() {
+ String str = "["+getId()+":"+getName()+"]";
+ return str;
+ }
+
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/EPRole.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/EPRole.java
new file mode 100644
index 00000000..db440897
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/EPRole.java
@@ -0,0 +1,204 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.domain;
+
+import java.util.Iterator;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+import org.openecomp.portalsdk.core.domain.RoleFunction;
+import org.openecomp.portalsdk.core.domain.support.DomainVo;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+
+public class EPRole extends DomainVo {
+
+ private static final long serialVersionUID = 1L;
+ private String name;
+ private boolean active;
+ private Integer priority;
+
+ // ECOMP will identify the specific remote application role id by appID;appRoleId among all the application roles it persists.
+ private Long appId; // used by ECOMP only
+ private Long appRoleId; // used by ECOMP only
+
+ private SortedSet<RoleFunction> roleFunctions = new TreeSet<RoleFunction>();
+
+ private SortedSet<EPRole> childRoles = new TreeSet<EPRole>();
+
+ @JsonIgnore
+ private SortedSet<EPRole> parentRoles = new TreeSet<EPRole>();
+
+ public EPRole() {}
+
+ public String getName() {
+ return name;
+ }
+
+ public boolean getActive() {
+ return active;
+ }
+
+ public SortedSet<RoleFunction> getRoleFunctions() {
+ return roleFunctions;
+ }
+
+ public Integer getPriority() {
+ return priority;
+ }
+
+ public SortedSet<EPRole> getChildRoles() {
+ return childRoles;
+ }
+
+ public SortedSet<EPRole> getParentRoles() {
+ return parentRoles;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void setActive(boolean active) {
+ this.active = active;
+ }
+
+ public void setRoleFunctions(SortedSet<RoleFunction> roleFunctions) {
+ this.roleFunctions = roleFunctions;
+ }
+
+ public void setPriority(Integer priority) {
+ this.priority = priority;
+ }
+
+ public void setChildRoles(SortedSet<EPRole> childRoles) {
+ this.childRoles = childRoles;
+ }
+
+ public void setParentRoles(SortedSet<EPRole> parentRoles) {
+ this.parentRoles = parentRoles;
+ }
+
+ public void addRoleFunction(RoleFunction roleFunction) {
+ this.roleFunctions.add(roleFunction);
+ }
+
+ public void addChildRole(EPRole role) {
+ this.childRoles.add(role);
+ }
+
+ public void addParentRole(EPRole role) {
+ this.parentRoles.add(role);
+ }
+
+ public String getEditUrl() {
+ return "/role.htm?role_id=" + getId();
+ }
+
+ public String getToggleActiveImage() {
+ return "/static/fusion/images/" + (getActive() ? "active.png" : "inactive.png" );
+ }
+
+ public String getToggleActiveAltText() {
+ return getActive() ? "Click to Deactivate Role" : "Click to Activate Role";
+ }
+
+ public void removeChildRole(Long roleId) {
+ Iterator<EPRole> i = this.childRoles.iterator();
+
+ while (i.hasNext()) {
+ EPRole childRole = (EPRole)i.next();
+ if (childRole.getId().equals(roleId)) {
+ this.childRoles.remove(childRole);
+ break;
+ }
+ }
+ }
+
+ public void removeParentRole(Long roleId) {
+ Iterator<EPRole> i = this.parentRoles.iterator();
+
+ while (i.hasNext()) {
+ EPRole parentRole = (EPRole)i.next();
+ if (parentRole.getId().equals(roleId)) {
+ this.parentRoles.remove(parentRole);
+ break;
+ }
+ }
+ }
+
+ public void removeRoleFunction(String roleFunctionCd) {
+ Iterator<RoleFunction> i = this.roleFunctions.iterator();
+
+ while (i.hasNext()) {
+ RoleFunction roleFunction = (RoleFunction)i.next();
+ if (roleFunction.getCode().equals(roleFunctionCd)) {
+ this.roleFunctions.remove(roleFunction);
+ break;
+ }
+ }
+ }
+
+ public int compareTo(Object obj){
+ EPRole other = (EPRole)obj;
+
+ if(this.appId == null)
+ if(other.getAppId() == null)
+ return compareByName(other); //equal
+ else
+ return -1;
+ else // this.appId != null
+ if(other.getAppId() == null)
+ return 1; // appId != null, but others is null
+ else{
+ int appIdCompareResult = appId.compareTo(other.getAppId());
+ return appIdCompareResult == 0? compareByName(other) : appIdCompareResult;
+ }
+ }
+
+ private int compareByName(EPRole other) {
+ String c1 = getName();
+ String c2 = other.getName();
+
+ return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2);
+ }
+
+ public Long getAppId() {
+ return appId;
+ }
+
+ public void setAppId(Long appId) {
+ this.appId = appId;
+ }
+
+ public Long getAppRoleId() {
+ return appRoleId;
+ }
+
+ public void setAppRoleId(Long appRoleId) {
+ this.appRoleId = appRoleId;
+ }
+
+ @Override
+ public String toString() {
+ String str = "[id: "+getId()+", appId: "+appId+", appRoleId: "+appRoleId+"]";
+ return str;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/EPUser.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/EPUser.java
new file mode 100644
index 00000000..d70daa9b
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/EPUser.java
@@ -0,0 +1,602 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.domain;
+
+import java.util.Date;
+import java.util.Iterator;
+import java.util.SortedSet;
+import java.util.TreeSet;
+
+import org.openecomp.portalsdk.core.domain.support.DomainVo;
+
+public class EPUser extends DomainVo {
+
+ private Long orgId;
+ private Long managerId;
+ private String firstName;
+ private String middleInitial;
+ private String lastName;
+ private String phone;
+ private String fax;
+ private String cellular;
+ private String email;
+ private Long addressId;
+ private String alertMethodCd;
+ private String hrid;
+ private String orgUserId;
+ private String orgCode;
+ private String address1;
+ private String address2;
+ private String city;
+ private String state;
+ private String zipCode;
+ private String country;
+ private String orgManagerUserId;
+ private String locationClli;
+ private String businessCountryCode;
+ private String businessCountryName;
+ private String businessUnit;
+ private String businessUnitName;
+ private String department;
+ private String departmentName;
+ private String companyCode;
+ private String company;
+ private String zipCodeSuffix;
+ private String jobTitle;
+ private String commandChain;
+ private String siloStatus;
+ private String costCenter;
+ private String financialLocCode;
+
+
+
+ private String loginId;
+ private String loginPwd;
+ private Date lastLoginDate;
+ private boolean active;
+ private boolean internal;
+ private Long selectedProfileId;
+ private Long timeZoneId;
+ private boolean online;
+ private String chatId;
+
+ private static final long serialVersionUID = 1L;
+
+ private static final long ECOMP_PORTAL_ID = 1L;
+ private static final String ECOMP_PORTAL_NAME = "ECOMP";
+ private boolean isGuest = false;
+
+ private SortedSet<EPUserApp> userApps = new TreeSet<EPUserApp>();
+ private SortedSet<EPRole> pseudoRoles = new TreeSet<EPRole>();
+
+ public EPUser() {}
+
+ public Long getAddressId() {
+ return addressId;
+ }
+
+ public String getAlertMethodCd() {
+ return alertMethodCd;
+ }
+
+ public String getCellular() {
+ return cellular;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public String getFax() {
+ return fax;
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public String getHrid() {
+ return hrid;
+ }
+
+ public Date getLastLoginDate() {
+ return lastLoginDate;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public String getFullName() {
+ return getFirstName() + " " + getLastName();
+ }
+
+ public String getLoginId() {
+ return loginId;
+ }
+
+ public String getLoginPwd() {
+ return loginPwd;
+ }
+
+ public Long getManagerId() {
+ return managerId;
+ }
+
+ public String getMiddleInitial() {
+ return middleInitial;
+ }
+
+ public String getOrgCode() {
+ return orgCode;
+ }
+
+ public Long getOrgId() {
+ return orgId;
+ }
+
+ public String getPhone() {
+ return phone;
+ }
+
+ public String getOrgUserId() {
+ return orgUserId;
+ }
+
+ public boolean getActive() {
+ return active;
+ }
+
+ public boolean getInternal() {
+ return internal;
+ }
+
+ public String getAddress1() {
+ return address1;
+ }
+
+ public String getAddress2() {
+ return address2;
+ }
+
+ public String getCity() {
+ return city;
+ }
+
+ public String getCountry() {
+ return country;
+ }
+
+ public String getState() {
+ return state;
+ }
+
+ public String getZipCode() {
+ return zipCode;
+ }
+
+ public String getBusinessCountryCode() {
+ return businessCountryCode;
+ }
+
+ public String getCommandChain() {
+ return commandChain;
+ }
+
+ public String getCompany() {
+ return company;
+ }
+
+ public String getCompanyCode() {
+ return companyCode;
+ }
+
+ public String getDepartment() {
+ return department;
+ }
+
+ public String getJobTitle() {
+ return jobTitle;
+ }
+
+ public String getLocationClli() {
+ return locationClli;
+ }
+
+ public String getOrgManagerUserId() {
+ return orgManagerUserId;
+ }
+
+ public String getZipCodeSuffix() {
+ return zipCodeSuffix;
+ }
+
+ public String getBusinessCountryName() {
+ return businessCountryName;
+ }
+
+ public Long getSelectedProfileId() {
+ return selectedProfileId;
+ }
+
+ public void setAddressId(Long addressId) {
+ this.addressId = addressId;
+ }
+
+ public void setAlertMethodCd(String alertMethodCd) {
+ this.alertMethodCd = alertMethodCd;
+ }
+
+ public void setCellular(String cellular) {
+ this.cellular = cellular;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+ public void setFax(String fax) {
+ this.fax = fax;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public void setHrid(String hrid) {
+ this.hrid = hrid;
+ }
+
+ public void setLastLoginDate(Date lastLoginDate) {
+ this.lastLoginDate = lastLoginDate;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public void setLoginId(String loginId) {
+ this.loginId = loginId;
+ }
+
+ public void setLoginPwd(String loginPwd) {
+ this.loginPwd = loginPwd;
+ }
+
+ public void setManagerId(Long managerId) {
+ this.managerId = managerId;
+ }
+
+ public void setMiddleInitial(String middleInitial) {
+ this.middleInitial = middleInitial;
+ }
+
+ public void setOrgCode(String orgCode) {
+ this.orgCode = orgCode;
+ }
+
+ public void setOrgId(Long orgId) {
+ this.orgId = orgId;
+ }
+
+ public void setPhone(String phone) {
+ this.phone = phone;
+ }
+
+ public void setOrgUserId(String orgUserId) {
+ this.orgUserId = orgUserId;
+ }
+
+ public void setActive(boolean active) {
+ this.active = active;
+ }
+
+ public void setInternal(boolean internal) {
+ this.internal = internal;
+ }
+
+ public void setAddress1(String address1) {
+ this.address1 = address1;
+ }
+
+ public void setAddress2(String address2) {
+ this.address2 = address2;
+ }
+
+ public void setCity(String city) {
+ this.city = city;
+ }
+
+ public void setCountry(String country) {
+ this.country = country;
+ }
+
+ public void setState(String state) {
+ this.state = state;
+ }
+
+ public void setZipCode(String zipCode) {
+ this.zipCode = zipCode;
+ }
+
+ public void setBusinessCountryCode(String businessCountryCode) {
+ this.businessCountryCode = businessCountryCode;
+ }
+
+ public void setCommandChain(String commandChain) {
+ this.commandChain = commandChain;
+ }
+
+ public void setCompany(String company) {
+ this.company = company;
+ }
+
+ public void setCompanyCode(String companyCode) {
+ this.companyCode = companyCode;
+ }
+
+ public void setDepartment(String department) {
+ this.department = department;
+ }
+
+ public void setJobTitle(String jobTitle) {
+ this.jobTitle = jobTitle;
+ }
+
+ public void setLocationClli(String locationClli) {
+ this.locationClli = locationClli;
+ }
+
+ public void setOrgManagerUserId(String orgManagerUserId) {
+ this.orgManagerUserId = orgManagerUserId;
+ }
+
+ public void setZipCodeSuffix(String zipCodeSuffix) {
+ this.zipCodeSuffix = zipCodeSuffix;
+ }
+
+ public void setBusinessCountryName(String businessCountryName) {
+ this.businessCountryName = businessCountryName;
+ }
+
+ public SortedSet<EPRole> getPseudoRoles() {
+ return pseudoRoles;
+ }
+
+ public void setPseudoRoles(SortedSet<EPRole> pseudoRoles) {
+ this.pseudoRoles = pseudoRoles;
+ }
+
+ public void setSelectedProfileId(Long selectedProfileId) {
+ this.selectedProfileId = selectedProfileId;
+ }
+
+ public Long getTimeZoneId() {
+ return timeZoneId;
+ }
+
+ public void setTimeZoneId(Long timeZoneId) {
+ this.timeZoneId = timeZoneId;
+ }
+
+ public String getBusinessUnit() {
+ return businessUnit;
+ }
+
+ public void setBusinessUnit(String businessUnit) {
+ this.businessUnit = businessUnit;
+ }
+
+ public String getSiloStatus() {
+ return siloStatus;
+ }
+
+ public void setSiloStatus(String siloStatus) {
+ this.siloStatus = siloStatus;
+ }
+
+ public String getCostCenter() {
+ return costCenter;
+ }
+
+ public void setCostCenter(String costCenter) {
+ this.costCenter = costCenter;
+ }
+
+ public String getFinancialLocCode() {
+ return financialLocCode;
+ }
+
+ public void setFinancialLocCode(String financialLocCode) {
+ this.financialLocCode = financialLocCode;
+ }
+
+ public String getBusinessUnitName() {
+ return businessUnitName;
+ }
+
+ public void setBusinessUnitName(String businessUnitName) {
+ this.businessUnitName = businessUnitName;
+ }
+
+ public String getDepartmentName() {
+ return departmentName;
+ }
+
+ public void setDepartmentName(String departmentName) {
+ this.departmentName = departmentName;
+ }
+
+ public int compareTo(Object obj){
+ EPUser user = (EPUser)obj;
+
+ String c1 = getLastName() + getFirstName() + getMiddleInitial();
+ String c2 = user.getLastName() + user.getFirstName() + user.getMiddleInitial();
+
+ return c1.compareTo(c2);
+ }
+
+ public boolean isOnline() {
+ return online;
+ }
+
+ public void setOnline(boolean online) {
+ this.online = online;
+ }
+
+ public String getChatId() {
+ return chatId;
+ }
+
+ public void setChatId(String chatId) {
+ this.chatId = chatId;
+ }
+
+
+ public void setPseudoEPRoles(SortedSet<EPRole> pseudoRoles) {
+ this.pseudoRoles = pseudoRoles;
+ }
+
+ public SortedSet<EPUserApp> getEPUserApps() {
+ return userApps;
+ }
+
+ public void setEPUserApps(SortedSet<EPUserApp> userApps) {
+ this.userApps = userApps;
+ }
+
+ public void addUserApp(EPUserApp userApp) {
+ userApps.add(userApp);
+ }
+
+ public void addAppRoles(EPApp app, SortedSet<EPRole> roles) {
+ if (roles != null) {
+ // add all
+ SortedSet<EPUserApp> userApps = new TreeSet<EPUserApp>();
+ // this.userApps.removeAll(this.userApps);
+ Iterator<EPRole> itr = roles.iterator();
+ while (itr.hasNext()) {
+ EPRole role = (EPRole) itr.next();
+ EPUserApp userApp = new EPUserApp();
+ userApp.setUserId(this.id);
+ userApp.setApp(app);
+ userApp.setRole(role);
+ userApps.add(userApp);
+ }
+ setEPUserApps(userApps);
+ } else {
+ // remove all
+ setEPUserApps(null);
+ }
+
+ }
+
+ public SortedSet<EPRole> getAppEPRoles(EPApp app) {
+ SortedSet<EPRole> roles = new TreeSet<EPRole>();
+ SortedSet<EPUserApp> apps = getEPUserApps();
+ Iterator<EPUserApp> appsItr = apps.iterator();
+ EPUserApp userApp = null;
+ // getting default app
+ while (appsItr.hasNext()) {
+ EPUserApp tempUserApp = (EPUserApp) appsItr.next();
+ if (tempUserApp.getApp().getId().equals(app)) {
+ userApp = tempUserApp;
+ roles.add((EPRole) userApp.getRole());
+ }
+ }
+ return roles;
+ }
+
+ /**
+ * Attention! Not for use in ECOMP
+ */
+ public SortedSet<EPRole> getAppRoles(EPApp app) {
+ SortedSet<EPRole> roles = new TreeSet<EPRole>();
+ SortedSet<EPUserApp> apps = getEPUserApps();
+ Iterator<EPUserApp> appsItr = apps.iterator();
+ EPUserApp userApp = null;
+ // getting default app
+ while (appsItr.hasNext()) {
+ EPUserApp tempUserApp = (EPUserApp) appsItr.next();
+ if (tempUserApp.getApp().getId().equals(app.getId())) {
+ userApp = tempUserApp;
+ roles.add((EPRole) userApp.getRole());
+ }
+ }
+ return roles;
+ }
+
+ /**
+ * Attention! Not for use in ECOMP
+ */
+ public SortedSet<EPRole> getEPRoles() {
+ EPApp app = new EPApp();
+ app.setId(new Long(ECOMP_PORTAL_ID));
+ app.setName(ECOMP_PORTAL_NAME);
+ return getAppEPRoles(app);
+ }
+
+ /**
+ * Attention! Not for use in ECOMP
+ */
+ public void setEPRoles(SortedSet<EPRole> roles) {
+ EPApp app = new EPApp();
+ app.setId(new Long(ECOMP_PORTAL_ID));
+ app.setName(ECOMP_PORTAL_NAME);
+ addAppRoles(app, roles);
+ }
+
+ /**
+ * Attention! Not for use in ECOMP
+ */
+ public void removeEPRole(Long roleId) {
+ SortedSet<EPUserApp> apps = getEPUserApps();
+ Iterator<EPUserApp> appsItr = apps.iterator();
+ // getting default app
+ while (appsItr.hasNext()) {
+ EPUserApp tempUserApp = (EPUserApp) appsItr.next();
+ if (tempUserApp.equals(new Long(ECOMP_PORTAL_ID)) && tempUserApp.getRole().getId().equals(roleId)) {
+ appsItr.remove();
+ }
+ }
+ }
+
+ /**
+ * Attention! Not for use in ECOMP
+ */
+ public void addEPRole(EPRole role) {
+ if (role != null) {
+ SortedSet<EPRole> roles = getEPRoles();
+ if (roles == null) {
+ roles = new TreeSet<EPRole>();
+ }
+ roles.add(role);
+ setEPRoles(roles);
+ }
+ }
+
+ public boolean isGuest() {
+ return isGuest;
+ }
+
+ public void setGuest(boolean isGuest) {
+ this.isGuest = isGuest;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/EPUserApp.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/EPUserApp.java
new file mode 100644
index 00000000..f4647fca
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/EPUserApp.java
@@ -0,0 +1,119 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.domain;
+
+
+@SuppressWarnings("rawtypes")
+public class EPUserApp implements java.io.Serializable, Comparable {
+
+ private static final long serialVersionUID = 1L;
+
+ private Long userId;
+ private EPApp app;
+ private EPRole role;
+ private Short priority;
+
+ public EPUserApp() {
+ }
+
+ public Long getAppId() {
+ return this.getApp().getId();
+ }
+
+ public Long getRoleId() {
+ return (role == null) ? null : role.getId();
+ }
+
+ public Long getAppRoleId() {
+ return (role.getAppRoleId() == null) ? null : role.getAppRoleId();
+ }
+
+ @Override
+ public String toString() {
+ String str = "[u: "+getUserId()+"; a: "+getAppId()+", r: "+getRoleId()+"; appRoleId: "+getAppRoleId()+"]";
+ return str;
+ }
+
+ public Long getUserId() {
+ return userId;
+ }
+
+ public void setUserId(Long id) {
+ this.userId = id;
+ }
+
+ public EPApp getApp() {
+ return app;
+ }
+
+ public void setApp(EPApp app) {
+ this.app = app;
+ }
+
+ public EPRole getRole() {
+ return role;
+ }
+
+ public void setRole(EPRole role) {
+ this.role = role;
+ }
+
+ public Short getPriority() {
+ return this.priority;
+ }
+
+ public void setPriority(Short priority) {
+ this.priority = priority;
+ }
+
+ public boolean equals(Object other) {
+ if ((this == other))
+ return true;
+ if ((other == null))
+ return false;
+ if (!(other instanceof EPUserApp))
+ return false;
+ EPUserApp castOther = (EPUserApp) other;
+
+ return (this.getUserId().equals(castOther.getUserId()))
+ && (this.getApp().getId().equals(castOther.getApp().getId()))
+ && (this.getRole().getId().equals(castOther.getRole().getId()))
+ && ((this.priority==null && castOther.getPriority()==null) || this.getPriority().equals(castOther.getPriority()));
+ }
+
+ public int hashCode() {
+ int result = 17;
+
+ result = 37 * result + (int) (this.getUserId()==null ? 0 : this.getUserId().intValue());
+ result = 37 * result + (int) (this.getApp().getId()==null ? 0 : this.getApp().getId().intValue());
+ result = 37 * result + (int) (this.getRole().getId()==null ? 0 : this.getRole().getId().intValue());
+ result = 37 * result + (int) (this.priority==null ? 0 : this.priority);
+ return result;
+ }
+
+ public int compareTo(Object other){
+ EPUserApp castOther = (EPUserApp) other;
+
+ Long c1 = (this.getUserId()==null ? 0 : this.getUserId()) + (this.getApp()==null||this.getApp().getId()==null ? 0 : this.getApp().getId()) + (this.getRole()==null||this.getRole().getId()==null ? 0 : this.getRole().getId()) + (this.priority==null ? 0 : this.priority);
+ Long c2 = (castOther.getUserId()==null ? 0 : castOther.getUserId()) + (castOther.getApp()==null||castOther.getApp().getId()==null ? 0 : castOther.getApp().getId()) + (castOther.getRole()==null||castOther.getRole().getId()==null ? 0 : castOther.getRole().getId()) + (castOther.priority==null ? 0 : castOther.priority);
+
+ return c1.compareTo(c2);
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/EcompApp.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/EcompApp.java
new file mode 100644
index 00000000..2564a178
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/EcompApp.java
@@ -0,0 +1,143 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.domain;
+
+public class EcompApp {
+
+ protected Long id;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ private String name;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ private String imageUrl;
+
+ public String getImageUrl() {
+ return imageUrl;
+ }
+
+ public void setImageUrl(String imageUrl) {
+ this.imageUrl = imageUrl;
+ }
+
+ private String description;
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ private String notes;
+
+ public String getNotes() {
+ return notes;
+ }
+
+ public void setNotes(String notes) {
+ this.notes = notes;
+ }
+
+ private String url;
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ private String alternateUrl;
+
+ public String getAlternateUrl() {
+ return alternateUrl;
+ }
+
+ public void setAlternateUrl(String alternateUrl) {
+ this.alternateUrl = alternateUrl;
+ }
+
+ private String uebTopicName;
+
+ public String getUebTopicName() {
+ return uebTopicName;
+ }
+
+ public void setUebTopicName(String topicName) {
+ this.uebTopicName = topicName;
+ }
+
+ private String uebKey;
+
+ public String getUebKey() {
+ return uebKey;
+ }
+
+ public void setUebKey(String uebKey) {
+ this.uebKey = uebKey;
+ }
+
+ private String uebSecret;
+
+ public String getUebSecret() {
+ return uebSecret;
+ }
+
+ public void setUebSecret(String secret) {
+ this.uebSecret = secret;
+ }
+
+ private Boolean enabled;
+
+ public Boolean isEnabled() {
+ return enabled;
+ }
+
+ public void setEnabled(Boolean enable) {
+ this.enabled = enable;
+ }
+
+ private Boolean restrictedApp;
+
+ public Boolean isRestrictedApp() {
+ return restrictedApp;
+ }
+
+ public void setRestrictedApp(Boolean restrictedApp) {
+ this.restrictedApp = restrictedApp;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/GetAccessResult.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/GetAccessResult.java
new file mode 100644
index 00000000..a7dab37e
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/GetAccessResult.java
@@ -0,0 +1,70 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.domain;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.IdClass;
+
+@Entity
+@IdClass(GetAccessResultId.class)
+public class GetAccessResult {
+
+ @Id
+ @Column(name="ecomp_function")
+ private String ecompFunction;
+
+ @Id
+ @Column(name="app_name")
+ private String appName;
+
+ @Column(name="app_mots_id",nullable=true)
+ private Integer appMotsId;
+
+ @Id
+ @Column(name="role_name")
+ private String roleName;
+
+ public String getEcompFunction() {
+ return ecompFunction;
+ }
+ public void setEcompFunction(String ecompFunction) {
+ this.ecompFunction = ecompFunction;
+ }
+ public String getAppName() {
+ return appName;
+ }
+ public void setAppName(String appName) {
+ this.appName = appName;
+ }
+ public Integer getAppMotsId() {
+ return appMotsId;
+ }
+ public void setAppMotsId(Integer appMotsId) {
+ this.appMotsId = appMotsId;
+ }
+ public String getRoleName() {
+ return roleName;
+ }
+ public void setRoleName(String roleName) {
+ this.roleName = roleName;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/GetAccessResultId.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/GetAccessResultId.java
new file mode 100644
index 00000000..83abda54
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/GetAccessResultId.java
@@ -0,0 +1,64 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.domain;
+
+import java.io.Serializable;
+
+import javax.persistence.Column;
+import javax.persistence.Id;
+
+public class GetAccessResultId implements Serializable{
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @Column(name="ecomp_function")
+ private String ecompFunction;
+
+ @Id
+ @Column(name="app_name")
+ private String appName;
+
+ @Id
+ @Column(name="role_name")
+ private String roleName;
+
+ public String getEcompFunction() {
+ return ecompFunction;
+ }
+ public void setEcompFunction(String ecompFunction) {
+ this.ecompFunction = ecompFunction;
+ }
+ public String getAppName() {
+ return appName;
+ }
+ public void setAppName(String appName) {
+ this.appName = appName;
+ }
+ public String getRoleName() {
+ return roleName;
+ }
+ public void setRoleName(String roleName) {
+ this.roleName = roleName;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/PersUserAppSelection.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/PersUserAppSelection.java
new file mode 100644
index 00000000..4288d920
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/PersUserAppSelection.java
@@ -0,0 +1,79 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.domain;
+
+
+import org.openecomp.portalsdk.core.domain.support.DomainVo;
+
+/**
+ * Models a row in the table with personalization of user app selections.
+ */
+public class PersUserAppSelection extends DomainVo {
+
+ private static final long serialVersionUID = 1545308654500121206L;
+
+ private Long userId;
+
+ private Long appId;
+
+ private String statusCode;
+
+ public PersUserAppSelection() {}
+
+ /**
+ * Convenience constructor
+ *
+ * @param id
+ * @param userId
+ * @param appId
+ * @param statusCode
+ */
+ public PersUserAppSelection(final Long id, final Long userId, final Long appId, final String statusCode) {
+ super.id = id;
+ this.userId = userId;
+ this.appId = appId;
+ this.statusCode = statusCode;
+ }
+
+ public Long getAppId() {
+ return appId;
+ }
+
+ public void setAppId(Long appId) {
+ this.appId = appId;
+ }
+
+ public Long getUserId() {
+ return userId;
+ }
+
+ public void setUserId(Long userId) {
+ this.userId = userId;
+ }
+
+ public String getStatusCode() {
+ return statusCode;
+ }
+
+ public void setStatusCode(String statusCode) {
+ this.statusCode = statusCode;
+ }
+
+} \ No newline at end of file
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/SharedContext.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/SharedContext.java
new file mode 100644
index 00000000..c68f1b8b
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/SharedContext.java
@@ -0,0 +1,161 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.domain;
+
+import java.util.Date;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+import org.openecomp.portalsdk.core.domain.support.DomainVo;
+
+/**
+ * A shared context is a key-value pair in a session. All shared-context objects
+ * should be dropped when a session is destroyed. Because there's always a
+ * chance of missing that event, this object notes its creation time so that it
+ * can be expired after a suitable time interval.
+ */
+@Entity
+@Table(name = "fn_shared_context")
+public class SharedContext extends DomainVo {
+
+ // generated
+ private static final long serialVersionUID = 7287469622586677888L;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private Long id;
+ private Date create_time;
+ private String context_id;
+ private String ckey;
+ private String cvalue;
+
+ /**
+ * Mandatory no-argument constructor
+ */
+ public SharedContext() {
+ }
+
+ /**
+ * Convenience constructor. The database ID and creation timestamp are
+ * populated when the object is added to the database.
+ */
+ public SharedContext(final String contextId, final String key, final String value) {
+ this.context_id = contextId;
+ this.ckey = key;
+ this.cvalue = value;
+ }
+
+ /**
+ * Gets the database row ID.
+ *
+ * @return Database row ID
+ */
+ public Long getId() {
+ return id;
+ }
+
+ /**
+ * Sets the database row ID.
+ *
+ * @param id
+ */
+ public void setId(final Long id) {
+ this.id = id;
+ }
+
+ /**
+ * Gets the creation time
+ *
+ * @return Creation time as a Date
+ */
+ public Date getCreate_time() {
+ return create_time;
+ }
+
+ /**
+ * Sets the creation time
+ *
+ * @param create_time
+ */
+ public void setCreate_time(final Date create_time) {
+ this.create_time = create_time;
+ }
+
+ /**
+ * Gets the context ID
+ *
+ * @return Context ID
+ */
+ public String getContext_id() {
+ return context_id;
+ }
+
+ /**
+ * Sets the context ID
+ *
+ * @param context_id
+ */
+ public void setContext_id(final String context_id) {
+ this.context_id = context_id;
+ }
+
+ /**
+ * Gets the key of the key-value pair. Called ckey because "key" is a
+ * reserved word in Mysql.
+ *
+ * @return The key
+ */
+ public String getCkey() {
+ return ckey;
+ }
+
+ /**
+ * Sets the key of the key-value pair.
+ *
+ * @param ckey
+ */
+ public void setCkey(final String ckey) {
+ this.ckey = ckey;
+ }
+
+ /**
+ * Gets the value of the key-value pair. Called cvalue because "value" is a
+ * reserved word in Mysql.
+ *
+ * @return
+ */
+ public String getCvalue() {
+ return cvalue;
+ }
+
+ /**
+ * Sets the value of the key-value pair.
+ *
+ * @param cvalue
+ */
+ public void setCvalue(final String cvalue) {
+ this.cvalue = cvalue;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/UserIdRoleId.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/UserIdRoleId.java
new file mode 100644
index 00000000..cce4cb23
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/UserIdRoleId.java
@@ -0,0 +1,77 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.domain;
+
+import java.io.Serializable;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+@Entity
+public class UserIdRoleId implements Serializable{
+
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @Column(name="USER_ID")
+ private String user_Id;
+
+ @Column(name="ROLE_ID")
+ private String roleId;
+
+ @Column(name="ORG_USER_ID")
+ private String orgUserId;
+
+ @Column(name="APP_ID")
+ private String appId;
+
+ public String getUser_Id() {
+ return user_Id;
+ }
+
+ public void setUser_Id(String id) {
+ this.user_Id = id;
+ }
+
+ public String getRoleId() {
+ return roleId;
+ }
+
+ public void setRoleId(String roleId) {
+ this.roleId = roleId;
+ }
+
+ public String getAppId() {
+ return appId;
+ }
+
+ public void setAppId(String appId) {
+ this.appId = appId;
+ }
+
+ public String getOrgUserId() {
+ return orgUserId;
+ }
+
+ public void setOrgUserId(String orgUserId) {
+ this.orgUserId = orgUserId;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/UserRole.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/UserRole.java
new file mode 100644
index 00000000..d0b5df92
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/UserRole.java
@@ -0,0 +1,91 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.domain;
+
+import java.io.Serializable;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+@Entity
+public class UserRole implements Serializable{
+ private static final long serialVersionUID = 1L;
+
+
+ @Id
+ @Column(name="USER_ID")
+ private Long user_Id;
+
+ @Id
+ @Column(name="ROLE_ID")
+ private Long roleId;
+
+ @Column(name="ORG_USER_ID")
+ private String orgUserId;
+
+
+ @Column(name="FIRST_NAME")
+ private String firstName;
+
+ @Column(name="LAST_NAME")
+ private String lastName;
+
+
+ @Column(name="ROLE_NAME")
+ private String roleName;
+
+ public String getFirstName() {
+ return firstName;
+ }
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+ public String getLastName() {
+ return lastName;
+ }
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+ public String getOrgUserId() {
+ return orgUserId;
+ }
+ public void setOrgUserId(String orgUserId) {
+ this.orgUserId = orgUserId;
+ }
+ public String getRoleName() {
+ return roleName;
+ }
+ public void setRoleName(String roleName) {
+ this.roleName = roleName;
+ }
+ public Long getUser_Id() {
+ return user_Id;
+ }
+ public void setUser_Id(Long user_Id) {
+ this.user_Id = user_Id;
+ }
+ public Long getRoleId() {
+ return roleId;
+ }
+ public void setRoleId(Long roleId) {
+ this.roleId = roleId;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/UserRoles.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/UserRoles.java
new file mode 100644
index 00000000..60ee4321
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/UserRoles.java
@@ -0,0 +1,111 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.domain;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+
+public class UserRoles implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private static final HashMap<Long, String> rolesDictionary;
+
+ static {
+ rolesDictionary = new HashMap<Long, String>();
+ rolesDictionary.put(Long.valueOf(SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID)).longValue(), "superAdmin");
+ rolesDictionary.put(Long.valueOf(SystemProperties.getProperty(EPSystemProperties.ACCOUNT_ADMIN_ROLE_ID)).longValue(), "admin");
+ }
+
+ public UserRoles(UserRole user) {
+ setOrgUserId(user.getOrgUserId());
+ setFirstName(user.getFirstName());
+ setLastName(user.getLastName());
+ setGuestSession(user.getUser_Id()==-1 ? true : false);
+ addRole(user.getRoleId());
+ }
+
+ public void addRole(Long roleId) {
+ String normalizedRole = normalizeRole(roleId);
+ if (!getRoles().contains(normalizedRole)) {
+ this.roles.add(normalizedRole);
+ }
+ }
+
+ public static String normalizeRole(Long role) {
+ String roleTranslated = rolesDictionary.get(role);
+ return roleTranslated == null ? "user" : roleTranslated;
+ }
+
+ private String orgUserId;
+
+ private String firstName;
+
+ private String lastName;
+
+ private boolean guestSession;
+
+ // TODO: Make into set
+ private List<String> roles = new ArrayList<String>();
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public String getOrgUserId() {
+ return orgUserId;
+ }
+
+ public void setOrgUserId(String orgUserId) {
+ this.orgUserId = orgUserId;
+ }
+
+ public List<String> getRoles() {
+ return roles;
+ }
+
+ public void setRoles(List<String> roles) {
+ this.roles = roles;
+ }
+
+ public void setGuestSession(boolean guestSession) {
+ this.guestSession = guestSession;
+ }
+
+ public boolean getGuestSession() {
+ return this.guestSession;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/Widget.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/Widget.java
new file mode 100644
index 00000000..309b0c87
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/domain/Widget.java
@@ -0,0 +1,104 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.domain;
+
+import org.apache.commons.lang.StringUtils;
+import org.openecomp.portalsdk.core.domain.support.DomainVo;
+
+public class Widget extends DomainVo {
+
+ private static final long serialVersionUID = 1L;
+
+ private String name;
+
+ private Integer width;
+
+ private Integer height;
+
+ private String url;
+
+ private Long appId;
+
+ public Widget() {
+ // Attention!!!
+ // We set here all default values. We also place protection
+ // into setters for fields with default values.
+ // If we don't use such protection we are able to place null
+ // to these fields and save such fields into DB even if DB has
+ // default values for these fields.
+ this.name = "";
+ this.width = new Integer(0);
+ this.height = new Integer(0);
+ this.url = "";
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ if (StringUtils.isEmpty(name)) {
+ name = "";
+ }
+ this.name = name;
+ }
+
+ public Integer getWidth() {
+ return width;
+ }
+
+ public void setWidth(Integer width) {
+ if (width == null) {
+ width = new Integer(0);
+ }
+ this.width = width;
+ }
+
+ public Integer getHeight() {
+ return height;
+ }
+
+ public void setHeight(Integer height) {
+ if (height == null) {
+ height = new Integer(0);
+ }
+ this.height = height;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ if (StringUtils.isEmpty(url)) {
+ url = "";
+ }
+ this.url = url;
+ }
+
+ public Long getAppId() {
+ return appId;
+ }
+
+ public void setAppId(Long appId) {
+ this.appId = appId;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppCatalogItem.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppCatalogItem.java
new file mode 100644
index 00000000..e0f516d9
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppCatalogItem.java
@@ -0,0 +1,159 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.ecomp.model;
+
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+import org.openecomp.portalsdk.core.domain.support.DomainVo;
+import com.fasterxml.jackson.annotation.JsonInclude;
+
+/**
+ * This model of an application catalog entry has some EPApp fields plus
+ * additional fields to indicate access(ible) and select(ed) statuses.
+ */
+@Entity
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class AppCatalogItem extends DomainVo {
+
+ private static final long serialVersionUID = 6619663784935017846L;
+
+ @Id
+ private Long id;
+ private String name;
+ private String imageUrl;
+ private String description;
+ private String notes;
+ private String url;
+ private String alternateUrl;
+ private Boolean restricted;
+ private Boolean open;
+ private Boolean access;
+ private Boolean select;
+ private Boolean pending;
+
+ 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;
+ }
+
+ public String getImageUrl() {
+ return imageUrl;
+ }
+
+ public void setImageUrl(String imageUrl) {
+ this.imageUrl = imageUrl;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getNotes() {
+ return notes;
+ }
+
+ public void setNotes(String notes) {
+ this.notes = notes;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public String getAlternateUrl() {
+ return alternateUrl;
+ }
+
+ public void setAlternateUrl(String alternateUrl) {
+ this.alternateUrl = alternateUrl;
+ }
+
+ public Boolean getRestricted() {
+ return restricted;
+ }
+
+ public void setRestricted(Boolean restricted) {
+ this.restricted = restricted;
+ }
+
+ public Boolean getOpen() {
+ return open;
+ }
+
+ public void setOpen(Boolean open) {
+ this.open = open;
+ }
+
+ public Boolean getAccess() {
+ return access;
+ }
+
+ public void setAccess(Boolean access) {
+ this.access = access;
+ }
+
+ public Boolean getSelect() {
+ return select;
+ }
+
+ public void setSelect(Boolean select) {
+ this.select = select;
+ }
+
+ public Boolean getPending() {
+ return pending;
+ }
+
+ public void setPending(Boolean pending) {
+ this.pending = pending;
+ }
+
+ public static long getSerialversionuid() {
+ return serialVersionUID;
+ }
+
+ @Override
+ public String toString() {
+ return "AppCatalogItem [id=" + id + ", name=" + name + ", access=" + access + ", select=" + select
+ + ", pending=" + pending + "]";
+ }
+
+} \ No newline at end of file
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppCategoryFunctionsItem.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppCategoryFunctionsItem.java
new file mode 100644
index 00000000..16aca032
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppCategoryFunctionsItem.java
@@ -0,0 +1,84 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.ecomp.model;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+import org.openecomp.portalsdk.core.domain.support.DomainVo;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+
+/**
+ * Carries row information for the functional table on the Contact Us page.
+ */
+@Entity
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class AppCategoryFunctionsItem extends DomainVo {
+
+ private static final long serialVersionUID = -1573834082471206458L;
+
+ @Id
+ private String rowId;
+ private String appId;
+ private String application;
+ private String category;
+ private String functions;
+
+ public String getRowId() {
+ return rowId;
+ }
+
+ public void setRowId(String rowId) {
+ this.rowId = rowId;
+ }
+
+ public String getAppId() {
+ return appId;
+ }
+
+ public void setAppId(String appId) {
+ this.appId = appId;
+ }
+
+ public String getApplication() {
+ return application;
+ }
+
+ public void setApplication(String appName) {
+ this.application = appName;
+ }
+
+ public String getCategory() {
+ return category;
+ }
+
+ public void setCategory(String category) {
+ this.category = category;
+ }
+
+ public String getFunctions() {
+ return functions;
+ }
+
+ public void setFunctions(String functions) {
+ this.functions = functions;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppContactUsItem.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppContactUsItem.java
new file mode 100644
index 00000000..c8dd8f0c
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/AppContactUsItem.java
@@ -0,0 +1,104 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.ecomp.model;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+import org.openecomp.portalsdk.core.domain.support.DomainVo;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+
+/**
+ * Carries row information for the apps table on the Contact Us page.
+ */
+@Entity
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class AppContactUsItem extends DomainVo {
+
+ private static final long serialVersionUID = 6964210807573346262L;
+
+ @Id
+ private Long appId;
+ private String appName;
+ private String description;
+ private String contactName;
+ private String contactEmail;
+ private String url;
+ private String activeYN;
+
+ public Long getAppId() {
+ return appId;
+ }
+
+ public void setAppId(Long appId) {
+ this.appId = appId;
+ }
+
+ public String getAppName() {
+ return appName;
+ }
+
+ public void setAppName(String appName) {
+ this.appName = appName;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getContactName() {
+ return contactName;
+ }
+
+ public void setContactName(String contactName) {
+ this.contactName = contactName;
+ }
+
+ public String getContactEmail() {
+ return contactEmail;
+ }
+
+ public void setContactEmail(String contactEmail) {
+ this.contactEmail = contactEmail;
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public String getActiveYN() {
+ return activeYN;
+ }
+
+ public void setActiveYN(String activeYN) {
+ this.activeYN = activeYN;
+ }
+
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/CommonWidgetsEnum.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/CommonWidgetsEnum.java
new file mode 100644
index 00000000..6270751b
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/CommonWidgetsEnum.java
@@ -0,0 +1,36 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.ecomp.model;
+
+public enum CommonWidgetsEnum{
+ NEWS("news"),
+ EVENTS("events"),
+ RESOURCES("resources");
+
+ private String value;
+ private CommonWidgetsEnum(String value){
+ this.value = value;
+ }
+
+ @Override
+ public String toString() {
+ return value;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/PortalRestResponse.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/PortalRestResponse.java
new file mode 100644
index 00000000..4f92e75e
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/PortalRestResponse.java
@@ -0,0 +1,60 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.ecomp.model;
+
+public class PortalRestResponse<T> {
+
+ private PortalRestStatusEnum status;
+ private String message;
+
+ private T response;
+
+ public PortalRestResponse(){};
+
+ public PortalRestResponse(PortalRestStatusEnum status, String message, T response){
+ this.status = status;
+ this.message = message;
+ this.response = response;
+ }
+
+ public PortalRestStatusEnum getStatus() {
+ return status;
+ }
+
+ public void setStatus(PortalRestStatusEnum status) {
+ this.status = status;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ public T getResponse() {
+ return response;
+ }
+
+ public void setResponse(T response) {
+ this.response = response;
+ };
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/PortalRestStatusEnum.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/PortalRestStatusEnum.java
new file mode 100644
index 00000000..eceabacb
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/PortalRestStatusEnum.java
@@ -0,0 +1,35 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.ecomp.model;
+
+public enum PortalRestStatusEnum{
+ OK("ok"),
+ ERROR("error");
+
+ private String value;
+ private PortalRestStatusEnum(String value){
+ this.value = value;
+ }
+
+ @Override
+ public String toString() {
+ return value;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/SearchResultItem.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/SearchResultItem.java
new file mode 100644
index 00000000..0fadab80
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ecomp/model/SearchResultItem.java
@@ -0,0 +1,92 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.ecomp.model;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+import org.openecomp.portalsdk.core.domain.support.DomainVo;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+@Entity
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class SearchResultItem extends DomainVo{
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1598343426058929653L;
+
+ @Id
+ private String rowId;
+
+ @JsonProperty("category")
+ private String category;
+
+ @JsonProperty("name")
+ private String name;
+
+ @JsonProperty("target")
+ private String target;
+
+ @JsonProperty("uuid")
+ private String uuid;
+
+ public String getUuid() {
+ return uuid;
+ }
+ public void setUuid(String uuid) {
+ this.uuid = uuid;
+ }
+ public String getRowId() {
+ return rowId;
+ }
+ public void setRowId(String rowId) {
+ this.rowId = rowId;
+ }
+ public String getCategory() {
+ return category;
+ }
+ public void setCategory(String category) {
+ this.category = category;
+ }
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getTarget() {
+ return target;
+ }
+ public void setTarget(String target) {
+ this.target = target;
+ }
+ @Override
+ public String toString() {
+ return "SearchResultItem [rowId=" + rowId + ", category=" + category + ", name=" + name + ", target=" + target
+ + ", uuid=" + uuid + "]";
+ }
+
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/interceptor/PortalResourceInterceptor.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/interceptor/PortalResourceInterceptor.java
new file mode 100644
index 00000000..87ba2a44
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/interceptor/PortalResourceInterceptor.java
@@ -0,0 +1,95 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.interceptor;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.controller.sessionmgt.SessionCommunicationController;
+import org.openecomp.portalapp.portal.controller.ExternalAppsRestfulController;
+import org.openecomp.portalapp.portal.controller.SharedContextRestController;
+import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
+import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
+import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.service.sessionmgt.ManageService;
+import org.openecomp.portalapp.service.sessionmgt.RemoteWebServiceCallService;
+import org.openecomp.portalsdk.core.exception.UrlAccessRestrictedException;
+import org.openecomp.portalsdk.core.interceptor.ResourceInterceptor;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.onboarding.crossapi.PortalTimeoutHandler;
+import org.openecomp.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.method.HandlerMethod;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+public class PortalResourceInterceptor extends ResourceInterceptor {
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalResourceInterceptor.class);
+
+ @Autowired
+ public RemoteWebServiceCallService remoteWebServiceCallService;
+
+ @Autowired
+ public ManageService manageService;
+
+ @Autowired
+ private EPEELFLoggerAdvice epAdvice;
+
+ static ObjectMapper mapper = new ObjectMapper();
+
+ @Override
+ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
+ throws Exception {
+
+ if (handler instanceof HandlerMethod) {
+ HandlerMethod method = (HandlerMethod) handler;
+ Object controllerObj = method.getBean();
+ /**
+ * These classes provide REST endpoints used by other application
+ * servers, NOT by an end user's browser.
+ */
+ if (controllerObj instanceof SessionCommunicationController
+ || controllerObj instanceof SharedContextRestController
+ || controllerObj instanceof ExternalAppsRestfulController) {
+ // check user authentication for RESTful calls
+ String secretKey = null;
+ try {
+ epAdvice.loadServletRequestBasedDefaults(request, SecurityEventTypeEnum.INCOMING_REST_MESSAGE);
+ if (!remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader("uebkey"),
+ request.getHeader("username"), request.getHeader("password"))) {
+ throw new UrlAccessRestrictedException();
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Error authenticating RESTful service. Details: " + EcompPortalUtils.getStackTrace(e));
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeRestApiAuthenticationError);
+ throw new UrlAccessRestrictedException();
+ }
+ }
+ }
+
+ handleSessionUpdates(request);
+ return true;
+ }
+
+ protected void handleSessionUpdates(HttpServletRequest request) {
+ PortalTimeoutHandler.handleSessionUpdatesNative(request, null, null, null, null, manageService);
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/interceptor/SessionTimeoutInterceptor.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/interceptor/SessionTimeoutInterceptor.java
new file mode 100644
index 00000000..cd0a3037
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/interceptor/SessionTimeoutInterceptor.java
@@ -0,0 +1,97 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.interceptor;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.authentication.LoginStrategy;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalapp.util.SessionCookieUtil;
+import org.openecomp.portalsdk.core.controller.FusionBaseController;
+import org.openecomp.portalsdk.core.domain.support.CollaborateList;
+import org.openecomp.portalsdk.core.exception.SessionExpiredException;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.method.HandlerMethod;
+import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
+
+public class SessionTimeoutInterceptor extends HandlerInterceptorAdapter {
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SessionTimeoutInterceptor.class);
+
+ @Autowired
+ private LoginStrategy loginStrategy;
+
+ public SessionTimeoutInterceptor() {
+ }
+
+ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
+ throws Exception {
+
+ if (!isHandlerMethod(handler))
+ return false;
+
+ HandlerMethod method = (HandlerMethod) handler;
+
+ if (!isFusionController(method.getBean()))
+ return false;
+
+ FusionBaseController controller = (FusionBaseController) method.getBean();
+
+ if (!controller.isAccessible()) {
+ try {
+ EPUser user = EPUserUtils.getUserSession(request);
+
+ if (request.getRequestURI().indexOf("logout.htm") > -1) {
+ CollaborateList.delUserName(user.getOrgUserId());
+ throw new SessionExpiredException();
+ } else {
+ resetSessionMaxIdleTimeOut(request);
+ CollaborateList.addUserName(user.getOrgUserId());
+ }
+ } catch (Exception see) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(see));
+ return loginStrategy.login(request, response);
+ }
+
+ }
+
+ return true;
+ }
+
+ private void resetSessionMaxIdleTimeOut(HttpServletRequest request) {
+ SessionCookieUtil.resetSessionMaxIdleTimeOut(request);
+
+ }
+
+ private boolean isFusionController(Object controller) {
+ if (controller instanceof FusionBaseController)
+ return true;
+ return false;
+ }
+
+ private boolean isHandlerMethod(Object controller) {
+ if (controller instanceof HandlerMethod)
+ return true;
+ return false;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/listener/HealthMonitor.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/listener/HealthMonitor.java
new file mode 100644
index 00000000..6b71eeb7
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/listener/HealthMonitor.java
@@ -0,0 +1,393 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.listener;
+
+import java.util.List;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
+import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
+import org.openecomp.portalapp.portal.ueb.EPUebHelper;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+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 {
+
+ @Autowired
+ private SessionFactory sessionFactory;
+
+ @Autowired
+ private EPUebHelper epUebHelper;
+
+ private static boolean databaseUp;
+ private static boolean uebUp;
+ private static boolean frontEndUp;
+ private static boolean backEndUp;
+ private static boolean dbClusterStatusOk;
+ private static boolean dbPermissionsOk;
+ public static boolean isSuspended = false;
+
+ Thread healthMonitorThread;
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HealthMonitor.class);
+
+ public HealthMonitor() {
+
+ }
+
+ public static boolean isDatabaseUp() {
+ return databaseUp;
+ }
+
+ public static boolean isClusterStatusOk() {
+ return dbClusterStatusOk;
+ }
+
+ public static boolean isDatabasePermissionsOk() {
+ return dbPermissionsOk;
+ }
+
+ public static boolean isUebUp() {
+ return uebUp;
+ }
+
+ public static boolean isFrontEndUp() {
+ return frontEndUp;
+ }
+
+ public static boolean isBackEndUp() {
+ return backEndUp;
+ }
+
+ private void monitorEPHealth() throws InterruptedException{
+
+ int numIntervalsDatabaseHasBeenDown = 0;
+ int numIntervalsClusterNotHealthy = 0;
+ int numIntervalsDatabasePermissionsIncorrect = 0;
+ int numIntervalsUebHasBeenDown = 0;
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "==> Health Monitor thread started");
+
+ long sleepInterval = (Long.valueOf(SystemProperties.getProperty(EPSystemProperties.HEALTH_POLL_INTERVAL_SECONDS)) * 1000);
+ long numIntervalsBetweenAlerts = Long.valueOf(SystemProperties.getProperty(EPSystemProperties.HEALTHFAIL_ALERT_EVERY_X_INTERVALS));
+ logger.debug(EELFLoggerDelegate.debugLogger, "Polling health every " + sleepInterval + " milliseconds. Alerting every "
+ + (sleepInterval * numIntervalsBetweenAlerts)/1000 + " seconds when component remains down.");
+
+ while (true)
+ {
+ //
+ // Get DB status. If down, signal alert once every X intervals.
+ //
+ databaseUp = this.checkIfDatabaseUp();
+ if (databaseUp == false) {
+
+ if ((numIntervalsDatabaseHasBeenDown % numIntervalsBetweenAlerts) == 0){
+ // Write a Log entry that will generate an alert
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeHealthCheckMySqlError);
+ logger.debug(EELFLoggerDelegate.debugLogger, "Database down, logging to error log to trigger alert.");
+ numIntervalsDatabaseHasBeenDown++;
+ }
+ else {
+ numIntervalsDatabaseHasBeenDown = 0;
+ }
+ }
+
+ dbClusterStatusOk = this.checkClusterStatus();
+ if (dbClusterStatusOk == false) {
+
+ if ((numIntervalsClusterNotHealthy % numIntervalsBetweenAlerts) == 0){
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeHealthCheckMySqlError);
+ logger.debug(EELFLoggerDelegate.debugLogger, "Cluster nodes appear to be down, logging to error log to trigger alert.");
+ numIntervalsClusterNotHealthy++;
+ }
+ else {
+ numIntervalsClusterNotHealthy = 0;
+ }
+ }
+
+ dbPermissionsOk = this.checkDatabaseAndPermissions();
+ if (dbPermissionsOk == false) {
+
+ if ((numIntervalsDatabasePermissionsIncorrect % numIntervalsBetweenAlerts) == 0){
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeHealthCheckMySqlError);
+ logger.debug(EELFLoggerDelegate.debugLogger, "Database permissions don't seem correct, logging to error log to trigger alert.");
+ numIntervalsDatabasePermissionsIncorrect++;
+ }
+ else {
+ numIntervalsDatabasePermissionsIncorrect = 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){
+ // Write a Log entry that will generate an alert
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeHealthCheckUebClusterError);
+ logger.debug(EELFLoggerDelegate.debugLogger, "UEB down, logging to error log to trigger alert");
+ numIntervalsUebHasBeenDown++;
+ }
+ else {
+ numIntervalsUebHasBeenDown = 0;
+ }
+ }
+
+ //The front end should be up because the API is called through proxy front end server.
+ frontEndUp = true;
+
+
+ //If the rest API called, the backend is always up
+ backEndUp = true;
+
+ //
+ // future nice to have...get Partner status
+ //
+ // For all apps exposing a rest url, query one of the rest urls(/roles?) and manage a list
+ // of app name/status. We might not return back a non 200 OK in health check, but we
+ // could return information in the json content of a health check.
+ //
+
+ //
+ // Get DB status. If down, signal alert once every X intervals.
+ //
+ Thread.sleep(sleepInterval);
+ }
+ }
+
+ @PostConstruct
+ public void initHealthMonitor() {
+
+ healthMonitorThread = new Thread("EP HealthMonitor thread") {
+ public void run(){
+ try {
+ monitorEPHealth();
+ } catch (InterruptedException e) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "<== Health Monitor thread exiting..." + EcompPortalUtils.getStackTrace(e));
+ } catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in Healthcheck monitor thread." + EcompPortalUtils.getStackTrace(e));
+ }
+ }
+ };
+ if (healthMonitorThread != null) {
+ healthMonitorThread.start();
+ }
+ }
+
+ @PreDestroy
+ public void closeHealthMonitor()
+ {
+ this.healthMonitorThread.interrupt();
+ }
+
+
+ private boolean checkIfDatabaseUp() {
+
+ boolean isUp = false;
+
+ Session localSession = null;
+
+ try {
+ localSession = sessionFactory.openSession();
+
+ if (localSession != null) {
+
+ String sql = "select app_name from fn_app where app_id=1";
+ Query query = localSession.createSQLQuery(sql);
+ @SuppressWarnings("unchecked")
+ List <String>queryList = query.list();
+ if (queryList != null) {
+ isUp = true;
+ }
+ localSession.close();
+ }
+ }
+ catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ isUp = false;
+ }
+
+ return isUp;
+ }
+
+
+ private boolean checkClusterStatus() {
+
+ boolean isUp = false;
+
+ Session localSession = null;
+
+ try {
+ localSession = sessionFactory.openSession();
+ if (localSession != null) {
+ /////////////////////////////////////////////////////////////////////////
+ // If all nodes are unhealthy in a cluster, this will throw an exception
+ /////////////////////////////////////////////////////////////////////////
+ String sql = "select * from mysql.user";
+ Query query = localSession.createSQLQuery(sql);
+ @SuppressWarnings("unchecked")
+ List <String>queryList = query.list();
+ if (queryList != null) {
+ isUp = true;
+ }
+ }
+ }
+ catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "checkClusterStatus() exception msg = " + e.getMessage());
+ if ((e.getCause() != null) && (e.getCause().getMessage() != null)) {
+ logger.error(EELFLoggerDelegate.errorLogger, "checkClusterStatus() exception msg = " + e.getCause().getMessage());
+ }
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception inside checkClusterStatus() exception = " + EcompPortalUtils.getStackTrace(e));
+ isUp = false;
+ }
+ finally {
+ if (localSession != null) {
+ localSession.close();
+ }
+ }
+
+ return isUp;
+
+ }
+
+
+ private boolean checkDatabaseAndPermissions() {
+
+ boolean isUp = false;
+
+ Session localSession = null;
+
+ try {
+ localSession = sessionFactory.openSession();
+ if (localSession != null) {
+ String sql = "SHOW GRANTS FOR CURRENT_USER";
+ Query query = localSession.createSQLQuery(sql);
+ @SuppressWarnings("unchecked")
+ List<String> grantsList = query.list();
+ for (String str : grantsList) {
+ if ((str.toUpperCase().contains("ALL"))
+ ||
+ (str.toUpperCase().contains("DELETE") &&
+ str.toUpperCase().contains("SELECT") &&
+ str.toUpperCase().contains("UPDATE") &&
+ str.toUpperCase().contains("INSERT"))) {
+ isUp = true;
+ break;
+ }
+ }
+ if (isUp == false) {
+ logger.error(EELFLoggerDelegate.errorLogger, "checkDatabaseAndPermissions() returning false. SHOW GRANTS FOR CURRENT_USER being dumped:");
+ for (String str : grantsList) {
+ logger.error(EELFLoggerDelegate.errorLogger, "grants output item = [" + str + "]");
+ }
+ }
+ }
+ }
+ catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "checkDatabaseAndPermissions() exception msg = " + e.getMessage());
+ if ((e.getCause() != null) && (e.getCause().getMessage() != null)) {
+ logger.error(EELFLoggerDelegate.errorLogger, "checkDatabaseAndPermissions() exception msg = " + e.getCause().getMessage());
+ }
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception inside checkDatabaseAndPermissions() exception = " + EcompPortalUtils.getStackTrace(e));
+ isUp = false;
+ }
+ finally {
+ if (localSession != null) {
+ localSession.close();
+ }
+ }
+
+ 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, "Exception inside CheckIfUebUp exception = " + EcompPortalUtils.getStackTrace(e));
+ }
+
+ return uebUp;
+
+
+ }
+
+ /*
+ private boolean checkIfFeUp() {
+ boolean frontenndUp = false;
+ try {
+ String url = SystemProperties.getProperty(EPSystemProperties.FE_URL);
+ if(StringUtils.isEmpty(url))
+ {
+ logger.debug(EELFLoggerDelegate.debugLogger, "The front end URL is empty. Cannot check the status");
+ return frontenndUp;
+ }
+
+ url = url.replace("index.html", "app/healthCheck.json");
+
+ URL frontEndURL = new URL(url);
+
+ HttpURLConnection con = (HttpURLConnection) frontEndURL.openConnection();
+
+ // optional default is GET
+ con.setRequestMethod("GET");
+
+ int responseCode = con.getResponseCode();
+ logger.debug(EELFLoggerDelegate.debugLogger, "Fronend response code : " + responseCode);
+
+ if(responseCode == 200)
+ {
+ frontenndUp = true;
+ }
+
+ }
+ catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while trying to access font end" + EcompPortalUtils.getStackTrace(e));
+ }
+
+ return frontenndUp;
+ }
+ */
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/listener/UserContextListener.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/listener/UserContextListener.java
new file mode 100644
index 00000000..8255914f
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/listener/UserContextListener.java
@@ -0,0 +1,49 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.listener;
+
+import java.util.HashMap;
+
+import javax.servlet.ServletContext;
+import javax.servlet.ServletContextEvent;
+import javax.servlet.ServletContextListener;
+
+public class UserContextListener implements ServletContextListener{
+ @SuppressWarnings("rawtypes")
+ public void contextInitialized(ServletContextEvent event){
+ ServletContext context = event.getServletContext();
+ //
+ // instanciate a map to store references to all the active
+ // sessions and bind it to context scope.
+ //
+ HashMap activeUsers = new HashMap();
+ context.setAttribute("activeUsers", activeUsers);
+ }
+
+ /**
+ * Needed for the ServletContextListener interface.
+ */
+ public void contextDestroyed(ServletContextEvent event){
+ // To overcome the problem with losing the session references
+ // during server restarts, put code here to serialize the
+ // activeUsers HashMap. Then put code in the contextInitialized
+ // method that reads and reloads it if it exists...
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/listener/UserSessionListener.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/listener/UserSessionListener.java
new file mode 100644
index 00000000..9b48c622
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/listener/UserSessionListener.java
@@ -0,0 +1,125 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+
+package org.openecomp.portalapp.portal.listener;
+
+import java.util.HashMap;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.annotation.WebListener;
+import javax.servlet.http.HttpSession;
+import javax.servlet.http.HttpSessionEvent;
+import javax.servlet.http.HttpSessionListener;
+
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.service.SharedContextService;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.domain.support.CollaborateList;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.ApplicationContext;
+import org.springframework.util.StringUtils;
+
+/**
+ * Listens for session-create and session-destroy events.
+ */
+@WebListener
+@SuppressWarnings({ "unchecked", "rawtypes" })
+public class UserSessionListener implements HttpSessionListener {
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserSessionListener.class);
+
+ /**
+ * Access to the database
+ */
+ @Autowired
+ SharedContextService sharedContextService;
+
+ public void init(ServletConfig config) {
+ }
+
+ /**
+ * Adds sessions to the context scoped HashMap when they begin.
+ */
+ public void sessionCreated(HttpSessionEvent event) {
+ HttpSession session = event.getSession();
+ ServletContext context = session.getServletContext();
+ HashMap activeUsers = (HashMap) context.getAttribute("activeUsers");
+
+ activeUsers.put(session.getId(), session);
+ context.setAttribute("activeUsers", activeUsers);
+ logger.info(EELFLoggerDelegate.debugLogger, "Session Created : " + session.getId());
+ }
+
+ /**
+ * Removes sessions from the context scoped HashMap when they expire or are
+ * invalidated.
+ */
+ public void sessionDestroyed(HttpSessionEvent event) {
+
+ try {
+ HttpSession session = event.getSession();
+ ServletContext context = session.getServletContext();
+ HashMap activeUsers = (HashMap) context.getAttribute("activeUsers");
+ activeUsers.remove(session.getId());
+
+ EPUser user = (EPUser) session
+ .getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
+ if (user!=null && !StringUtils.isEmpty(user.getOrgUserId())) {
+ CollaborateList.delUserName(user.getOrgUserId());
+ }
+
+ // Remove any shared context entries for this session.
+ if (getSharedContextService()!=null) {
+ getSharedContextService().deleteSharedContexts(session.getId());
+
+ // Clean the shared context each time a session is destroyed.
+ // TODO: move the threshold to configuration file.
+ getSharedContextService().expireSharedContexts(60 * 60 * 8);
+ }
+
+ logger.info(EELFLoggerDelegate.debugLogger, "Session Destroyed : " + session.getId());
+
+ } catch (Exception e) {
+ logger.warn(EELFLoggerDelegate.errorLogger, "Exception occurred while executing sessionDestroyed. Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+ }
+
+ private static ApplicationContext applicationContext;
+
+ public static void setApplicationContext(ApplicationContext _applicationContext) {
+ applicationContext = _applicationContext;
+ }
+
+ public SharedContextService getSharedContextService() {
+ if(sharedContextService == null){
+ if (applicationContext != null)
+ sharedContextService = (SharedContextService)applicationContext.getBean("sharedContextService");
+ }
+
+ return sharedContextService;
+ }
+
+ public void setSharedContextService(SharedContextService sharedContextService) {
+ this.sharedContextService = sharedContextService;
+ }
+}
+
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPAuditLog.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPAuditLog.java
new file mode 100644
index 00000000..15a4c7f0
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPAuditLog.java
@@ -0,0 +1,31 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.logging.aop;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target({ElementType.METHOD, ElementType.TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+public @interface EPAuditLog {
+ String value() default "";
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAdvice.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAdvice.java
new file mode 100644
index 00000000..a03f5153
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAdvice.java
@@ -0,0 +1,341 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.logging.aop;
+
+import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY;
+import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID;
+import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
+import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
+import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS;
+import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID;
+import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
+
+import java.net.InetAddress;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.UUID;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum;
+import org.openecomp.portalsdk.core.logging.format.AuditLogFormatter;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.openecomp.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
+import org.openecomp.portalsdk.core.web.support.UserUtils;
+import org.slf4j.MDC;
+
+import com.att.eelf.configuration.Configuration;
+
+@org.springframework.context.annotation.Configuration
+public class EPEELFLoggerAdvice {
+
+ EELFLoggerDelegate adviceLogger = EELFLoggerDelegate.getLogger(EPEELFLoggerAdvice.class);
+ //DateTime Format according to the ECOMP Application Logging Guidelines.
+ private static final SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
+
+ public void loadServletRequestBasedDefaults(HttpServletRequest req, SecurityEventTypeEnum securityEventType) {
+ try {
+ this.setHttpRequestBasedDefaultsIntoGlobalLoggingContext(req, securityEventType, req.getServletPath());
+ } catch(Exception e) {
+ adviceLogger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+ }
+
+ public Object[] before(SecurityEventTypeEnum securityEventType, Object[] args, Object[] passOnArgs) {
+ String className = "";
+ if (passOnArgs[0]!=null) {
+ className = passOnArgs[0].toString();
+ }
+
+ String methodName = "";
+ if (passOnArgs[1]!=null) {
+ methodName = passOnArgs[1].toString();
+ }
+
+ //Initialize Request defaults only for controller methods.
+ MDC.put(className + methodName + EPSystemProperties.METRICSLOG_BEGIN_TIMESTAMP, getCurrentDateTimeUTC());
+ MDC.put(EPSystemProperties.TARGET_ENTITY, EPSystemProperties.ECOMP_PORTAL_BE);
+ MDC.put(EPSystemProperties.TARGET_SERVICE_NAME, methodName);
+ if (securityEventType!=null) {
+ MDC.put(className + methodName + EPSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, getCurrentDateTimeUTC());
+ HttpServletRequest req = null;
+ if (args[0]!=null && args[0] instanceof HttpServletRequest ) {
+ req = (HttpServletRequest)args[0];
+ this.setHttpRequestBasedDefaultsIntoGlobalLoggingContext(req, securityEventType, methodName);
+ }
+ }
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(className);
+
+ //StopWatch stopWatch = new StopWatch("Metrics for " + className + "." + methodName);
+ //stopWatch.start();
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "Entered executing " + methodName +".");
+
+ return new Object[] {""};
+ }
+
+ public void after(SecurityEventTypeEnum securityEventType, String statusCode, String responseCode, Object[] args, Object[] returnArgs, Object[] passOnArgs) {
+ //ClassName
+ String className = "";
+ if (passOnArgs[0]!=null) {
+ className = passOnArgs[0].toString();
+ }
+
+ //Method Name
+ String methodName = "";
+ if (passOnArgs[1]!=null) {
+ methodName = passOnArgs[1].toString();
+ }
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(className);
+ /*/
+ StopWatch stopWatch = (StopWatch)returnArgs[0];
+ if (stopWatch!=null && stopWatch.isRunning()) {
+ stopWatch.stop();
+ MDC.put(SystemProperties.MDC_TIMER, stopWatch.getTotalTimeMillis() + "ms");
+ }
+ /**/
+
+ if (MDC.get(EPSystemProperties.TARGET_SERVICE_NAME) == null || MDC.get(EPSystemProperties.TARGET_SERVICE_NAME) == "") {
+ MDC.put(EPSystemProperties.TARGET_SERVICE_NAME, methodName);
+ }
+
+ if (MDC.get(EPSystemProperties.TARGET_ENTITY) == null || MDC.get(EPSystemProperties.TARGET_ENTITY) == "") {
+ MDC.put(EPSystemProperties.TARGET_ENTITY, EPSystemProperties.ECOMP_PORTAL_BE);
+ }
+
+ MDC.put(EPSystemProperties.METRICSLOG_BEGIN_TIMESTAMP, MDC.get(className + methodName + EPSystemProperties.METRICSLOG_BEGIN_TIMESTAMP));
+ MDC.put(EPSystemProperties.METRICSLOG_END_TIMESTAMP, getCurrentDateTimeUTC());
+ this.calculateDateTimeDifference(MDC.get(EPSystemProperties.METRICSLOG_BEGIN_TIMESTAMP), MDC.get(EPSystemProperties.METRICSLOG_END_TIMESTAMP));
+
+ //Making sure to reload the INCOMING request MDC defaults if they have
+ //been wiped out by either Outgoing or LDAP Phone book search operations.
+ if (securityEventType!=null && args[0]!=null && args[0] instanceof HttpServletRequest &&
+ securityEventType==SecurityEventTypeEnum.INCOMING_REST_MESSAGE &&
+ (MDC.get(EPSystemProperties.FULL_URL)==null || MDC.get(EPSystemProperties.FULL_URL)=="")) {
+ HttpServletRequest req = (HttpServletRequest)args[0];
+ this.setHttpRequestBasedDefaultsIntoGlobalLoggingContext(req, securityEventType, methodName);
+ }
+
+ //Use external API response code in case if it resulted in an error.
+ String externalAPIResponseCode = MDC.get(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE);
+ if (externalAPIResponseCode==null || externalAPIResponseCode=="" || externalAPIResponseCode.trim().equalsIgnoreCase("200")) {
+ MDC.put(EPSystemProperties.RESPONSE_CODE, responseCode);
+ MDC.put(EPSystemProperties.STATUS_CODE, statusCode);
+ } else {
+ MDC.put(EPSystemProperties.RESPONSE_CODE, externalAPIResponseCode);
+ MDC.put(EPSystemProperties.STATUS_CODE, "ERROR");
+ }
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "Finished executing " + methodName + ".");
+ logger.info(EELFLoggerDelegate.metricsLogger, methodName + " operation is completed.");
+
+ //Log security message, if necessary
+ if (securityEventType!=null) {
+ MDC.put(EPSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, MDC.get(className + methodName + EPSystemProperties.AUDITLOG_BEGIN_TIMESTAMP));
+ MDC.put(EPSystemProperties.AUDITLOG_END_TIMESTAMP, getCurrentDateTimeUTC());
+ this.calculateDateTimeDifference(MDC.get(EPSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), MDC.get(EPSystemProperties.AUDITLOG_END_TIMESTAMP));
+
+ this.logSecurityMessage(logger, securityEventType, methodName);
+
+ //Outgoing & LDAP messages are part of Incoming requests so,
+ //keep "RequestId", "PartnerName", "ServiceName", "LoginId" &
+ //"ResponseCode" etc. in memory and remove it only when
+ //finished processing the parent incoming message.
+ if (securityEventType!=SecurityEventTypeEnum.OUTGOING_REST_MESSAGE &&
+ securityEventType!=SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH) {
+ MDC.remove(MDC_KEY_REQUEST_ID);
+ MDC.remove(EPSystemProperties.PARTNER_NAME);
+ MDC.remove(Configuration.MDC_SERVICE_NAME);
+ MDC.remove(EPSystemProperties.MDC_LOGIN_ID);
+ MDC.remove(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE);
+ }
+
+ //clear when finishes audit logging
+ MDC.remove(EPSystemProperties.FULL_URL);
+ MDC.remove(EPSystemProperties.PROTOCOL);
+ MDC.remove(EPSystemProperties.STATUS_CODE);
+ MDC.remove(className + methodName + EPSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+ MDC.remove(EPSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+ MDC.remove(EPSystemProperties.AUDITLOG_END_TIMESTAMP);
+ MDC.remove(EPSystemProperties.RESPONSE_CODE);
+ }
+ MDC.remove(className + methodName + EPSystemProperties.METRICSLOG_BEGIN_TIMESTAMP);
+ MDC.remove(EPSystemProperties.METRICSLOG_BEGIN_TIMESTAMP);
+ MDC.remove(EPSystemProperties.METRICSLOG_END_TIMESTAMP);
+ MDC.remove(EPSystemProperties.MDC_TIMER);
+ MDC.remove(EPSystemProperties.TARGET_ENTITY);
+ MDC.remove(EPSystemProperties.TARGET_SERVICE_NAME);
+ }
+
+ private void logSecurityMessage(EELFLoggerDelegate logger, SecurityEventTypeEnum securityEventType, String restMethod) {
+ StringBuilder additionalInfoAppender = new StringBuilder();
+ String auditMessage = "";
+
+ if (securityEventType == SecurityEventTypeEnum.OUTGOING_REST_MESSAGE) {
+ additionalInfoAppender.append(String.format("%s '%s' request was initiated.",
+ restMethod, MDC.get(EPSystemProperties.TARGET_SERVICE_NAME)));
+ } else if (securityEventType==SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH) {
+ additionalInfoAppender.append("LDAP Phonebook search operation is performed.");
+ } else {
+ additionalInfoAppender.append(String.format("%s request was received.", restMethod));
+
+ if (securityEventType == SecurityEventTypeEnum.FE_LOGIN_ATTEMPT) {
+ String loginId = "";
+ String additionalMessage = " Successfully authenticated.";
+ loginId = MDC.get(EPSystemProperties.MDC_LOGIN_ID);
+ if (loginId==null || loginId=="" || loginId== EPSystemProperties.UNKNOWN) {
+ additionalMessage = " No cookies are found.";
+ }
+ additionalInfoAppender.append(additionalMessage);
+ } else if (securityEventType == SecurityEventTypeEnum.FE_LOGOUT) {
+ additionalInfoAppender.append(" User has been successfully logged out.");
+ }
+ }
+
+ String fullURL = MDC.get(EPSystemProperties.FULL_URL);
+ if (fullURL!=null && fullURL!="") {
+ additionalInfoAppender.append(" Request-URL:" + MDC.get(EPSystemProperties.FULL_URL));
+ }
+
+ auditMessage = AuditLogFormatter.getInstance().createMessage( MDC.get(EPSystemProperties.PROTOCOL),
+ securityEventType.name(),
+ MDC.get(EPSystemProperties.MDC_LOGIN_ID),
+ additionalInfoAppender.toString());
+
+ logger.info(EELFLoggerDelegate.auditLogger, auditMessage);
+ }
+
+ private void setHttpRequestBasedDefaultsIntoGlobalLoggingContext(HttpServletRequest req, SecurityEventTypeEnum securityEventType, String restMethod) {
+ //No need to load the request based defaults for the following security messages
+ //since either they are initiated by the Portal BE or not Http request based.
+ if (req!=null) {
+ if (securityEventType!=SecurityEventTypeEnum.OUTGOING_REST_MESSAGE &&
+ securityEventType!=SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH &&
+ securityEventType!=SecurityEventTypeEnum.INCOMING_UEB_MESSAGE) {
+ //Load the RequestID (aka TrasactionId) into MDC context.
+ String requestId = UserUtils.getRequestId(req);
+ if (requestId=="" || requestId==null) {
+ requestId = UUID.randomUUID().toString();
+ }
+ MDC.put(MDC_KEY_REQUEST_ID, requestId);
+
+ //Load user agent into MDC context, if available.
+ String accessingClient = "Unknown";
+ accessingClient = req.getHeader(SystemProperties.USERAGENT_NAME);
+ if (accessingClient!=null && accessingClient!="" &&
+ (accessingClient.contains("Mozilla") || accessingClient.contains("Chrome") || accessingClient.contains("Safari"))) {
+ accessingClient = EPSystemProperties.ECOMP_PORTAL_FE;
+ }
+ MDC.put(EPSystemProperties.PARTNER_NAME, accessingClient);
+
+ //Load loginId into MDC context.
+ String loginId = "";
+ try {
+ loginId = UserUtils.getUserIdFromCookie(req);
+ } catch (Exception e) {
+ adviceLogger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+ if (loginId == null || loginId == "") {
+ EPUser user = EPUserUtils.getUserSession(req);
+ if (user != null) {
+ loginId = user.getLoginId();
+ }
+
+ if (loginId==null || loginId=="") {
+ loginId = "Unknown";
+ }
+ }
+ MDC.put(EPSystemProperties.MDC_LOGIN_ID, loginId);
+
+ //Rest URL & Protocol
+ String restURL = "";
+ MDC.put(EPSystemProperties.FULL_URL, EPSystemProperties.UNKNOWN);
+ MDC.put(EPSystemProperties.PROTOCOL, EPSystemProperties.HTTP);
+ restURL = UserUtils.getFullURL(req);
+ if (restURL!=null && restURL!="") {
+ MDC.put(EPSystemProperties.FULL_URL, restURL);
+ if (restURL.toLowerCase().contains("https")) {
+ MDC.put(EPSystemProperties.PROTOCOL, EPSystemProperties.HTTPS);
+ }
+ }
+
+ //Rest Path
+ MDC.put(MDC_SERVICE_NAME, restMethod);
+ String restPath = req.getServletPath();
+ if (restPath!=null && restPath!="") {
+ MDC.put(MDC_SERVICE_NAME, restPath);
+ }
+
+ //Client IPAddress i.e. IPAddress of the remote host who is making this request.
+ String clientIPAddress = "";
+ clientIPAddress = req.getHeader("X-FORWARDED-FOR");
+ if (clientIPAddress == null) {
+ clientIPAddress = req.getRemoteAddr();
+ }
+ MDC.put(EPSystemProperties.CLIENT_IP_ADDRESS, clientIPAddress);
+ } else if(securityEventType==SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH) {
+ MDC.put(EPSystemProperties.TARGET_ENTITY, "Phonebook");
+ MDC.put(EPSystemProperties.TARGET_SERVICE_NAME, "search");
+ }
+ } else {
+ MDC.put(MDC_SERVICE_NAME, restMethod);
+ MDC.put(EPSystemProperties.PARTNER_NAME, EPSystemProperties.ECOMP_PORTAL_FE);
+ }
+
+ MDC.put(MDC_SERVICE_INSTANCE_ID, "");
+ MDC.put(MDC_ALERT_SEVERITY, AlarmSeverityEnum.INFORMATIONAL.toString());
+ try {
+ MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
+ MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
+ MDC.put(MDC_INSTANCE_UUID, SystemProperties.getProperty(SystemProperties.INSTANCE_UUID));
+ } catch (Exception e) {
+ adviceLogger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+ }
+
+ private String getCurrentDateTimeUTC() {
+ String currentDateTime = ecompLogDateFormat.format(new Date());
+ return currentDateTime;
+ }
+
+ private void calculateDateTimeDifference(String beginDateTime, String endDateTime) {
+ if (beginDateTime!=null && endDateTime!=null) {
+ try {
+ Date beginDate = ecompLogDateFormat.parse(beginDateTime);
+ Date endDate = ecompLogDateFormat.parse(endDateTime);
+ String timeDifference = String.format("%d ms", endDate.getTime() - beginDate.getTime());
+ MDC.put(SystemProperties.MDC_TIMER, timeDifference);
+ } catch(Exception e) {
+ adviceLogger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+ }
+ }
+
+ public String getInternalResponseCode() {
+ return MDC.get(EPSystemProperties.RESPONSE_CODE);
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAspect.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAspect.java
new file mode 100644
index 00000000..80ae9262
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAspect.java
@@ -0,0 +1,204 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.logging.aop;
+
+import org.aspectj.lang.ProceedingJoinPoint;
+import org.aspectj.lang.annotation.Around;
+import org.aspectj.lang.annotation.Aspect;
+import org.aspectj.lang.annotation.Pointcut;
+import org.openecomp.portalapp.portal.transport.FieldsValidator;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
+import org.springframework.beans.factory.annotation.Autowired;
+
+@Aspect
+@org.springframework.context.annotation.Configuration
+public class EPEELFLoggerAspect {
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPEELFLoggerAspect.class);
+
+ @Autowired
+ EPEELFLoggerAdvice epAdvice;
+
+ /*
+ * Point-cut expression to handle all INCOMING_REST_MESSAGES
+ */
+ @Pointcut("execution(public * org.openecomp.portalapp.portal.controller.*.*(..))")
+ public void incomingAuditMessages() {}
+
+ /*
+ * Handles all INCOMING_REST_MESSAGES from kpiDashboard
+ */
+ @Pointcut("execution(public * org.openecomp.portalapp.kpidash.controller.*.*(..))")
+ public void kpiDashboardAuditMessages() {}
+
+ /*
+ * Point-cut expression to handle all session management INCOMING_REST_MESSAGES
+ */
+ @Pointcut("execution(public * org.openecomp.portalapp.controller.sessionmgt.*.*(..))")
+ public void sessionMgtIncomingAuditMessages() {}
+
+ /*
+ * Point-cut expression to handle UserProfileController INCOMING_REST_MESSAGES
+ */
+ @Pointcut("execution(public * org.openecomp.portalapp.controller.UserProfileController.*(..))")
+ public void userProfileIncomingAuditMessages() {}
+
+ /*
+ * Point-cut expression to handle UserProfileController INCOMING_REST_MESSAGES
+ */
+ @Pointcut("execution(public * org.openecomp.portalapp.controller.WelcomeController.*(..))")
+ public void welcomeIncomingAuditMessages() {}
+
+ /*
+ * Point-cut expression to handle INCOING Logout Rest Messages
+ */
+ @Pointcut("execution(public * org.openecomp.portalapp.controller.ECOMPLogoutController.*(..))")
+ public void logoutAuditMessages() {}
+
+
+ /*
+ * Point-cut expression which handles all the OUTGOING_REST_MESSAGES.
+ */
+ @Pointcut("execution(public * org.openecomp.portalapp.portal.service.ApplicationsRestClientServiceImpl.*(..))")
+ public void outgoingAuditMessages() {}
+
+ /*
+ * Point-cut expression to handle all the session management OUTGOING_REST_MESSAGES.
+ */
+ @Pointcut("execution(public * org.openecomp.portalapp.service.sessionmgt.SessionCommunication.*(..))")
+ public void sessionMgtOutgoingAuditMessages() {}
+
+ /*
+ * Point-cut expression which handles all the LDAP_PHONEBOOK_USER_SEARCH calls.
+ */
+ @Pointcut("execution(public * org.openecomp.portalapp.portal.service.EPLdapServiceImpl.*(..))")
+ public void phoneBookSearchAuditMessages() {}
+
+ /*
+ * Handles Audit, Metrics & Debug logging for the point-cut
+ * expression defined at class-level
+ */
+ @Around("(incomingAuditMessages() || kpiDashboardAuditMessages() || sessionMgtIncomingAuditMessages() || "
+ + "userProfileIncomingAuditMessages() || welcomeIncomingAuditMessages()) && @within(epAuditLog)")
+ public Object incomingAuditMessagesAroundClass(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable {
+ return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.INCOMING_REST_MESSAGE);
+ }
+
+ /*
+ * Handles Audit, Metrics & Debug logging for the point-cut
+ * expression defined at class-level
+ */
+ @Around("(outgoingAuditMessages() || sessionMgtOutgoingAuditMessages()) && @within(epAuditLog)")
+ public Object outgoingAuditMessagesAroundClass(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable {
+ return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.OUTGOING_REST_MESSAGE);
+ }
+
+
+ /*
+ * Handles Audit, Metrics & Debug logging for the point-cut
+ * expression defined at method-level
+ */
+ @Around("(outgoingAuditMessages() || sessionMgtOutgoingAuditMessages()) && @annotation(epAuditLog)")
+ public Object outgoingAuditMessagesAroundMethod(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable {
+ return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.OUTGOING_REST_MESSAGE);
+ }
+
+ /*
+ * Handles Audit, Metrics & Debug logging for the point-cut
+ * expression defined at method-level
+ */
+ @Around("(incomingAuditMessages() || kpiDashboardAuditMessages() || sessionMgtIncomingAuditMessages() ||"
+ + "userProfileIncomingAuditMessages() || welcomeIncomingAuditMessages()) && @annotation(epAuditLog)")
+ public Object incomingAuditMessagesAroundMethod(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable {
+ return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.INCOMING_REST_MESSAGE);
+ }
+
+ @Around("@annotation(epAuditLog)")
+ public Object loginAuditMessagesAroundMethod(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable {
+ return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.FE_LOGIN_ATTEMPT);
+ }
+
+ @Around("logoutAuditMessages() && @annotation(epAuditLog)")
+ public Object logoutAuditMessagesAroundMethod(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable {
+ return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.FE_LOGOUT);
+ }
+
+ @Around("phoneBookSearchAuditMessages() && @annotation(epAuditLog)")
+ public Object phonebookSearchAuditMessagesAroundMethod(ProceedingJoinPoint joinPoint, EPAuditLog epAuditLog) throws Throwable {
+ return this.logAroundMethod(joinPoint, SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH);
+ }
+
+ private Object logAroundMethod(ProceedingJoinPoint joinPoint, SecurityEventTypeEnum securityEventType) throws Throwable {
+ //Before
+ Object[] passOnArgs = new Object[] {joinPoint.getSignature().getDeclaringType().getName(), joinPoint.getSignature().getName()};
+ Object[] returnArgs = epAdvice.before(securityEventType, joinPoint.getArgs(), passOnArgs);
+
+ //Call the actual method
+ Object result = null;
+ String statusCode = "COMPLETE";
+ String responseCode = "200";
+ try {
+ result = joinPoint.proceed();
+ } catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ statusCode = "ERROR";
+ responseCode = "500"; //Internal server error
+ }
+
+ //Check the result
+ if (securityEventType!=null) {
+ if (result==null) {
+ statusCode = "ERROR";
+ //Check if there is an internal response code
+ //and use it if the caller function has configured it.
+ responseCode = epAdvice.getInternalResponseCode();
+ if (responseCode==null||responseCode=="") {
+ responseCode = "500"; //Internal server error
+ }
+ } else if (result instanceof FieldsValidator) {
+ FieldsValidator fieldsValidator = (FieldsValidator) result;
+ if (fieldsValidator!=null && fieldsValidator.httpStatusCode!=null) {
+ responseCode = fieldsValidator.httpStatusCode.toString();
+ }
+ }
+ }
+
+ //After
+ epAdvice.after(securityEventType, statusCode, responseCode, joinPoint.getArgs(), returnArgs, passOnArgs);
+
+ return result;
+ }
+
+ //Metrics Logging
+ @Pointcut("execution(* *(..))")
+ public void performMetricsLogging() {}
+
+ @Around("performMetricsLogging() && @within(epMetricsLog)")
+ public Object metricsLoggingAroundClass(ProceedingJoinPoint joinPoint, EPMetricsLog epMetricsLog) throws Throwable {
+ return this.logAroundMethod(joinPoint, null);
+ }
+
+ @Around("performMetricsLogging() && @annotation(epMetricsLog)")
+ public Object metricsLoggingAroundMethod(ProceedingJoinPoint joinPoint, EPMetricsLog epMetricsLog) throws Throwable {
+ return this.logAroundMethod(joinPoint, null);
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPMetricsLog.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPMetricsLog.java
new file mode 100644
index 00000000..cc325a12
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPMetricsLog.java
@@ -0,0 +1,31 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.logging.aop;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target({ElementType.METHOD, ElementType.TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+public @interface EPMetricsLog {
+ String value() default "";
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/format/ApplicationCodes.properties b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/format/ApplicationCodes.properties
new file mode 100644
index 00000000..2533dfa8
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/format/ApplicationCodes.properties
@@ -0,0 +1,141 @@
+###
+# ================================================================================
+# eCOMP Portal
+# ================================================================================
+# Copyright (C) 2017 AT&T Intellectual Property
+# ================================================================================
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ================================================================================
+###
+########################################################################
+#Resource key=Error Code|Message text|Resolution text |Description text
+#######
+#Newlines can be utilized to add some clarity ensuring continuing line
+#has atleast one leading space
+#ResourceKey=\
+# ERR0000E\
+# Sample error msg txt\
+# Sample resolution msg\
+# Sample description txt
+#
+######
+#Error code classification category
+#100 Permission errors
+#200 Availability errors/Timeouts
+#300 Data errors
+#400 Schema Interface type/validation errors
+#500 Business process errors
+#900 Unknown errors
+#
+########################################################################
+
+# Define Alarm Codes Specific to ECOMP Portal
+BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT= ||Reason: {0}.|\
+ An Authentication failure occurred during access to UEB server. Please check that UEB keys are configured correctly under fusion.properties file.
+
+BERESTAPIAUTHENTICATIONERROR = |||Please check application credentials defined in Database or portal.properties file.
+
+INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT=||Description: {0}.|Please check the logs for more information.
+
+INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT=||Description: {0}.|Please check the logs for more information.
+
+INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT=||Description: {0}.|Please check the logs for more information.
+
+INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT=||Description: {0}.|Please check the logs for more information.
+
+BEHEALTHCHECKERROR= |||Please check the logs for more information.
+
+BEHEALTHCHECKMYSQLERROR= ||Please check the logs for more information.|\
+ Check connectivity to MYSQL is configured correctly under system.properties file.
+
+BEHEALTHCHECKUEBCLUSTERERROR= ||Please check the logs for more information.|\
+ Check connectivity to UEB cluster which is configured under portal.properties file.
+
+FEHEALTHCHECKERROR= |||Please check connectivity from this FE instance towards BE or BE Load Balancer.
+
+BEHEALTHCHECKRECOVERY= |||Please check logs for more specific information about the problem.
+
+BEHEALTHCHECKMYSQLRECOVERY= |||Please check logs for more specific information about the problem.
+
+BEHEALTHCHECKUEBCLUSTERRECOVERY= |||Please check logs for more specific information about the problem.
+
+FEHEALTHCHECKRECOVERY= |||Please check logs for more specific information about the problem.
+
+#UEB communication
+BEUEBCONNECTIONERROR_ONE_ARGUMENT= ||Reason: {0}.|\
+ Please check UEB server list and keys configured under Portal.Properties file.
+
+BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT= ||Cannot reach host {0}.|\
+ Please check UEB server list and keys configured under Portal.Properties file.
+
+#Onboarding apps
+BEUEBREGISTERONBOARDINGAPPERROR= ||Reason: {0}.|\
+ Please check UEB server list and keys configured under Portal.Properties file.
+
+#HTTP communication
+BEHTTPCONNECTIONERROR_ONE_ARGUMENT= ||Reason: {0}.|Please check the logs for more information.
+
+INTERNALCONNECTIONINFO_ONE_ARGUMENT= ||Description: {0}.|Please check the logs for more information.
+
+INTERNALCONNECTIONWARNING_ONE_ARGUMENT= ||Description: {0}.|Please check the logs for more information.
+
+INTERNALCONNECTIONERROR_ONE_ARGUMENT= ||Description: {0}.|Please check the logs for more information.
+
+INTERNALCONNECTIONFATAL_ONE_ARGUMENT= ||Description: {0}.|Please check the logs for more information.
+
+BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT= ||Data not found: {0}.|\
+ An error occurred during access to UEB Server, {1} failed to either register or unregister to/from UEB topic.
+
+#Login error codes
+BEUSERMISSINGERROR_ONE_ARGUMENT= |||\
+ User {0} must be added to the corresponding application with proper user roles.
+
+BEUSERINACTIVEWARNING_ONE_ARGUMENT= |||\
+ User {0} must be added to the corresponding application with proper user roles.
+
+BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT= |||\
+ User {0} should be given proper administrator role for the corresponding application to perform the necessary actions.
+
+BEINVALIDJSONINPUT= |||Please check error logs for more information.
+
+BEINCORRECTHTTPSTATUSERROR= |||Please check logs for more information.
+
+BEINITIALIZATIONERROR= |||Please check logs for more information.
+
+BEUEBSYSTEMERROR= ||\
+ Operation: {0}.|\
+ An error occurred in {1} distribution mechanism. Please check the logs for more information.
+
+BEDAOSYSTEMERROR= |||Please check MySQL DB health or look at the logs for more details.
+
+BESYSTEMERROR= |||Please check logs for more information.
+
+BEEXECUTEROLLBACKERROR= |||Please check MYSQL DB health or look at the logs for more details.
+
+FEHTTPLOGGINGERROR= |||Please check MYSQL DB health or look at the logs for more details.
+
+FEPORTALSERVLETERROR= |||Please check logs for more specific information about the problem.
+
+BEDAOCLOSESESSIONERROR= |||Please check MYSQL DB health or look at the logs form more details.
+
+BERESTAPIGENERALERROR= |||Please check error log for more information.
+
+FEHEALTHCHECKGENERALERROR= |||Please check error log for more information.
+
+INTERNALUNEXPECTEDINFO_ONE_ARGUMENT= |||Description: {0}.
+
+INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT= |||Description: {0}.
+
+INTERNALUNEXPECTEDERROR_ONE_ARGUMENT= |||Description: {0}.
+
+INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT= |||Description: {0}.
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/format/EPAppMessagesEnum.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/format/EPAppMessagesEnum.java
new file mode 100644
index 00000000..aae56e93
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/format/EPAppMessagesEnum.java
@@ -0,0 +1,260 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.logging.format;
+
+import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum;
+import org.openecomp.portalsdk.core.logging.format.ErrorSeverityEnum;
+import org.openecomp.portalsdk.core.logging.format.ErrorTypeEnum;
+
+/**
+ *
+ * @author rc580q
+ * Add ECOMP Portal Specific Error Code Enums here, for generic
+ * ones (ones you think are useful not only Portal but also SDK), add it
+ * to the enum class AppMessagesEnum defined in SDK.
+ */
+public enum EPAppMessagesEnum {
+ /*
+ 100-199 Security/Permission Related
+ - Authentication problems (from external client, to external server)
+ - Certification errors
+ -
+
+ 200-299 Availability/Timeout Related
+ - connectivity error
+ - connection timeout
+
+ 300-399 Data Access/Integrity Related
+ - Data in graph in invalid(E.g. no creator is found for service)
+ - Artifact is missing in ES, but exists in graph.
+
+ 400-499 Schema Interface Type/Validation
+ - received Pay-load checksum is invalid
+ - received JSON is not valid
+
+ 500-599 Business/Flow Processing Related
+ - check out to service is not allowed
+ - Roll-back is done
+ - failed to generate heat file
+
+
+ 600-899 Reserved - do not use
+
+ 900-999 Unknown Errors
+ - Unexpected exception
+ */
+
+ BeUebAuthenticationError(EPErrorCodesEnum.BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR100E", "An Authentication failure occurred during access to UEB server", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."),
+
+ 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."),
+
+ InternalAuthenticationWarning(EPErrorCodesEnum.INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN,
+ "ERR199W", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."),
+
+ InternalAuthenticationError(EPErrorCodesEnum.INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR199E", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."),
+
+ InternalAuthenticationFatal(EPErrorCodesEnum.INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT, ErrorTypeEnum.AUTHENTICATION_PROBLEM, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL,
+ "ERR199F", "Internal authentication problem", "Details: {0}.", "Please check the logs for more information."),
+
+ BeHealthCheckError(EPErrorCodesEnum.BeHEALTHCHECKERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
+ "ERR200E", "ECOMP-PORTAL Back-end probably lost connectivity to either one of the following components: MySQL DB, UEB Cluster", "", "Please check the logs for more information."),
+
+ BeHealthCheckMySqlError(EPErrorCodesEnum.BEHEALTHCHECKMYSQLERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
+ "ERR201E", "ECOMP-PORTAL Back-end probably lost connectivity to MySQL DB", "", "Check connectivity to MYSQL is configured correctly under system.properties file."),
+
+ BeHealthCheckUebClusterError(EPErrorCodesEnum.BEHEALTHCHECKUEBCLUSTERERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
+ "ERR203E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "", "Check connectivity to UEB cluster which is configured under portal.properties file."),
+
+ FeHealthCheckError(EPErrorCodesEnum.FEHEALTHCHECKERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
+ "ERR204E", "Unable to connect to a valid ECOMP-PORTAL Back-end Server.", "", "Please check connectivity from this FE instance towards BE or BE Load Balancer."),
+
+ BeHealthCheckRecovery(EPErrorCodesEnum.BEHEALTHCHECKRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
+ "ERR205I", "ECOMP-PORTAL Back-end Recovery to either one of the following components: MySQL DB, UEB Cluster", "", "Please check logs for more specific information about the problem."),
+
+ BeHealthCheckMySqlRecovery(EPErrorCodesEnum.BEHEALTHCHECKMYSQLRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
+ "ERR206I", "ECOMP-PORTAL Back-end connection recovery to MySQL DB", "", "Please check logs for more specific information about the problem."),
+
+ BeHealthCheckUebClusterRecovery(EPErrorCodesEnum.BEHEALTHCHECKUEBCLUSTERRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
+ "ERR208I", "ECOMP-PORTAL Back-end connection recovery to UEB Cluster", "", "Please check logs for more specific information about the problem."),
+
+ FeHealthCheckRecovery(EPErrorCodesEnum.FEHEALTHCHECKRECOVERY, ErrorTypeEnum.RECOVERY, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
+ "ERR209I", "Connectivity to ECOMP-PORTAL Front-end Server is recovered", "", "Please check logs for more specific information about the problem."),
+
+ BeUebConnectionError(EPErrorCodesEnum.BEUEBCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR210E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."),
+
+ BeUebUnkownHostError(EPErrorCodesEnum.BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR211E", "ECOMP-PORTAL Back-end probably lost connectivity to UEB Cluster", "Cannot reach host: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."),
+
+ BeUebRegisterOnboardingAppError(EPErrorCodesEnum.BEUEBREGISTERONBOARDINGAPPERROR, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR212E", "Failed to register the On-boarding application with UEB Communication server", "Details: {0}.", "Please check UEB server list and keys configured under Portal.Properties file."),
+
+ 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."),
+
+ InternalConnectionInfo(EPErrorCodesEnum.INTERNALCONNECTIONINFO_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
+ "ERR299I", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."),
+
+ InternalConnectionWarning(EPErrorCodesEnum.INTERNALCONNECTIONWARNING_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN,
+ "ERR299W", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."),
+
+ InternalConnectionError(EPErrorCodesEnum.INTERNALCONNECTIONERROR_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR299E", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."),
+
+ InternalConnectionFatal(EPErrorCodesEnum.INTERNALCONNECTIONFATAL_ONE_ARGUMENT, ErrorTypeEnum.CONNECTION_PROBLEM, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL,
+ "ERR299F", "Internal Connection problem", "Details: {0}.", "Please check logs for more information."),
+
+ BeUebObjectNotFoundError(EPErrorCodesEnum.BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR303E", "Error occurred during access to U-EB Server.", "Data not found: {0}.", "An error occurred during access to UEB Server, {1} failed to either register or unregister to/from UEB topic."),
+
+ BeUserMissingError(EPErrorCodesEnum.BEUSERMISSINGERROR_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR310E", "User is not found", "", "User {0} must be added to the corresponding application with proper user roles."),
+
+ BeUserInactiveWarning(EPErrorCodesEnum.BEUSERINACTIVEWARNING_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN,
+ "ERR313W", "User is found but in-active", "", "User {0} must be added to the corresponding application with proper user roles."),
+
+ BeUserAdminPrivilegesInfo(EPErrorCodesEnum.BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN,
+ "ERR314W", "User is found but don't have administrative privileges", "", "User {0} should be given administrator role for the corresponding application to perform the necessary actions."),
+
+ BeInvalidJsonInput(EPErrorCodesEnum.BEINVALIDJSONINPUT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR405E", "Failed to convert JSON input to object", "", "Please check logs for more information."),
+
+ BeIncorrectHttpStatusError(EPErrorCodesEnum.BEINCORRECTHTTPSTATUSERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR407E", "Communication to an external application is resulted in with Incorrect Http response code", "", "Please check logs for more information."),
+
+ BeInitializationError(EPErrorCodesEnum.BEINITIALIZATIONERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
+ "ERR500E", "ECOMP-PORTAL Back-end was not initialized properly", "", "Please check logs for more information."),
+
+ BeUebSystemError(EPErrorCodesEnum.BEUEBSYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR502E", "Error occurred during access to U-EB Server", "Details: {0}.", "An error occurred in {1} distribution mechanism. Please check the logs for more information."),
+
+ BeDaoSystemError(EPErrorCodesEnum.BEDAOSYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
+ "ERR505E", "Performing DDL or DML operations on database might have failed", "", "Please check MySQL DB health or look at the logs for more details."),
+
+ BeSystemError(EPErrorCodesEnum.BESYSTEMERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
+ "ERR506E", "Unexpected error during operation", "", "Please check logs for more information."),
+
+ BeExecuteRollbackError(EPErrorCodesEnum.BEEXECUTEROLLBACKERROR, ErrorTypeEnum.DATA_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR507E", "Roll-back operation towards database has failed", "", "Please check MYSQL DB health or look at the logs for more details."),
+
+ FeHttpLoggingError(EPErrorCodesEnum.FEHTTPLOGGINGERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.ERROR,
+ "ERR517E", "Error when logging FE HTTP request/response", "", "Please check MYSQL DB health or look at the logs for more details."),
+
+ FePortalServletError(EPErrorCodesEnum.FEPORTALSERVLETERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR518E", "Error when trying to access FE Portal page.", "", "Please check logs for more information."),
+
+ BeDaoCloseSessionError(EPErrorCodesEnum.BEDAOCLOSESESSIONERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR519E", "Close local session operation with database failed", "", "Please check MYSQL DB health or look at the logs form more details."),
+
+ BeRestApiGeneralError(EPErrorCodesEnum.BERESTAPIGENERALERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
+ "ERR900E", "Unexpected error during ECOMP-PORTAL Back-end REST API execution", "", "Please check error log for more information."),
+
+ FeHealthCheckGeneralError(EPErrorCodesEnum.FEHEALTHCHECKGENERALERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.ERROR,
+ "ERR901E", "General error during FE Health Check", "", "Please check error log for more information."),
+
+ InternalUnexpectedInfo(EPErrorCodesEnum.INTERNALUNEXPECTEDINFO_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.INFORMATIONAL, ErrorSeverityEnum.INFO,
+ "ERR999I", "Unexpected error", "Details: {0}.", "Please check logs for more information."),
+
+ InternalUnexpectedWarning(EPErrorCodesEnum.INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MINOR, ErrorSeverityEnum.WARN,
+ "ERR999W", "Unexpected error", "Details: {0}.", "Please check logs for more information."),
+
+ InternalUnexpectedError(EPErrorCodesEnum.INTERNALUNEXPECTEDERROR_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR,
+ "ERR999E", "Unexpected error", "Details: {0}.", "Please check logs for more information."),
+
+ InternalUnexpectedFatal(EPErrorCodesEnum.INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.CRITICAL, ErrorSeverityEnum.FATAL,
+ "ERR999F", "Unexpected error", "Details: {0}.", "Please check logs for more information."),
+
+ ;
+
+ ErrorTypeEnum eType;
+ AlarmSeverityEnum alarmSeverity;
+ EPErrorCodesEnum messageCode;
+ ErrorSeverityEnum errorSeverity;
+ String errorCode;
+ String errorDescription;
+ String details;
+ String resolution;
+
+ EPAppMessagesEnum(EPErrorCodesEnum messageCode, ErrorTypeEnum eType, AlarmSeverityEnum alarmSeverity, ErrorSeverityEnum errorSeverity, String errorCode, String errorDescription,
+ String details, String resolution) {
+ this.messageCode = messageCode;
+ this.eType = eType;
+ this.alarmSeverity = alarmSeverity;
+ this.errorSeverity = errorSeverity;
+ this.errorCode = errorCode;
+ this.errorDescription = errorDescription;
+ this.details = details;
+ this.resolution = resolution;
+ }
+
+ public String getDetails() {
+ return this.details;
+ }
+
+ public String getResolution() {
+ return this.resolution;
+ }
+ public String getErrorCode() {
+ return this.errorCode;
+ }
+
+ public String getErrorDescription() {
+ return this.errorDescription;
+ }
+
+ public ErrorSeverityEnum getErrorSeverity() {
+ return this.errorSeverity;
+ }
+
+ public void setErrorSeverity(ErrorSeverityEnum errorSeverity) {
+ this.errorSeverity = errorSeverity;
+ }
+
+ public EPErrorCodesEnum getMessageCode() {
+ return messageCode;
+ }
+
+ public void setMessageCode(EPErrorCodesEnum messageCode) {
+ this.messageCode = messageCode;
+ }
+
+ public AlarmSeverityEnum getAlarmSeverity() {
+ return alarmSeverity;
+ }
+
+ public void setAlarmSeverity(AlarmSeverityEnum alarmSeverity) {
+ this.alarmSeverity = alarmSeverity;
+ }
+
+ public ErrorTypeEnum getErrorType() {
+ return eType;
+ }
+
+ public void setErrorType(ErrorTypeEnum eType) {
+ this.eType = eType;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/format/EPErrorCodesEnum.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/format/EPErrorCodesEnum.java
new file mode 100644
index 00000000..39771e3d
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/format/EPErrorCodesEnum.java
@@ -0,0 +1,95 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.logging.format;
+
+import com.att.eelf.i18n.EELFResolvableErrorEnum;
+import com.att.eelf.i18n.EELFResourceManager;
+
+/**
+ *
+ * @author rc580q
+ * Add ECOMP Portal Specific Error Code Enums here, for generic
+ * ones (ones you think are useful not only Portal but also SDK), add it
+ * to the enum class AppMessagesEnum defined in SDK.
+ */
+public enum EPErrorCodesEnum implements EELFResolvableErrorEnum {
+ BERESTAPIAUTHENTICATIONERROR,
+ BEHTTPCONNECTIONERROR_ONE_ARGUMENT,
+ BEUEBAUTHENTICATIONERROR_ONE_ARGUMENT,
+
+ INTERNALAUTHENTICATIONINFO_ONE_ARGUMENT,
+ INTERNALAUTHENTICATIONWARNING_ONE_ARGUMENT,
+ INTERNALAUTHENTICATIONERROR_ONE_ARGUMENT,
+ INTERNALAUTHENTICATIONFATAL_ONE_ARGUMENT,
+
+ BEHEALTHCHECKRECOVERY,
+ BEHEALTHCHECKMYSQLRECOVERY,
+ BEHEALTHCHECKUEBCLUSTERRECOVERY,
+ FEHEALTHCHECKRECOVERY,
+ BeHEALTHCHECKERROR,
+
+ BEHEALTHCHECKMYSQLERROR,
+ BEHEALTHCHECKUEBCLUSTERERROR,
+ FEHEALTHCHECKERROR,
+ BEUEBCONNECTIONERROR_ONE_ARGUMENT,
+ BEUEBUNKOWNHOSTERROR_ONE_ARGUMENT,
+ BEUEBREGISTERONBOARDINGAPPERROR,
+
+ INTERNALCONNECTIONINFO_ONE_ARGUMENT,
+ INTERNALCONNECTIONWARNING_ONE_ARGUMENT,
+ INTERNALCONNECTIONERROR_ONE_ARGUMENT,
+ INTERNALCONNECTIONFATAL_ONE_ARGUMENT,
+
+ BEUEBOBJECTNOTFOUNDERROR_ONE_ARGUMENT,
+ BEUSERMISSINGERROR_ONE_ARGUMENT,
+
+ BEUSERINACTIVEWARNING_ONE_ARGUMENT,
+ BEUSERADMINPRIVILEGESINFO_ONE_ARGUMENT,
+
+ BEINVALIDJSONINPUT,
+ BEINCORRECTHTTPSTATUSERROR,
+
+ BEINITIALIZATIONERROR,
+ BEUEBSYSTEMERROR,
+ BEDAOSYSTEMERROR,
+ BESYSTEMERROR,
+ BEEXECUTEROLLBACKERROR,
+
+ FEHTTPLOGGINGERROR,
+ FEPORTALSERVLETERROR,
+ BEDAOCLOSESESSIONERROR,
+
+ BERESTAPIGENERALERROR,
+ FEHEALTHCHECKGENERALERROR,
+
+ INTERNALUNEXPECTEDINFO_ONE_ARGUMENT,
+ INTERNALUNEXPECTEDWARNING_ONE_ARGUMENT,
+ INTERNALUNEXPECTEDERROR_ONE_ARGUMENT,
+ INTERNALUNEXPECTEDFATAL_ONE_ARGUMENT,
+ ;
+
+ /**
+ * Static initializer to ensure the resource bundles for this class are loaded...
+ * Here this application loads messages from three bundles
+ */
+ static {
+ EELFResourceManager.loadMessageBundle("org/openecomp/portalapp/portal/logging/format/ApplicationCodes");
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/logic/EPLogUtil.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/logic/EPLogUtil.java
new file mode 100644
index 00000000..489a68a8
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/logging/logic/EPLogUtil.java
@@ -0,0 +1,76 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.logging.logic;
+
+import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY;
+
+import java.text.MessageFormat;
+
+import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
+import org.openecomp.portalsdk.core.logging.format.AlarmSeverityEnum;
+import org.openecomp.portalsdk.core.logging.format.ErrorSeverityEnum;
+import org.openecomp.portalsdk.core.web.support.UserUtils;
+import org.slf4j.MDC;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+
+public class EPLogUtil {
+ private static EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger();
+ public static void logEcompError(EPAppMessagesEnum epMessageEnum, String... param) {
+ try {
+ AlarmSeverityEnum alarmSeverityEnum = epMessageEnum.getAlarmSeverity();
+ ErrorSeverityEnum errorSeverityEnum = epMessageEnum.getErrorSeverity();
+
+ MDC.put(MDC_ALERT_SEVERITY, alarmSeverityEnum.name());
+ MDC.put("ErrorCode", epMessageEnum.getErrorCode());
+ MDC.put("ErrorDescription", epMessageEnum.getErrorDescription());
+ MDC.put("ClassName", EPLogUtil.class.getName());
+
+ String resolution = EPLogUtil.formatMessage(epMessageEnum.getDetails() + " " + epMessageEnum.getResolution(), (Object[]) param);
+ if (errorSeverityEnum == ErrorSeverityEnum.WARN) {
+ errorLogger.warn(resolution);
+ } else if(errorSeverityEnum == ErrorSeverityEnum.INFO) {
+ errorLogger.info(resolution);
+ } else {
+ errorLogger.error(resolution);
+ }
+ } catch(Exception e) {
+ errorLogger.error("Failed to log the error code. Details: " + UserUtils.getStackTrace(e));
+ } finally {
+ MDC.remove("ErrorCode");
+ MDC.remove("ErrorDescription");
+ MDC.remove("ClassName");
+ MDC.remove(MDC_ALERT_SEVERITY);
+ }
+ }
+
+ public static String formatMessage(String message, Object...args) {
+ StringBuilder sbFormattedMessage = new StringBuilder();
+ if (args!=null && args.length>0 && message!=null && message != "") {
+ MessageFormat mf = new MessageFormat(message);
+ sbFormattedMessage.append(mf.format(args));
+ } else {
+ sbFormattedMessage.append(message);
+ }
+
+ return sbFormattedMessage.toString();
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesService.java
new file mode 100644
index 00000000..c399d891
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesService.java
@@ -0,0 +1,52 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.transport.AppsListWithAdminRole;
+
+public interface AdminRolesService {
+
+ public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(String orgUserId);
+
+ public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles);
+
+ /**
+ * Attention! User roles in ECOMP PORTAL cannot be managed by this function.
+ * @param user
+ * @return 'true' if user has Super Administrator role SYS_ADMIN_ROLE_ID (1 for now) in ECOMP PORTAL, 'false' otherwise
+ */
+ public boolean isSuperAdmin(EPUser user);
+
+ /**
+ * Attention! User roles in ECOMP PORTAL cannot be managed by this function.
+ * @param user
+ * @return 'true' if user has Account Administrator role ACCOUNT_ADMIN_ROLE_ID (999 for now) for any application except ECOMP Portal, 'false' otherwise
+ */
+ public boolean isAccountAdmin(EPUser user);
+
+ /**
+ * Attention! User roles in ECOMP PORTAL cannot be managed by this function.
+ * @param user
+ * @return 'true' if user has any remote(!) role within any application (ECOMP Portal roles are not included), 'false' otherwise
+ */
+ public boolean isUser(EPUser user);
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesServiceImpl.java
new file mode 100644
index 00000000..508bd3d6
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesServiceImpl.java
@@ -0,0 +1,318 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import javax.annotation.PostConstruct;
+
+import org.apache.cxf.common.util.StringUtils;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.Transaction;
+import org.openecomp.portalapp.portal.domain.EPApp;
+import org.openecomp.portalapp.portal.domain.EPRole;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.domain.EPUserApp;
+import org.openecomp.portalapp.portal.domain.UserIdRoleId;
+import org.openecomp.portalapp.portal.domain.UserRole;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
+import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
+import org.openecomp.portalapp.portal.transport.AppNameIdIsAdmin;
+import org.openecomp.portalapp.portal.transport.AppsListWithAdminRole;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.service.DataAccessService;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service("adminRolesService")
+@Transactional
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class AdminRolesServiceImpl implements AdminRolesService {
+
+ private Long SYS_ADMIN_ROLE_ID = 1L;
+ private Long ACCOUNT_ADMIN_ROLE_ID = 999L;
+ private Long ECOMP_APP_ID = 1L;
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesServiceImpl.class);
+
+ @Autowired
+ private SessionFactory sessionFactory;
+ @Autowired
+ private DataAccessService dataAccessService;
+ @Autowired
+ SearchService searchService;
+ @Autowired
+ EPAppService appsService;
+
+ @PostConstruct
+ private void init() {
+ try {
+ SYS_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPSystemProperties.SYS_ADMIN_ROLE_ID));
+ ACCOUNT_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPSystemProperties.ACCOUNT_ADMIN_ROLE_ID));
+ ECOMP_APP_ID = Long.valueOf(SystemProperties.getProperty(EPSystemProperties.ECOMP_APP_ID));
+ } catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(String orgUserId) {
+ AppsListWithAdminRole appsListWithAdminRole = null;
+
+ try {
+ List<EPUser> userList = dataAccessService.getList(EPUser.class, " where org_user_id = '" + orgUserId + "'", null,
+ null);
+ HashMap<Long, Long> appsUserAdmin = new HashMap<Long, Long>();
+ if (userList.size() > 0) {
+ EPUser user = userList.get(0);
+ List<EPUserApp> userAppList = null;
+ try {
+ userAppList = dataAccessService.getList(EPUserApp.class,
+ " where userId = " + user.getId() + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID, null, null);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ }
+ for (EPUserApp userApp : userAppList) {
+ appsUserAdmin.put(userApp.getAppId(), userApp.getUserId());
+ }
+ }
+
+ appsListWithAdminRole = new AppsListWithAdminRole();
+ appsListWithAdminRole.orgUserId = orgUserId;
+ List<EPApp> appsList = null;
+ try {
+ appsList = dataAccessService.getList(EPApp.class, " where enabled = 'Y'", null, null);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ }
+ for (EPApp app : appsList) {
+ AppNameIdIsAdmin appNameIdIsAdmin = new AppNameIdIsAdmin();
+ appNameIdIsAdmin.id = app.getId();
+ appNameIdIsAdmin.appName = app.getName();
+ appNameIdIsAdmin.isAdmin = new Boolean(appsUserAdmin.containsKey(app.getId()));
+ appNameIdIsAdmin.restrictedApp = app.isRestrictedApp();
+ appsListWithAdminRole.appsRoles.add(appNameIdIsAdmin);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing AdminRolesServiceImpl.getAppsWithAdminRoleStateForUser operation, Details:"
+ + EcompPortalUtils.getStackTrace(e));
+ }
+
+ return appsListWithAdminRole;
+ }
+
+ private static final Object syncRests = new Object();
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public boolean setAppsWithAdminRoleStateForUser(AppsListWithAdminRole newAppsListWithAdminRoles) {
+ boolean result = false;
+ // No changes if no new roles list or no userId.
+ if (!StringUtils.isEmpty(newAppsListWithAdminRoles.orgUserId) && newAppsListWithAdminRoles.appsRoles != null) {
+ synchronized (syncRests) {
+ List<EPApp> apps = appsService.getAppsFullList();
+ HashMap<Long, EPApp> enabledApps = new HashMap<Long, EPApp>();
+ for (EPApp app : apps) {
+ if (app.getEnabled().booleanValue()) {
+ enabledApps.put(app.getId(), app);
+ }
+ }
+ List<AppNameIdIsAdmin> newAppsWhereUserIsAdmin = new ArrayList<AppNameIdIsAdmin>();
+ for (AppNameIdIsAdmin adminRole : newAppsListWithAdminRoles.appsRoles) {
+ // user Admin role may be added only for enabled apps
+ if (adminRole.isAdmin.booleanValue() && enabledApps.containsKey(adminRole.id)) {
+ newAppsWhereUserIsAdmin.add(adminRole);
+ }
+ }
+ EPUser user = null;
+ boolean createNewUser = false;
+ String orgUserId = newAppsListWithAdminRoles.orgUserId.trim();
+ List<EPUser> localUserList = dataAccessService.getList(EPUser.class, " where org_user_id='" + orgUserId + "'",
+ null, null);
+ List<EPUserApp> oldAppsWhereUserIsAdmin = new ArrayList<EPUserApp>();
+ if (localUserList.size() > 0) {
+ EPUser tmpUser = localUserList.get(0);
+ oldAppsWhereUserIsAdmin = dataAccessService.getList(EPUserApp.class,
+ " where userId = " + tmpUser.getId() + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID, null,
+ null);
+ if (oldAppsWhereUserIsAdmin.size() > 0 || newAppsWhereUserIsAdmin.size() > 0) {
+ user = tmpUser;
+ }
+ } else if (newAppsWhereUserIsAdmin.size() > 0) {
+ // we create new user only if he has Admin Role for any App
+ createNewUser = true;
+ }
+ if (user != null || createNewUser) {
+ Session localSession = null;
+ Transaction transaction = null;
+ try {
+ localSession = sessionFactory.openSession();
+ transaction = localSession.beginTransaction();
+ if (createNewUser) {
+ user = this.searchService.searchUserByUserId(orgUserId);
+ if (user != null) {
+ // insert the user with active true in order to
+ // pass login phase.
+ user.setActive(true);
+ localSession.save(EPUser.class.getName(), user);
+ }
+ }
+ for (EPUserApp oldUserApp : oldAppsWhereUserIsAdmin) {
+ // user Admin role may be deleted only for enabled
+ // apps
+ if (enabledApps.containsKey(oldUserApp.getAppId())) {
+ localSession.delete(oldUserApp);
+ }
+ }
+ for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) {
+ EPApp app = (EPApp) localSession.get(EPApp.class, appNameIdIsAdmin.id);
+ EPRole role = (EPRole) localSession.get(EPRole.class, new Long(ACCOUNT_ADMIN_ROLE_ID));
+ EPUserApp newUserApp = new EPUserApp();
+ newUserApp.setUserId(user.getId());
+ newUserApp.setApp(app);
+ newUserApp.setRole(role);
+ localSession.save(EPUserApp.class.getName(), newUserApp);
+ }
+ transaction.commit();
+ result = true;
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 2 = "
+ + EcompPortalUtils.getStackTrace(e));
+ try {
+ transaction.rollback();
+ } catch (Exception ex) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeExecuteRollbackError);
+ logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 3 = "
+ + EcompPortalUtils.getStackTrace(ex));
+ }
+ } finally {
+ try {
+ localSession.close();
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoCloseSessionError);
+ logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 4 = "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+ }
+ }
+ }
+ }
+
+ return result;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public boolean isSuperAdmin(EPUser user) {
+ if ((user != null) /* && (user.getId() == null) */ && (user.getOrgUserId() != null)) {
+ String sql = "SELECT user.USER_ID, user.ORG_USER_ID, userrole.ROLE_ID, userrole.APP_ID FROM fn_user_role userrole "
+ + "INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID " + "WHERE user.ORG_USER_ID = '"
+ + user.getOrgUserId() + "' " + "AND userrole.ROLE_ID = '" + SYS_ADMIN_ROLE_ID + "' "
+ + "AND userrole.APP_ID = '" + ECOMP_APP_ID + "';";
+ try {
+ List<UserRole> userRoleList = dataAccessService.executeSQLQuery(sql, UserIdRoleId.class, null);
+ if (userRoleList != null && userRoleList.size() > 0) {
+ return true;
+ }
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isSuperAdmin operation, Details: "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+ }
+ // else
+ // {
+ // User currentUser = user != null ? (User)
+ // dataAccessService.getDomainObject(User.class, user.getId(), null) :
+ // null;
+ // if (currentUser != null && currentUser.getId() != null) {
+ // for (UserApp userApp : currentUser.getUserApps()) {
+ // if (userApp.getApp().getId().equals(ECOMP_APP_ID) &&
+ // userApp.getRole().getId().equals(SYS_ADMIN_ROLE_ID)) {
+ // // Super Administrator role is global, no need to keep iterating
+ // return true;
+ // }
+ // }
+ // }
+ // }
+ return false;
+ }
+
+ public boolean isAccountAdmin(EPUser user) {
+ try {
+ EPUser currentUser = user != null
+ ? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null) : null;
+ if (currentUser != null && currentUser.getId() != null) {
+ for (EPUserApp userApp : currentUser.getEPUserApps()) {
+ if (!userApp.getApp().getId().equals(ECOMP_APP_ID)
+ && userApp.getRole().getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
+ // Account Administrator sees only the applications
+ // he/she is Administrator
+ return true;
+ }
+ }
+ }
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isAccountAdmin operation, Details: "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+ return false;
+ }
+
+ public boolean isUser(EPUser user) {
+ try {
+ EPUser currentUser = user != null
+ ? (EPUser) dataAccessService.getDomainObject(EPUser.class, user.getId(), null) : null;
+ if (currentUser != null && currentUser.getId() != null) {
+ for (EPUserApp userApp : currentUser.getEPUserApps()) {
+ if (!userApp.getApp().getId().equals(ECOMP_APP_ID)) {
+ EPRole role = userApp.getRole();
+ if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
+ if (role.getActive()) {
+ return true;
+ }
+ }
+ }
+ }
+ }
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation, Details: "
+ + EcompPortalUtils.getStackTrace(e));
+ }
+ return false;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AppContactUsService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AppContactUsService.java
new file mode 100644
index 00000000..c81f2938
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AppContactUsService.java
@@ -0,0 +1,55 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.List;
+
+import org.openecomp.portalapp.portal.ecomp.model.AppCategoryFunctionsItem;
+import org.openecomp.portalapp.portal.ecomp.model.AppContactUsItem;
+
+public interface AppContactUsService {
+
+ /**
+ * Gets a list of contact-us information for all entries in
+ * the fn_app_contact_us table, sorted by app name. If an application is active but has no fn_app_contact_us entry, it will have no entry in this result.
+ *
+ * @return List of AppContactUsItem, one for each item in fn_app_contact_us table.
+ * @throws Exception
+ */
+ public List<AppContactUsItem> getAppContactUs() throws Exception;
+
+ /**
+ * Gets a list of contact-us information for all applications
+ * in the fn_app table, extended with any information in the fn_app_contact_us table.
+ *
+ * @return List of AppContactUsItem, one for each item in fn_app table.
+ * @throws Exception
+ */
+ public List<AppContactUsItem> getAppsAndContacts() throws Exception;
+
+ public List<AppCategoryFunctionsItem> getAppCategoryFunctions() throws Exception;
+
+ public String saveAppContactUs(List<AppContactUsItem> contactUs) throws Exception;
+
+ public String saveAppContactUs(AppContactUsItem contactUs) throws Exception;
+
+ public String deleteContactUs(Long id) throws Exception;
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AppContactUsServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AppContactUsServiceImpl.java
new file mode 100644
index 00000000..7a2f6206
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AppContactUsServiceImpl.java
@@ -0,0 +1,178 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+
+import org.openecomp.portalapp.portal.domain.AppContactUs;
+import org.openecomp.portalapp.portal.domain.EPApp;
+import org.openecomp.portalapp.portal.ecomp.model.AppCategoryFunctionsItem;
+import org.openecomp.portalapp.portal.ecomp.model.AppContactUsItem;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.service.DataAccessService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.transaction.annotation.Transactional;
+
+/**
+ * Provides database access for the contact-us page controllers.
+ */
+@Transactional
+@org.springframework.context.annotation.Configuration
+public class AppContactUsServiceImpl implements AppContactUsService {
+
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppContactUsServiceImpl.class);
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<AppContactUsItem> getAppContactUs() throws Exception {
+ List<AppContactUsItem> contactUsItemList = (List<AppContactUsItem>) getDataAccessService()
+ .executeNamedQuery("getAppContactUsItems", null, null);
+ Collections.sort(contactUsItemList, new AppContactUsItemCompare());
+ return contactUsItemList;
+ }
+
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<AppContactUsItem> getAppsAndContacts() throws Exception {
+ List<AppContactUsItem> contactUsItemList = (List<AppContactUsItem>) getDataAccessService()
+ .executeNamedQuery("getAppsAndContacts", null, null);
+ Collections.sort(contactUsItemList, new AppContactUsItemCompare());
+ return contactUsItemList;
+ }
+
+ /**
+ * Assists in sorting app-contact-us items by application name.
+ */
+ class AppContactUsItemCompare implements Comparator<AppContactUsItem> {
+ @Override
+ public int compare(AppContactUsItem o1, AppContactUsItem o2) {
+ return o1.getAppName().compareTo(o2.getAppName());
+ }
+ }
+
+ /**
+ * Gets a table of category and function details for apps that participate
+ * in the functional menu.
+ */
+ @Override
+ public List<AppCategoryFunctionsItem> getAppCategoryFunctions() throws Exception {
+ @SuppressWarnings("unchecked")
+ // This named query requires no parameters.
+ List<AppCategoryFunctionsItem> list = (List<AppCategoryFunctionsItem>) dataAccessService
+ .executeNamedQuery("getAppCategoryFunctions", null, null);
+ logger.debug(EELFLoggerDelegate.debugLogger, "getAppCategoryFunctions: result list size is " + list.size());
+ return list;
+ }
+
+ /**
+ * Saves the list of contact-us objects to the database.
+ */
+ @Override
+ @Transactional(rollbackFor = Exception.class)
+ public String saveAppContactUs(List<AppContactUsItem> contactUsModelList) throws Exception {
+ try {
+ for (AppContactUsItem contactUs : contactUsModelList) {
+ String status = saveAppContactUs(contactUs);
+ if (!status.equals("success"))
+ throw new Exception("saveAppContaatUsFailed: service returned " + status);
+ }
+ return "success";
+
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "", e);
+ throw new Exception(e);
+ }
+
+ }
+
+ /**
+ * Saves a single contact-us object to the database, either creating a new
+ * row or updating if the argument has the ID of an existing row.
+ */
+ @Override
+ @Transactional(rollbackFor = Exception.class)
+ public String saveAppContactUs(AppContactUsItem contactUsModel) throws Exception {
+ try {
+ HashMap<String, Object> map = new HashMap<String, Object>();
+ AppContactUs contactUs = null;
+ try {
+ contactUs = (AppContactUs) getDataAccessService().getDomainObject(AppContactUs.class,
+ contactUsModel.getAppId(), map);
+ } catch (Exception e) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "saveAppContactUs: not found for App {}, adding new entry",
+ contactUsModel.getAppName());
+ contactUs = new AppContactUs();
+ }
+
+ // Populate the AppContactUs model for the database.
+ EPApp app = (EPApp) getDataAccessService().getDomainObject(EPApp.class, contactUsModel.getAppId(), map);
+ if (app == null || app.getId() == null)
+ throw new Exception("saveAppContactus: App not found for Id " + contactUsModel.getAppId());
+ contactUs.setApp(app);
+ contactUs.setDescription(contactUsModel.getDescription());
+ contactUs.setContactName(contactUsModel.getContactName());
+ contactUs.setContactEmail(contactUsModel.getContactEmail());
+ contactUs.setActiveYN(contactUsModel.getActiveYN());
+ contactUs.setUrl(contactUsModel.getUrl());
+ getDataAccessService().saveDomainObject(contactUs, map);
+ return "success";
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "saveAppContactUs failed", e);
+ throw e;
+ // return "failure";
+ }
+ }
+
+ /**
+ * Deletes the row from the app contact us table with the specified ID.
+ */
+ @Override
+ public String deleteContactUs(Long id) throws Exception {
+ try {
+ HashMap<String, Object> map = new HashMap<String, Object>();
+ AppContactUs contactUs = (AppContactUs) getDataAccessService().getDomainObject(AppContactUs.class, id, map);
+ if (contactUs.getApp() == null)
+ throw new Exception("Delete unsuccessful for Id " + id);
+ getDataAccessService().deleteDomainObject(contactUs, map);
+ return "success";
+ } catch (Exception e) {
+
+ logger.info(EELFLoggerDelegate.errorLogger, "", e);
+ throw e;
+ }
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientService.java
new file mode 100644
index 00000000..2ed9820d
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientService.java
@@ -0,0 +1,28 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import org.apache.cxf.transport.http.HTTPException;
+
+public interface ApplicationsRestClientService {
+ public <T> T get(Class<T> clazz, long app, String restPath) throws HTTPException;
+ public <T> T post(Class<T> clazz, long appId, Object payload, String restPath) throws HTTPException ;
+ public <T> T put(Class<T> clazz, long appId, Object payload, String restPath) throws HTTPException ;
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientServiceImpl.java
new file mode 100644
index 00000000..c18fe304
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/ApplicationsRestClientServiceImpl.java
@@ -0,0 +1,267 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
+
+import java.lang.reflect.Type;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Date;
+
+import javax.annotation.PostConstruct;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.apache.cxf.transport.http.HTTPException;
+import org.openecomp.portalapp.portal.domain.EPApp;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
+import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.util.CipherUtil;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParseException;
+
+@Service("applicationsRestClientService")
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class ApplicationsRestClientServiceImpl implements ApplicationsRestClientService{
+
+ private static final String PASSWORD_HEADER = "password";
+
+ private static final String APP_USERNAME_HEADER = "username";
+
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ApplicationsRestClientServiceImpl.class);
+
+ @Autowired
+ private AppsCacheService appsCacheService;
+ Gson gson = null;
+
+ @PostConstruct
+ private void init(){
+ logger.debug(EELFLoggerDelegate.debugLogger, "initializing");
+ GsonBuilder builder = new GsonBuilder();
+
+ // Register an adapter to manage the date types as long values
+ builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
+ public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
+ return new Date(json.getAsJsonPrimitive().getAsLong());
+ }
+ });
+
+ gson = builder.create();
+ }
+
+ // TODO: do we need to do additional logging for remote API calls?
+ private static WebClient createClientForPath(String baseUri, String path) {
+ logger.info(EELFLoggerDelegate.debugLogger, "Creating web client for " + baseUri + " + " + path);
+ WebClient client = WebClient.create(baseUri);
+ client.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
+ client.path(path);
+ return client;
+ }
+
+ @EPMetricsLog
+ private void verifyResponse(Response response) throws HTTPException {
+ int status = response.getStatus();
+ logger.debug(EELFLoggerDelegate.debugLogger, "http response status=" + status);
+ MDC.put(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(status));
+ if (!isHttpSuccess(status)) {
+ String errMsg = "Failed. Status=" + status + "; [" + response.getStatusInfo().getReasonPhrase().toString() + "]";
+ URL url = null;
+ try {
+ // must not be null to avoid NPE in HTTPException constructor
+ url = new URL("http://null");
+ if (response.getLocation() != null)
+ url = response.getLocation().toURL();
+ } catch (MalformedURLException e) {
+ // never mind. it is only for the debug message.
+ logger.warn(EELFLoggerDelegate.errorLogger, "Failed to build URL", e);
+ }
+ logger.error(EELFLoggerDelegate.errorLogger, "http response failed. " + errMsg + "; url=" + url);
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeIncorrectHttpStatusError);
+ throw new HTTPException(status, errMsg, url);
+ }
+ }
+
+ private static boolean isHttpSuccess(int status){
+ return status / 100 == 2;
+ }
+
+ @EPMetricsLog
+ private WebClient createClientForApp(long appId, String restPath) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "creating client for appId=" + appId + "; restPath=" + restPath);
+ EPApp externalApp = appsCacheService.getApp(appId);
+ if(externalApp != null){
+ String appBaseUri = externalApp.getAppRestEndpoint();
+ String username = externalApp.getUsername();
+ String encriptedPwd = externalApp.getAppPassword();
+ String decreptedAppPwd = "";
+
+ //Set local context
+ MDC.put(EPSystemProperties.PROTOCOL, EPSystemProperties.HTTP);
+ if (appBaseUri!=null && appBaseUri.contains("https")) {
+ MDC.put(EPSystemProperties.PROTOCOL, EPSystemProperties.HTTPS);
+ }
+ MDC.put(EPSystemProperties.FULL_URL, appBaseUri + restPath);
+ MDC.put(EPSystemProperties.TARGET_ENTITY, externalApp.getName());
+ MDC.put(EPSystemProperties.TARGET_SERVICE_NAME, restPath);
+
+ try {
+ decreptedAppPwd = CipherUtil.decrypt(encriptedPwd, SystemProperties.getProperty(SystemProperties.Decryption_Key));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Unable to decrypt App name = " + externalApp, EcompPortalUtils.getStackTrace(e));
+ logger.error(EELFLoggerDelegate.errorLogger, "Unable to decrypt App name = " + externalApp, EcompPortalUtils.getStackTrace(e));
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger, String.format("App %d found, baseUri=[%s], Headers: [%s=%s, %s=%s]", appId, appBaseUri, APP_USERNAME_HEADER, username, PASSWORD_HEADER, encriptedPwd));
+ WebClient client = createClientForPath(appBaseUri, restPath);
+ client.header(APP_USERNAME_HEADER, username);
+ client.header(PASSWORD_HEADER, decreptedAppPwd);
+ client.header(SystemProperties.ECOMP_REQUEST_ID, MDC.get(MDC_KEY_REQUEST_ID));
+ client.header(SystemProperties.USERAGENT_NAME, EPSystemProperties.ECOMP_PORTAL_BE);
+
+ return client;
+ }
+ return null;
+ }
+
+ @Override
+ public <T> T get(Class<T> clazz, long appId, String restPath) throws HTTPException {
+
+ WebClient webClient = null;
+ Response response = null;
+ T t = null;
+
+ webClient = createClientForApp(appId, restPath);
+ EcompPortalUtils.logAndSerializeObject(restPath, "GET request =", "no-payload");
+
+ try {
+ if (webClient!=null) {
+ response = webClient.get();
+ } else {
+ logger.error(EELFLoggerDelegate.errorLogger, "Unable to create the Webclient to make the '" + restPath + "' API call.");
+ }
+ } catch (Exception e) {
+ MDC.put(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeRestApiGeneralError);
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while making the GET REST API call, Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+
+ if (response!=null) {
+ verifyResponse(response);
+ String str = response.readEntity(String.class);
+ EcompPortalUtils.logAndSerializeObject(restPath, "GET result =", str);
+ try { t = gson.fromJson(str, clazz); } catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput);
+ }
+ }
+
+ return t;
+ }
+
+ @Override
+ public <T> T post(Class<T> clazz, long appId, Object payload, String restPath) throws HTTPException {
+ WebClient client = null;
+ Response response = null;
+ T t = null;
+
+ client = createClientForApp(appId, restPath);
+ EcompPortalUtils.logAndSerializeObject(restPath, "POST request =", payload);
+
+
+ try {
+ if (client!=null) {
+ response = client.post(payload);
+ } else {
+ logger.error(EELFLoggerDelegate.errorLogger, "Unable to create the Webclient to make the '" + restPath + "' API call.");
+ }
+ } catch (Exception e) {
+ MDC.put(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeRestApiGeneralError);
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while making the POST REST API call, Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+
+ if (response!=null) {
+ verifyResponse(response);
+
+ //String contentType = response.getHeaderString("Content-Type");
+ if(clazz != null) {
+ String str = response.readEntity(String.class);
+ EcompPortalUtils.logAndSerializeObject(restPath, "POST result =", str);
+ try { t = gson.fromJson(str, clazz); } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput);
+ }
+ }
+ }
+ return t;
+ }
+
+ @Override
+ public <T> T put(Class<T> clazz, long appId, Object payload, String restPath) throws HTTPException {
+ WebClient client = null;
+ Response response = null;
+ T t = null;
+
+ client = createClientForApp(appId, restPath);
+ EcompPortalUtils.logAndSerializeObject(restPath, "PUT request =", payload);
+
+ try {
+ if (client!=null) {
+ response = client.put(payload);
+ } else {
+ logger.error(EELFLoggerDelegate.errorLogger, "Unable to create the Webclient to make the '" + restPath + "' API call.");
+ }
+ } catch(Exception e) {
+ MDC.put(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeRestApiGeneralError);
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while making the PUT REST API call, Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+
+ if (response!=null) {
+ verifyResponse(response);
+ String str = response.readEntity(String.class);
+ EcompPortalUtils.logAndSerializeObject(restPath, "PUT result =", str);
+ try { t = gson.fromJson(str, clazz); } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput);
+ }
+ }
+ return t;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheService.java
new file mode 100644
index 00000000..dc3ac56d
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheService.java
@@ -0,0 +1,40 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+
+package org.openecomp.portalapp.portal.service;
+
+import org.openecomp.portalapp.portal.domain.EPApp;
+
+public interface AppsCacheService {
+
+ /**
+ * returns an app by id from the cache
+ * @param appId
+ * @return corresponding App
+ */
+ EPApp getApp(Long appId);
+
+ /**
+ * returns the corresponding application endpoint
+ * @param appId
+ * @return if appId exists in cache, then return corresponding application endpoint, null otherwise.
+ */
+ String getAppEndpoint(Long appId);
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheServiceImple.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheServiceImple.java
new file mode 100644
index 00000000..7bbff768
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/AppsCacheServiceImple.java
@@ -0,0 +1,104 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.annotation.PostConstruct;
+
+import org.openecomp.portalapp.portal.domain.EPApp;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+
+@Service("appsCacheService")
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class AppsCacheServiceImple implements AppsCacheService {
+ @Autowired
+ EPAppService appsService;
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsCacheServiceImple.class);
+
+ private static long updateTime = 0;
+ private static final int cacheUpdateIntervalInSeconds = 10;
+
+ private static volatile Map<Long, EPApp> appsMap;
+
+ @PostConstruct
+ public void init() {
+ this.refreshAppsMap();
+ }
+
+ private Map<Long, EPApp> refreshAppsMap() {
+ long now = System.currentTimeMillis();
+
+ if(noNeedToUpdate(now))
+ return null;
+
+ synchronized (this) {
+ if(noNeedToUpdate(now))
+ return null;
+ List<EPApp> allApps = appsService.getAppsFullList();
+ Map<Long, EPApp> newAppsMap = new HashMap<Long, EPApp>();
+ for (EPApp app : allApps) {
+ newAppsMap.put(app.getId(), app);
+ }
+ // Switch cache with the new one.
+ appsMap = newAppsMap;
+ updateTime = now;
+ }
+
+ return appsMap;
+ }
+
+ private boolean noNeedToUpdate(long now) {
+ long secondsPassed = (now - updateTime)/1000;
+ if(secondsPassed < cacheUpdateIntervalInSeconds){
+ logger.debug(EELFLoggerDelegate.debugLogger, "no need to refresh yet, seconds since last refresh: " + secondsPassed + ", refresh interval (sec) = " + cacheUpdateIntervalInSeconds);
+ return true; // no need to update cache
+ }
+ return false; // its time to update
+ }
+
+ @Override
+ public String getAppEndpoint(Long appId) {
+ refreshAppsMap();
+ EPApp app = appsMap.get(appId);
+ if(app != null)
+ return app.getAppRestEndpoint();
+ return null;
+ }
+
+ @Override
+ public EPApp getApp(Long appId) {
+ refreshAppsMap();
+ EPApp app = appsMap.get(appId);
+ if(app != null)
+ return app;
+ return null;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/DashboardSearchService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/DashboardSearchService.java
new file mode 100644
index 00000000..3daeb852
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/DashboardSearchService.java
@@ -0,0 +1,38 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem;
+import org.openecomp.portalapp.portal.transport.CommonWidget;
+import org.openecomp.portalapp.portal.transport.CommonWidgetMeta;
+
+public interface DashboardSearchService {
+ public Map<String, List<SearchResultItem>> searchResults(String userId, String searchString);
+ public List<String> getRelatedUsers(String userId);
+ public List<Object[]> getRelatedUserVOs(String orgUserId);
+
+ public CommonWidgetMeta getWidgetData(String resourceType);
+ public String saveWidgetDataBulk(CommonWidgetMeta commonWidgetMetaData);
+ public String saveWidgetData(CommonWidget commonWidgetData);
+ public String deleteWidgetData(CommonWidget eventWidget);
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/DashboardSearchServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/DashboardSearchServiceImpl.java
new file mode 100644
index 00000000..bf0fc447
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/DashboardSearchServiceImpl.java
@@ -0,0 +1,238 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem;
+import org.openecomp.portalapp.portal.transport.CommonWidget;
+import org.openecomp.portalapp.portal.transport.CommonWidgetMeta;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.service.DataAccessService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Transactional;
+
+@Component
+@Transactional
+public class DashboardSearchServiceImpl implements DashboardSearchService{
+
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DashboardSearchServiceImpl.class);
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ @SuppressWarnings("unchecked")
+ public Map<String, List<SearchResultItem>> searchResults(String orgUserId, String searchString){
+
+ Map<String, String> params = new HashMap<>();
+ params.put("userId", orgUserId);
+ params.put("searchQuery", searchString);
+ // Named query is stored in a *.hbm.xml file, mapped to SearchResultItem
+ @SuppressWarnings("unchecked")
+ List<SearchResultItem> list = dataAccessService.executeNamedQuery("searchPortal", params, null);
+ Map<String, List<SearchResultItem>> finalJson = null;
+ if (list.size() > 0) {
+ finalJson = new HashMap<String, List<SearchResultItem>>();
+ for (SearchResultItem thisResult : list) {
+ List<SearchResultItem> thisList = finalJson.get(thisResult.getCategory().toLowerCase());
+ if (thisList == null)
+ thisList = new ArrayList<SearchResultItem>();
+ thisList.add(thisResult);
+ finalJson.put(thisResult.getCategory().toLowerCase(), thisList);
+ }
+ }
+ return finalJson;
+
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<String> getRelatedUsers(String orgUserId) {
+
+ Map<String, String> params = new HashMap<>();
+
+ params.put("org_user_id", orgUserId);
+
+ List<String> activeUsers = null;
+
+ try{
+ activeUsers = dataAccessService.executeNamedQuery("relatedUsers", params, null);
+ }
+ catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+
+ return activeUsers;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<Object[]> getRelatedUserVOs(String orgUserId) {
+
+ Map<String, String> params = new HashMap<>();
+
+ params.put("org_user_id", orgUserId);
+
+ List<Object[]> activeUsers = null;
+
+ try{
+ activeUsers = dataAccessService.executeNamedQuery("relatedUserVOs", params, null);
+ }
+ catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+
+ return activeUsers;
+ }
+
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public CommonWidgetMeta getWidgetData(String resourceType) {
+
+ List<CommonWidget> widgetItems = null;
+ try{
+ Map<String, String> params = new HashMap<>();
+ params.put("cat", resourceType);
+ widgetItems = (List<CommonWidget>)dataAccessService.executeNamedQuery("getCommonWidgetItem", params, null);
+
+ /*widgetItems2 = new ArrayList<CommonWidget2>();
+
+ for(int i = 0; i < widgetItems.size(); i++){
+ CommonWidget2 item = (CommonWidget2)widgetItems.get(i);
+ widgetItems2.add(new CommonWidget2(item.getCategory(), item.getHref(), item.getTitle(), item.getSortOrder()));
+ }*/
+ }
+ catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+ return new CommonWidgetMeta(resourceType, widgetItems);
+ }
+
+ @Override
+ public String saveWidgetDataBulk(CommonWidgetMeta commonMetaWidgetData) {
+
+ try{
+ for(CommonWidget widgetData : commonMetaWidgetData.getItems()){
+ widgetData.setCategory(commonMetaWidgetData.getCategory());
+ dataAccessService.saveDomainObject(widgetData, null);
+ }
+
+ return "success";
+ }
+ catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ return e.getMessage();
+ }
+ }
+
+ @Override
+ public String saveWidgetData(CommonWidget commonWidgetData) {
+
+ try{
+
+ dataAccessService.saveDomainObject(commonWidgetData, null);
+ return "success";
+ }
+ catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ return e.getMessage();
+ }
+ }
+
+ @Override
+ public String deleteWidgetData(CommonWidget eventWidget) {
+ try{
+ dataAccessService.deleteDomainObject(eventWidget, null);
+ return "success";
+ }
+ catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ return e.getMessage();
+ }
+ }
+
+/* @Override
+ public EventWidgetMeta getEventWidgetData() {
+ List<EventWidget> widgetItems = null;
+ try{
+ Map<String, String> params = new HashMap<>();
+ widgetItems = (List<EventWidget>)dataAccessService.executeNamedQuery("getEventWidgetData", params, null);
+
+ widgetItems2 = new ArrayList<CommonWidget2>();
+
+ for(int i = 0; i < widgetItems.size(); i++){
+ CommonWidget2 item = (CommonWidget2)widgetItems.get(i);
+ widgetItems2.add(new CommonWidget2(item.getCategory(), item.getHref(), item.getTitle(), item.getSortOrder()));
+ }
+ }
+ catch(Exception e){
+ e.printStackTrace();
+ }
+ return new EventWidgetMeta("EVENTS", widgetItems);
+ }
+
+ @Override
+ public String saveEventWidgetDataBulk(EventWidgetMeta eventsWidgetData) {
+ try{
+ for(EventWidget widgetData : eventsWidgetData.getItems()){
+ widgetData.setCategory(eventsWidgetData.getCategory());
+ dataAccessService.saveDomainObject(widgetData, null);
+ }
+
+ return "success";
+ }
+ catch(Exception e){
+ e.printStackTrace();
+ return e.getMessage();
+ }
+ }
+
+ @Override
+ public String saveEventWidgetData(EventWidget eventWidget) {
+ try{
+ dataAccessService.saveDomainObject(eventWidget, null);
+ return "success";
+ }
+ catch(Exception e){
+ e.printStackTrace();
+ return e.getMessage();
+ }
+ }
+
+ @Override
+ public String deleteEventWidgetData(EventWidget eventWidget) {
+ try{
+ dataAccessService.deleteDomainObject(eventWidget, null);
+ return "success";
+ }
+ catch(Exception e){
+ e.printStackTrace();
+ return e.getMessage();
+ }
+ }
+
+ */
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPAppService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPAppService.java
new file mode 100644
index 00000000..4614a2c8
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPAppService.java
@@ -0,0 +1,164 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.List;
+
+import org.openecomp.portalapp.portal.domain.AdminUserApplications;
+import org.openecomp.portalapp.portal.domain.AppIdAndNameTransportModel;
+import org.openecomp.portalapp.portal.domain.AppsResponse;
+import org.openecomp.portalapp.portal.domain.EPApp;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.domain.EcompApp;
+import org.openecomp.portalapp.portal.domain.UserRoles;
+import org.openecomp.portalapp.portal.transport.FieldsValidator;
+import org.openecomp.portalapp.portal.transport.LocalRole;
+import org.openecomp.portalapp.portal.transport.OnboardingApp;
+import org.openecomp.portalapp.portal.ecomp.model.AppCatalogItem;
+
+public interface EPAppService {
+
+ /**
+ * Get all applications adminId is an admin
+ *
+ * @param adminId
+ * - the admin
+ * @return the admin's applications
+ */
+ List<EPApp> getUserAsAdminApps(EPUser user);
+
+ List<EPApp> getUserByOrgUserIdAsAdminApps(String attuid);
+
+ /**
+ * Gets all rows and all fields from the fn_app table.
+ *
+ * @return list of EPApp objects
+ */
+ List<EPApp> getAppsFullList();
+
+ /**
+ * Gets all rows and most fields from the fn_app table.
+ *
+ * @return list of EcompApp objects.
+ */
+ List<EcompApp> getEcompAppAppsFullList();
+
+ /**
+ * Get apps with app app admins
+ *
+ * @return
+ */
+ List<AdminUserApplications> getAppsAdmins();
+
+ /**
+ * Get all apps from fn_app table (index, name, title only). If all is true,
+ * return active and inactive apps; otherwise, just active apps.
+ *
+ * @return List of AppsResponse objects.
+ */
+ List<AppsResponse> getAllApps(Boolean all);
+
+ UserRoles getUserProfile(String loginId);
+
+ List<LocalRole> getAppRoles(Long appId);
+
+ List<AppIdAndNameTransportModel> getAdminApps(EPUser user);
+
+ List<AppIdAndNameTransportModel> getAppsForSuperAdminAndAccountAdmin(EPUser user);
+
+ List<EPApp> getUserRemoteApps(String id);
+
+ /**
+ * Gets the applications accessible to the specified user, which includes
+ * all enabled open applications, plus all enabled applications for which
+ * the user has a defined role for that app.
+ *
+ * @param user
+ * EPUser object with the user's UID
+ * @return the user's list of applications, which may be empty.
+ */
+ List<EPApp> getUserApps(EPUser user);
+
+ /**
+ * Gets the user-personalized list of applications for the Portal (super)
+ * admin, which includes enabled open applications, enabled applications for
+ * which the user has a defined role for that app, and/or enabled
+ * applications which the user has chosen to show.
+ *
+ * @param user
+ * EPUser object with the user's UID
+ * @return the user's personalized list of applications, which may be empty.
+ */
+ List<EPApp> getPersAdminApps(EPUser user);
+
+ /**
+ * Gets the user-personalized list of accessible applications, which
+ * includes enabled open applications and/or enabled applications for which
+ * the user has a defined role for that app. Personalization means the user
+ * can indicate an accessible application should be excluded from this
+ * result.
+ *
+ * @param user
+ * EPUser object with the user's UID
+ * @return the user's personalized list of applications, which may be empty.
+ */
+ List<EPApp> getPersUserApps(EPUser user);
+
+ /**
+ * Gets the application catalog for the specified user who is a super admin.
+ * This includes all enabled applications. Each item indicates whether the
+ * user has access (open or via a role), and whether the application is
+ * selected for showing in the user's home (applications) page. Admin sees
+ * slightly different behavior - can force an app onto the home page using
+ * the personalization feature (user-app-selection table).
+ *
+ * @param user
+ * @return list of all enabled applications, which may be empty
+ */
+ List<AppCatalogItem> getAdminAppCatalog(EPUser user);
+
+ /**
+ * Gets the application catalog for the specified user, who is a regular
+ * user. This includes all enabled applications. Each item indicates whether
+ * the user has access (open or via a role), and whether the application is
+ * selected for showing in the user's home (applications) page.
+ *
+ * @param user
+ * @return list of all enabled applications, which may be empty
+ */
+ List<AppCatalogItem> getUserAppCatalog(EPUser user);
+
+ List<OnboardingApp> getOnboardingApps();
+
+ List<OnboardingApp> getEnabledNonOpenOnboardingApps();
+
+ FieldsValidator modifyOnboardingApp(OnboardingApp modifiedOnboardingApp, EPUser user);
+
+ FieldsValidator addOnboardingApp(OnboardingApp newOnboardingApp, EPUser user);
+
+ FieldsValidator deleteOnboardingApp(EPUser user, Long onboardingAppId);
+
+ List<EcompApp> transformAppsToEcompApps(List<EPApp> appsList);
+
+ EPApp getApp(Long appId);
+
+ void writeAppsImagesToDiskCacheIfNecessary();
+
+} \ No newline at end of file
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPAppServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPAppServiceImpl.java
new file mode 100644
index 00000000..fd84ec35
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPAppServiceImpl.java
@@ -0,0 +1,1218 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Base64;
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeSet;
+
+import javax.annotation.PostConstruct;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.lang.StringUtils;
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.Transaction;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiConstants;
+import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiProperties;
+import org.openecomp.portalsdk.core.onboarding.ueb.Helper;
+import org.openecomp.portalsdk.core.onboarding.ueb.TopicManager;
+import org.openecomp.portalsdk.core.service.DataAccessService;
+import org.openecomp.portalsdk.core.util.CipherUtil;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.openecomp.portalapp.portal.domain.AdminUserApp;
+import org.openecomp.portalapp.portal.domain.AdminUserApplications;
+import org.openecomp.portalapp.portal.domain.AppIdAndNameTransportModel;
+import org.openecomp.portalapp.portal.domain.AppsResponse;
+import org.openecomp.portalapp.portal.domain.EPApp;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.domain.EcompApp;
+import org.openecomp.portalapp.portal.domain.UserRole;
+import org.openecomp.portalapp.portal.domain.UserRoles;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
+import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
+import org.openecomp.portalapp.portal.transport.FieldsValidator;
+import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
+import org.openecomp.portalapp.portal.transport.LocalRole;
+import org.openecomp.portalapp.portal.transport.OnboardingApp;
+import org.openecomp.portalapp.portal.ueb.EPUebHelper;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.portal.ecomp.model.AppCatalogItem;
+import com.att.nsa.apiClient.http.HttpException;
+import com.att.nsa.cambria.client.CambriaClient.CambriaApiException;
+import com.att.nsa.cambria.client.CambriaClientBuilders;
+import com.att.nsa.cambria.client.CambriaIdentityManager;
+
+@Service("epAppService")
+@Transactional
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class EPAppServiceImpl implements EPAppService {
+
+ private String ECOMP_APP_ID = "1";
+ private String SUPER_ADMIN_ROLE_ID = "1";
+ private String ACCOUNT_ADMIN_ROLE_ID = "999";
+ private String RESTRICTED_APP_ROLE_ID = "900";
+
+ private static final String PATH_SEPARATOR = "/";
+ private static final String webappsBaseFullPath = System.getProperty("catalina.base") + PATH_SEPARATOR
+ + "wtpwebapps";
+ private static final String imageCacheRelativePath = "images" + PATH_SEPARATOR + "cache";
+ private String ecompportalPath = null;
+ private static final Long DUBLICATED_FIELD_VALUE_ECOMP_ERROR = new Long(
+ EPSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
+
+ private static final String urlField = "url";
+
+ private static final String nameField = "name";
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPAppServiceImpl.class);
+
+ @Autowired
+ AdminRolesService adminRolesService;
+ @Autowired
+ private SessionFactory sessionFactory;
+ @Autowired
+ private DataAccessService dataAccessService;
+ @Autowired
+ EPUebHelper epUebHelper;
+
+ private String constructImagesCachePath() {
+ String filePath = System.getProperty("catalina.base");
+ File eclipseWebAppDir = new File(webappsBaseFullPath);
+
+ if (eclipseWebAppDir.exists()) {
+ // Eclipse webapps
+ filePath += PATH_SEPARATOR + "wtpwebapps";
+ } else {
+ filePath += PATH_SEPARATOR + "webapps";
+ }
+ filePath += PATH_SEPARATOR + SystemProperties.getProperty(EPSystemProperties.ECOMP_CONTEXT_ROOT);;
+
+ return filePath.toString();
+ // return SystemProperties.getProperty(SystemProperties.TEMP_PATH);
+ }
+
+ @PostConstruct
+ private void init() {
+ ecompportalPath = constructImagesCachePath();
+ writeAppsImagesToDiskCacheIfNecessary();
+
+ SUPER_ADMIN_ROLE_ID = SystemProperties.getProperty(EPSystemProperties.SYS_ADMIN_ROLE_ID);
+ ACCOUNT_ADMIN_ROLE_ID = SystemProperties.getProperty(EPSystemProperties.ACCOUNT_ADMIN_ROLE_ID);
+ ECOMP_APP_ID = SystemProperties.getProperty(EPSystemProperties.ECOMP_APP_ID);
+ RESTRICTED_APP_ROLE_ID = SystemProperties.getProperty(EPSystemProperties.RESTRICTED_APP_ROLE_ID);
+ }
+
+ @Override
+ public List<EPApp> getUserAsAdminApps(EPUser user) {
+ if (adminRolesService.isAccountAdmin(user)) {
+ String sql = "SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID=FN_APP.APP_ID where "
+ + "FN_USER_ROLE.USER_ID=" + user.getId() + " AND FN_USER_ROLE.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
+ + " AND FN_APP.ENABLED = 'Y'";
+ logQuery(sql);
+ try {
+ @SuppressWarnings("unchecked")
+ List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
+ return adminApps;
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ return null;
+ }
+ } else {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "getUserAsAdminApps: only Account Admin may invoke this function!");
+ return new ArrayList<EPApp>();
+ }
+ }
+
+ @Override
+ public List<EPApp> getUserByOrgUserIdAsAdminApps(String orgUserId) {
+ String format = "SELECT * FROM FN_APP app INNER JOIN FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID "
+ + "INNER JOIN FN_USER user on user.USER_ID = userrole.USER_ID "
+ + "WHERE user.ORG_USER_ID = '%s' AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID + " AND FN_APP.ENABLED = 'Y'";
+
+ String sql = String.format(format, orgUserId);
+ logQuery(sql);
+
+ try {
+ @SuppressWarnings("unchecked")
+ List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
+ return adminApps;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ return null;
+ }
+ }
+
+ @Override
+ public List<EPApp> getAppsFullList() {
+ @SuppressWarnings("unchecked")
+ List<EPApp> apps = dataAccessService.getList(EPApp.class, null);
+ // Write the image to disk in case if it is missing
+ for (EPApp app : apps)
+ writeAppImageToDiskCacheIfNecessary(app);
+ return apps;
+ }
+
+ @Override
+ public List<EcompApp> getEcompAppAppsFullList() {
+ return transformAppsToEcompApps(getAppsFullList());
+ }
+
+ @Override
+ public List<EcompApp> transformAppsToEcompApps(List<EPApp> appsList) {
+ List<EcompApp> ecompAppList = new ArrayList<EcompApp>();
+ for (EPApp app : appsList) {
+ EcompApp ecompApp = new EcompApp();
+ ecompApp.setId(app.getId());
+ ecompApp.setName(app.getName());
+ ecompApp.setImageUrl(app.getImageUrl());
+ ecompApp.setDescription(app.getDescription());
+ ecompApp.setNotes(app.getNotes());
+ ecompApp.setUrl(app.getUrl());
+ ecompApp.setAlternateUrl(app.getAlternateUrl());
+ ecompApp.setUebTopicName(app.getUebTopicName());
+ ecompApp.setUebKey(app.getUebKey());
+ ecompApp.setUebSecret(app.getUebSecret());
+ ecompApp.setEnabled(app.getEnabled());
+ ecompApp.setRestrictedApp(app.isRestrictedApp());
+ ecompAppList.add(ecompApp);
+ }
+ return ecompAppList;
+ }
+
+ @Override
+ public EPApp getApp(Long appId) {
+ try {
+ @SuppressWarnings("unchecked")
+ List<EPApp> apps = dataAccessService.getList(EPApp.class, " where id = " + appId, null, null);
+ return (apps.size() > 0) ? apps.get(0) : null;
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ return null;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<AppIdAndNameTransportModel> getAdminApps(EPUser user) {
+ if (adminRolesService.isAccountAdmin(user)) {
+ String format = "SELECT app.APP_ID, app.APP_NAME, app.APP_TYPE FROM FN_APP app inner join FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID "
+ + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
+ + " AND app.ENABLED = 'Y'";
+ String sql = String.format(format, user.getId());
+ // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
+ // app.APP_REST_ENDPOINT <> ''";
+ logQuery(sql);
+ try {
+ return (ArrayList<AppIdAndNameTransportModel>) dataAccessService.executeSQLQuery(sql,
+ AppIdAndNameTransportModel.class, null);
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while fetching the adminApps for user "
+ + user.getLoginId() + ". Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+ }
+ return new ArrayList<AppIdAndNameTransportModel>();
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<AppIdAndNameTransportModel> getAppsForSuperAdminAndAccountAdmin(EPUser user) {
+ if (adminRolesService.isSuperAdmin(user) || adminRolesService.isAccountAdmin(user)) {
+ String format = "";
+ String sql = "";
+ if (adminRolesService.isSuperAdmin(user)) {
+ format = "SELECT app.APP_ID, app.APP_NAME, app.APP_TYPE FROM FN_APP app " + "where app.ENABLED = 'Y'";
+ } else {
+ format = "SELECT app.APP_ID, app.APP_NAME, APP_TYPE FROM FN_APP app inner join FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID "
+ + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID
+ + " AND app.ENABLED = 'Y'";
+ }
+ sql = String.format(format, user.getId());
+ // sql += " AND app.APP_REST_ENDPOINT IS NOT NULL AND
+ // app.APP_REST_ENDPOINT <> ''";
+ logQuery(sql);
+ try {
+ return (ArrayList<AppIdAndNameTransportModel>) dataAccessService.executeSQLQuery(sql,
+ AppIdAndNameTransportModel.class, null);
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while fetching the adminApps for user "
+ + user.getLoginId() + ". Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+ }
+ return new ArrayList<AppIdAndNameTransportModel>();
+ }
+
+ private void logQuery(String sql) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ }
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+ @Override
+ public List<AdminUserApplications> getAppsAdmins() {
+ String sql = "SELECT apps.APP_NAME, apps.APP_ID, user.USER_ID, user.FIRST_NAME, user.LAST_NAME, user.ORG_USER_ID FROM fn_user_role userrole "
+ + "INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID "
+ + "INNER JOIN fn_app apps ON apps.APP_ID = userrole.APP_ID " + "WHERE userrole.ROLE_ID = "
+ + ACCOUNT_ADMIN_ROLE_ID + " AND apps.ENABLED = 'Y'";
+ logQuery(sql);
+ try {
+ @SuppressWarnings("unchecked")
+ List<AdminUserApp> adminApps = dataAccessService.executeSQLQuery(sql, AdminUserApp.class, null); // DataAccessService
+ // does
+ // not
+ // use
+ // generic
+ // types.
+ return aggregateRowsResultsByUserId(adminApps);
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ return null;
+ }
+ }
+
+ private List<AdminUserApplications> aggregateRowsResultsByUserId(List<AdminUserApp> adminApps) {
+ HashMap<Long, AdminUserApplications> adminUserApplications = new HashMap<Long, AdminUserApplications>();
+ for (AdminUserApp app : adminApps) {
+ Long userId = app.getUser_Id();
+ if (adminUserApplications.get(userId) == null)
+ adminUserApplications.put(userId, new AdminUserApplications(app));
+ else
+ adminUserApplications.get(userId).addApp(app.getAppId(), app.getAppName());
+ }
+ return new ArrayList<AdminUserApplications>(adminUserApplications.values());
+ }
+
+ @Override
+ public List<AppsResponse> getAllApps(Boolean all) {
+ // If all is true, return both active and inactive apps. Otherwise, just
+ // active apps.
+ @SuppressWarnings("unchecked")
+ // Sort the list by application name so the drop-down looks pretty.
+ List<EPApp> apps = all
+ ? (List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null)
+ : (List<EPApp>) dataAccessService.getList(EPApp.class, " where enabled = 'Y'", "name", null);
+ List<AppsResponse> appsModified = new ArrayList<AppsResponse>();
+ for (EPApp app : apps) {
+ appsModified.add(new AppsResponse(app.getId(), app.getName(), app.isRestrictedApp(), app.getEnabled()));
+
+ // Write the image to disk in case if it is missing
+ writeAppImageToDiskCacheIfNecessary(app);
+ }
+ return appsModified;
+ }
+
+ @Override
+ public UserRoles getUserProfile(String loginId) {
+ String format = "SELECT DISTINCT user.USER_ID, role.ROLE_ID, user.ORG_USER_ID, user.FIRST_NAME, user.LAST_NAME, role.ROLE_NAME FROM fn_user_role userrole "
+ + "INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID "
+ + "INNER JOIN fn_role role ON role.ROLE_ID = userrole.ROLE_ID " + "WHERE user.ORG_USER_ID = \"%s\";";
+ String sql = String.format(format, loginId);
+ logQuery(sql);
+ @SuppressWarnings("unchecked")
+ List<UserRole> userRoleList = dataAccessService.executeSQLQuery(sql, UserRole.class, null);
+ ArrayList<UserRoles> usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList);
+ if (usersRolesList == null || usersRolesList.size() < 1)
+ return null;
+
+ return usersRolesList.get(0);
+ }
+
+ private ArrayList<UserRoles> aggregateUserProfileRowsResultsByRole(List<UserRole> userRoleList) {
+ HashMap<String, UserRoles> userRoles = new HashMap<String, UserRoles>();
+ for (UserRole user : userRoleList) {
+ String orgUserId = user.getOrgUserId();
+ if (userRoles.get(orgUserId) == null)
+ userRoles.put(orgUserId, new UserRoles(user));
+ else
+ userRoles.get(orgUserId).addRole(user.getRoleId());
+ }
+ return new ArrayList<UserRoles>(userRoles.values());
+ }
+
+ private boolean isRestrictedApp(Long appId) {
+ EPApp app = getApp(appId);
+ return app.isRestrictedApp();
+ }
+
+ // For the functional menu edit
+ @Override
+ public List<LocalRole> getAppRoles(Long appId) {
+ String sql = "";
+ if (isRestrictedApp(appId)) {
+ sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where ROLE_ID = '" + RESTRICTED_APP_ROLE_ID + "'";
+ } else {
+ sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where APP_ID = '" + appId + "'";
+ }
+ logQuery(sql);
+ @SuppressWarnings("unchecked")
+ List<LocalRole> appRoles = dataAccessService.executeSQLQuery(sql, LocalRole.class, null);
+ return appRoles;
+ }
+
+ private String userAppsQuery(EPUser user) {
+ StringBuilder query = new StringBuilder();
+ if (adminRolesService.isSuperAdmin(user)) {
+ query.append("SELECT * FROM FN_APP where FN_APP.ENABLED = 'Y'");
+ } else {
+ query.append("SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = FN_APP.APP_ID where ");
+ query.append(
+ "FN_USER_ROLE.USER_ID = " + user.getId() + " AND FN_USER_ROLE.ROLE_ID != " + SUPER_ADMIN_ROLE_ID);
+ query.append(" AND FN_APP.ENABLED = 'Y'");
+ }
+ return query.toString();
+ }
+
+ @Override
+ public List<EPApp> getUserApps(EPUser user) {
+ List<EPApp> openApps = getOpenApps();
+ for (EPApp app : openApps) {
+ // Write the image to disk in case if it is missing
+ writeAppImageToDiskCacheIfNecessary(app);
+ }
+
+ if (user.isGuest()) {
+ return openApps;
+ } else {
+ String sql = userAppsQuery(user);
+ logQuery(sql);
+
+ TreeSet<EPApp> distinctApps = new TreeSet<EPApp>();
+
+ @SuppressWarnings("unchecked")
+ List<EPApp> adminApps = dataAccessService.executeSQLQuery(sql, EPApp.class, null);
+ for (EPApp app : adminApps) {
+ // Write the image to disk in case if it is missing
+ writeAppImageToDiskCacheIfNecessary(app);
+
+ distinctApps.add(app);
+ }
+
+ for (EPApp app : openApps) {
+ distinctApps.add(app);
+ }
+
+ List<EPApp> userApps = new ArrayList<EPApp>();
+ userApps.addAll(distinctApps);
+ return userApps;
+ }
+ }
+
+ @Override
+ public List<EPApp> getPersAdminApps(EPUser user) {
+ final Map<String, Long> params = new HashMap<>();
+ params.put("userId", user.getId());
+ // Named query is stored in EP.hbm.xml, mapped to EPApp
+ @SuppressWarnings("unchecked")
+ List<EPApp> list = dataAccessService.executeNamedQuery("getPersAdminApps", params, null);
+ // Why is this necessary?
+ for (EPApp app : list)
+ writeAppImageToDiskCacheIfNecessary(app);
+ return list;
+ }
+
+ @Override
+ public List<EPApp> getPersUserApps(EPUser user) {
+ final Map<String, Long> params = new HashMap<>();
+ params.put("userId", user.getId());
+ // Named query is stored in EP.hbm.xml, mapped to EPApp
+ @SuppressWarnings("unchecked")
+ List<EPApp> list = dataAccessService.executeNamedQuery("getPersUserApps", params, null);
+ // Why is this necessary?
+ for (EPApp app : list)
+ writeAppImageToDiskCacheIfNecessary(app);
+ return list;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.openecomp.portalapp.portal.service.EPAppService#getAppCatalog(org.openecomp.portalapp.portal.domain.EPUser)
+ */
+ @Override
+ public List<AppCatalogItem> getUserAppCatalog(EPUser user) {
+ final Map<String, Long> params = new HashMap<>();
+ params.put("userId", user.getId());
+ // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
+ @SuppressWarnings("unchecked")
+ List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getUserAppCatalog", params, null);
+ return list;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.openecomp.portalapp.portal.service.EPAppService#getAdminAppCatalog(org.openecomp.portalapp.portal.domain.EPUser)
+ */
+ @Override
+ public List<AppCatalogItem> getAdminAppCatalog(EPUser user) {
+ final Map<String, Long> params = new HashMap<>();
+ params.put("userId", user.getId());
+ // Named query is stored in EP.hbm.xml, mapped to AppCatalogItem
+ @SuppressWarnings("unchecked")
+ List<AppCatalogItem> list = dataAccessService.executeNamedQuery("getAdminAppCatalog", params, null);
+ return list;
+ }
+
+ private List<EPApp> getOpenApps() {
+ @SuppressWarnings("unchecked")
+ List<EPApp> openApps = dataAccessService.getList(EPApp.class, " where open='Y' and enabled='Y'", null, null);
+ return openApps;
+ }
+
+ @Override
+ public List<OnboardingApp> getOnboardingApps() {
+ @SuppressWarnings("unchecked")
+ List<EPApp> apps = (List<EPApp>) dataAccessService.getList(EPApp.class, " where id!=" + ECOMP_APP_ID, null,
+ null);
+ List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
+ for (EPApp app : apps) {
+ OnboardingApp onboardingApp = new OnboardingApp();
+ createOnboardingFromApp(app, onboardingApp);
+ onboardingAppsList.add(onboardingApp);
+ }
+ return onboardingAppsList;
+ }
+
+ @Override
+ public List<OnboardingApp> getEnabledNonOpenOnboardingApps() {
+ @SuppressWarnings("unchecked")
+ List<EPApp> apps = (List<EPApp>) dataAccessService.getList(EPApp.class,
+ " where enabled = true and open = false and id!=" + ECOMP_APP_ID, null, null);
+ List<OnboardingApp> onboardingAppsList = new ArrayList<OnboardingApp>();
+ for (EPApp app : apps) {
+ OnboardingApp onboardingApp = new OnboardingApp();
+ createOnboardingFromApp(app, onboardingApp);
+ onboardingAppsList.add(onboardingApp);
+ }
+ return onboardingAppsList;
+ }
+
+ private FieldsValidator onboardingAppFieldsChecker(OnboardingApp onboardingApp) {
+ FieldsValidator fieldsValidator = new FieldsValidator();
+ if (onboardingApp.name == null || onboardingApp.name.length() == 0 || onboardingApp.url == null
+ || onboardingApp.url.length() == 0 || onboardingApp.restrictedApp == null
+ || onboardingApp.isOpen == null || onboardingApp.isEnabled == null
+ || (onboardingApp.id != null && onboardingApp.id.equals(ECOMP_APP_ID))
+ // For a normal app (appType==1), these fields must be filled
+ // in.
+ // For a restricted app (appType==2), they will be empty.
+ || ((!onboardingApp.restrictedApp) && (onboardingApp.username == null
+ || onboardingApp.username.length() == 0 || onboardingApp.appPassword == null
+ || onboardingApp.appPassword.length() == 0))) {
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
+ }
+ return fieldsValidator;
+ }
+
+ @SuppressWarnings("unchecked")
+ private void validateOnboardingApp(OnboardingApp onboardingApp, FieldsValidator fieldsValidator) {
+ boolean dublicatedUrl = false;
+ boolean dublicatedName = false;
+ List<EPApp> apps;
+ if (onboardingApp.id == null) {
+ apps = dataAccessService.getList(EPApp.class,
+ " where url = '" + onboardingApp.url + "' or name = '" + onboardingApp.name + "'", null, null);
+ } else {
+ apps = dataAccessService.getList(EPApp.class, " where id = " + onboardingApp.id + " or url = '"
+ + onboardingApp.url + "' or name = '" + onboardingApp.name + "'", null, null);
+ }
+ for (EPApp app : apps) {
+ if (onboardingApp.id != null && onboardingApp.id.equals(app.getId())) {
+ continue;
+ }
+ if (!dublicatedUrl && app.getUrl().equalsIgnoreCase(onboardingApp.url)) {
+ dublicatedUrl = true;
+ if (dublicatedName) {
+ break;
+ }
+ }
+ if (!dublicatedName && app.getName().equalsIgnoreCase(onboardingApp.name)) {
+ dublicatedName = true;
+ if (dublicatedUrl) {
+ break;
+ }
+ }
+ }
+ if (dublicatedUrl || dublicatedName) {
+ if (dublicatedUrl) {
+ fieldsValidator.addProblematicFieldName(urlField);
+ }
+ if (dublicatedName) {
+ fieldsValidator.addProblematicFieldName(nameField);
+ }
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
+ fieldsValidator.errorCode = DUBLICATED_FIELD_VALUE_ECOMP_ERROR;
+ }
+ }
+
+ @Override
+ public FieldsValidator modifyOnboardingApp(OnboardingApp modifiedOnboardingApp, EPUser user) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering modifyOnboardingApp");
+ FieldsValidator fieldsValidator = onboardingAppFieldsChecker(modifiedOnboardingApp);
+ if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
+ validateOnboardingApp(modifiedOnboardingApp, fieldsValidator);
+ }
+ if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
+ if (modifiedOnboardingApp.id != null) {
+ updateApp(modifiedOnboardingApp.id, modifiedOnboardingApp, fieldsValidator, user);
+ } else {
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
+ }
+ }
+ return fieldsValidator;
+ }
+
+ @Override
+ public FieldsValidator addOnboardingApp(OnboardingApp newOnboardingApp, EPUser user) {
+ FieldsValidator fieldsValidator = onboardingAppFieldsChecker(newOnboardingApp);
+ if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
+ validateOnboardingApp(newOnboardingApp, fieldsValidator);
+ }
+ if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
+ if (newOnboardingApp.id == null) {
+ updateApp(null, newOnboardingApp, fieldsValidator, user);
+ } else {
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
+ }
+ }
+ return fieldsValidator;
+ }
+
+ @Override
+ public FieldsValidator deleteOnboardingApp(EPUser user, Long appid) {
+ FieldsValidator fieldsValidator = new FieldsValidator();
+ if (!adminRolesService.isSuperAdmin(user)) {
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
+ return fieldsValidator;
+ }
+ Boolean result = false;
+ Session localSession = null;
+ Transaction transaction = null;
+ try {
+ localSession = sessionFactory.openSession();
+ transaction = localSession.beginTransaction();
+
+ // 1) Remove the URL for any functional menu item associated with
+ // this app
+ String sql = "UPDATE fn_menu_functional m, fn_menu_functional_roles mr SET m.url='' "
+ + " WHERE m.menu_id=mr.menu_id " + " AND mr.app_id='" + appid + "'";
+ logQuery(sql);
+ Query query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+
+ // 2) Remove any favorites associated with a menu item that is
+ // associated with this app
+ sql = "Delete from fn_menu_favorites " + " using fn_menu_favorites inner join fn_menu_functional_roles "
+ + " where fn_menu_functional_roles.app_id='" + appid + "' "
+ + " AND fn_menu_functional_roles.menu_id=fn_menu_favorites.menu_id";
+ logQuery(sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+
+ // 3) Remove all role,appid records from fn_menu_functional_role
+ // that are associated with this app
+ sql = "delete from fn_menu_functional_roles where app_id='" + appid + "'";
+ logQuery(sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+
+ // 4) Remove all records from fn_user_role associated with this app
+ sql = "delete from fn_user_role where app_id='" + appid + "'";
+ logQuery(sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+
+ // 5) Remove all records from fn_role associated with this app
+ sql = "delete from fn_role where app_id='" + appid + "'";
+ logQuery(sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+
+ // 6) Remove any widgets associated with this app
+ sql = "delete from fn_widget where app_id='" + appid + "'";
+ logQuery(sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+
+ // Remove any selections in the personalization table
+ sql = "delete from fn_pers_user_app_sel where app_id='" + appid + "'";
+ logQuery(sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+
+ // Delete the app
+ sql = "delete from fn_app where app_id='" + appid + "'";
+ logQuery(sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+
+ transaction.commit();
+ result = true;
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingApp rollback, exception = " + e);
+ } finally {
+ EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingApp");
+ }
+ if (!result) {
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+ return fieldsValidator;
+ }
+
+ private static Object syncRests = new Object();
+
+ // An app has been enabled/disabled. Must enable/disable all associated
+ // functional menu items.
+ private void setFunctionalMenuItemsEnabled(Session localSession, Boolean enabled, Long appId) {
+ String active_yn = enabled ? "Y" : "N";
+ String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
+ + "FROM fn_menu_functional m, fn_menu_functional_roles r " + "WHERE m.menu_id = r.menu_id "
+ + " AND r.app_id = '" + appId + "' ";
+ logQuery(sql);
+ @SuppressWarnings("unchecked")
+ List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
+ for (FunctionalMenuItem menuItem : menuItems) {
+ FunctionalMenuItem myMenuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class,
+ menuItem.menuId);
+ myMenuItem.active_yn = active_yn;
+ localSession.save(myMenuItem);
+ }
+ }
+
+ // Attention! If (appId == null) we use this function to create application
+ // otherwise we use it to modify existing application
+ private void updateApp(Long appId, OnboardingApp onboardingApp, FieldsValidator fieldsValidator, EPUser user) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering updateApp");
+ // Separate out the code for a restricted app, since it doesn't need any
+ // of the UEB code.
+ if (onboardingApp.restrictedApp) {
+ boolean result = false;
+ Session localSession = null;
+ Transaction transaction = null;
+ try {
+ localSession = sessionFactory.openSession();
+ transaction = localSession.beginTransaction();
+ EPApp app;
+ if (appId == null) {
+ app = new EPApp();
+ } 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;
+ }
+ }
+ createAppFromOnboarding(app, onboardingApp, localSession);
+ localSession.saveOrUpdate(app);
+ // Enable or disable all menu items associated with this app
+ setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId);
+ transaction.commit();
+ result = true;
+ } catch (Exception e) {
+ EcompPortalUtils.rollbackTransaction(transaction,
+ "updateApp rollback, exception = " + EcompPortalUtils.getStackTrace(e));
+ } finally {
+ EcompPortalUtils.closeLocalSession(localSession, "updateApp");
+ }
+ if (!result) {
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+
+ } else {
+ 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();
+ // -------------------------------------------------------------------------------------------
+ // Register this App with the UEB communication server.
+ // Save
+ // the App's unique mailbox/topic
+ // name and keys to the FN_APP table. The App's mailbox
+ // and
+ // keys will be visible to the
+ // admin on the ECOMP portal.
+ // -------------------------------------------------------------------------------------------
+ TopicManager topicManager = new TopicManager();
+ final CambriaIdentityManager im = new CambriaClientBuilders.IdentityManagerBuilder()
+ .usingHosts(Helper.uebUrlList()).build();
+ com.att.nsa.apiClient.credentials.ApiCredential credential = im.createApiKey(user.getEmail(),
+ "ECOMP Portal Owner");
+ String appKey = credential.getApiKey();
+ String appSecret = credential.getApiSecret();
+ boolean isProductionBuild = EcompPortalUtils.isProductionBuild();
+ String appMailboxName = null;
+
+ int maxNumAttemptsToCreateATopic = 3;
+ boolean successfullyCreatedMailbox = false;
+ for (int i = 0; i < maxNumAttemptsToCreateATopic; i++) {
+ if (isProductionBuild) {
+ appMailboxName = "ECOMP-PORTAL-OUTBOX-" + (int) (Math.random() * 100000.0);
+ } else {
+ appMailboxName = "ECOMP-PORTAL-OUTBOX-TEST-" + (int) (Math.random() * 100000.0);
+ }
+
+ try {
+ topicManager.createTopic(
+ PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
+ PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
+ appMailboxName, "ECOMP outbox for app" + onboardingApp.name);
+ successfullyCreatedMailbox = true;
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "Successfully created " + appMailboxName + " for App " + onboardingApp.name);
+ logger.debug(EELFLoggerDelegate.debugLogger, " Key = " + appKey + " Secret = "
+ + appSecret + " generated using = " + user.getEmail());
+ break;
+ } catch (HttpException e) {
+ String stackTrace = EcompPortalUtils.getStackTrace(e);
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeUebConnectionError, e.getMessage());
+ if (e.getStatusCode() == 409) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Topic/mailbox " + appMailboxName
+ + " already exists. Will try using a different name, Details: "
+ + stackTrace);
+ } else {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "HttpException when onboarding App: " + stackTrace);
+ }
+ }
+ }
+
+ if (successfullyCreatedMailbox) {
+ onboardingApp.setUebTopicName(appMailboxName);
+ onboardingApp.setUebKey(appKey);
+ onboardingApp.setUebSecret(appSecret);
+
+ try {
+ /*
+ * EP is a publisher to this App's new mailbox
+ */
+ topicManager.addPublisher(
+ PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
+ PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
+ PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
+ appMailboxName);
+
+ /*
+ * This App is a subcriber of it's own mailbox
+ */
+ topicManager.addSubscriber(
+ PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
+ PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
+ appMailboxName);
+
+ /*
+ * This App is a publisher to EP
+ */
+ topicManager.addPublisher(
+ PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
+ PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET), appKey,
+ PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME));
+ } catch (HttpException | CambriaApiException | IOException e) {
+ String stackTrace = EcompPortalUtils.getStackTrace(e);
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeUebRegisterOnboardingAppError,
+ e.getMessage());
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Error when configuring Publisher/Subscriber for App's new mailbox "
+ + stackTrace);
+ transaction.commit();
+ localSession.close();
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
+ return;
+ }
+ } else {
+ transaction.commit();
+ localSession.close();
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
+ return;
+ }
+ } 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, "LR: about to call createAppFromOnboarding");
+ createAppFromOnboarding(app, onboardingApp, localSession);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "LR: updateApp: finished calling createAppFromOnboarding");
+ localSession.saveOrUpdate(app);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "LR: updateApp: finished calling localSession.saveOrUpdate");
+ // Enable or disable all menu items associated with this app
+ setFunctionalMenuItemsEnabled(localSession, onboardingApp.isEnabled, appId);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "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;
+ } catch (Exception e) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "exception: " + e.toString());
+ logger.debug(EELFLoggerDelegate.debugLogger, "exception.cause: " + e.getCause());
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeUebRegisterOnboardingAppError, e.getMessage());
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ EcompPortalUtils.rollbackTransaction(transaction,
+ "updateApp rollback, exception = " + EcompPortalUtils.getStackTrace(e));
+ } finally {
+ EcompPortalUtils.closeLocalSession(localSession, "updateApp");
+ }
+ if (!result) {
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+ }
+ }
+ }
+
+ private void createOnboardingFromApp(EPApp app, OnboardingApp onboardingApp) {
+ onboardingApp.id = app.getId();
+ onboardingApp.name = app.getName();
+ onboardingApp.imageUrl = app.getImageUrl();
+ onboardingApp.description = app.getDescription();
+ onboardingApp.notes = app.getNotes();
+ onboardingApp.url = app.getUrl();
+ onboardingApp.alternateUrl = app.getAlternateUrl();
+ onboardingApp.restUrl = app.getAppRestEndpoint();
+ onboardingApp.isOpen = app.getOpen();
+ onboardingApp.isEnabled = app.getEnabled();
+ onboardingApp.username = app.getUsername();
+ onboardingApp.appPassword = this.decryptedPassword(app.getAppPassword(), app);
+ onboardingApp.uebTopicName = app.getUebTopicName();
+ onboardingApp.uebKey = app.getUebKey();
+ onboardingApp.uebSecret = app.getUebSecret();
+ onboardingApp.setRestrictedApp(app.isRestrictedApp());
+
+ if (app.getThumbnail() != null) {
+ onboardingApp.thumbnail = new String(Base64.getEncoder().encode(app.getThumbnail()));
+ // Write the image to disk in case if it is missing
+ writeAppImageToDiskCacheIfNecessary(app);
+ }
+ }
+
+ private EPApp createAppFromOnboarding(EPApp app, OnboardingApp onboardingApp, Session localSession) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: entering createAppFromOnboarding");
+ app.setName(onboardingApp.name);
+ app.setDescription(onboardingApp.description);
+ app.setNotes(onboardingApp.notes);
+ app.setUrl(onboardingApp.url);
+ app.setAlternateUrl(onboardingApp.alternateUrl);
+ app.setAppRestEndpoint(onboardingApp.restUrl);
+ app.setOpen(onboardingApp.isOpen);
+ app.setEnabled(onboardingApp.isEnabled);
+ app.setUsername(onboardingApp.username);
+ app.setAppPassword(this.encryptedPassword(onboardingApp.appPassword, app));
+ app.setUebTopicName(onboardingApp.uebTopicName);
+ app.setUebKey(onboardingApp.uebKey);
+ app.setUebSecret(onboardingApp.uebSecret);
+ app.setRestrictedApp(onboardingApp.restrictedApp);
+ if (!StringUtils.isEmpty(onboardingApp.thumbnail)) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: onboarding thumbnail is NOT empty");
+ String[] splitBase64Thumbnail = onboardingApp.thumbnail.split("base64,");
+ if (splitBase64Thumbnail != null) {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "LR: length of splitBase64Thumbnail: " + splitBase64Thumbnail.length);
+ }
+ if (splitBase64Thumbnail.length > 1) {
+ // This occurs when we have a new image, not an existing image
+ byte[] decodedImage = Base64.getDecoder().decode(splitBase64Thumbnail[1].getBytes());
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: finished calling decode");
+ deleteOldImageFromDisk(app);
+ saveNewImageToDisk(app, onboardingApp, decodedImage);
+ app.setThumbnail(decodedImage);
+ }
+ } else if (app.getThumbnail() != null) {
+ // The thumbnail that came in from the json is empty; the previous
+ // thumbnail is NOT empty. Must delete it.
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: onboarding thumbnail is empty; db thumbnail is NOT null");
+ deleteOldImageFromDisk(app);
+ app.setThumbnail(null);
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: onboarding thumbnail is empty; db thumbnail is null");
+ }
+ return app;
+ }
+
+ private void deleteOldImageFromDisk(EPApp app) {
+ if (app.getImageUrl() != null) {
+ String oldImageFullFilePath = ecompportalPath + PATH_SEPARATOR + app.getImageUrl();
+ try {
+ File oldFile = new File(oldImageFullFilePath);
+ if (oldFile.exists() && oldFile.delete()) {
+ app.setImageUrl(null);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "old file " + oldImageFullFilePath + " was successfully deleted");
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "old file " + oldImageFullFilePath + " delete failure",
+ EcompPortalUtils.getStackTrace(e));
+ }
+ }
+ }
+
+ // No need to optimize this code since it happens only when adding/modifying
+ // an application.
+ private void saveNewImageToDisk(EPApp app, OnboardingApp onboardingApp, byte[] decodedImage) {
+ // Notice!!!
+ // using separator did not worked on WINDOWS as the database was saved
+ // as assets\images\tmp\ which the UI did not understand thus ichanged
+ // it to "/"
+ String imageFileName = constructImageName(onboardingApp);
+ String imageRelativeFilePath = imageCacheRelativePath + PATH_SEPARATOR + imageFileName;
+ String imageFullFilePath = ecompportalPath + PATH_SEPARATOR + imageRelativeFilePath;
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "saving app " + onboardingApp.name + " image to " + imageFullFilePath);
+
+ FileOutputStream osf = null;
+ try {
+ // Base64 Image example: 'data:image/png;base64,AAAFBfj42Pj4'
+ logger.info(EELFLoggerDelegate.debugLogger, "Saving new image: " + decodedImage);
+ osf = writeImageAsBase64(decodedImage, imageFullFilePath);
+ app.setImageUrl(imageRelativeFilePath);
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "saveBlobImageToDisk onboardingAppImageUrl = " + imageRelativeFilePath);
+ } catch (IOException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "failed to save image to " + imageFullFilePath,
+ EcompPortalUtils.getStackTrace(e));
+ } finally {
+ if (osf != null) {
+ try {
+ osf.close();
+ } catch (IOException e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "failed to close outpoot stream for image " + imageFullFilePath,
+ EcompPortalUtils.getStackTrace(e));
+ }
+ }
+ }
+ }
+
+ private FileOutputStream writeImageAsBase64(byte[] decodedImage, String imageFullFilePath)
+ throws FileNotFoundException, IOException {
+ FileOutputStream osf;
+ File of = new File(imageFullFilePath);
+ osf = new FileOutputStream(of);
+ osf.write(decodedImage);
+ osf.flush();
+ return osf;
+ }
+
+ private String constructImageName(OnboardingApp onboardingApp) {
+ return "portal" + String.valueOf(onboardingApp.url.hashCode() + "_" + (int) (Math.random() * 100000.0))
+ + ".png";
+ }
+
+ // Don't encrypt or decrypt the password if it is null or the empty string
+ private String decryptedPassword(String encryptedAppPwd, EPApp app) {
+ String result = "";
+ if (encryptedAppPwd != null & encryptedAppPwd.length() > 0) {
+ try {
+ result = CipherUtil.decrypt(encryptedAppPwd,
+ SystemProperties.getProperty(SystemProperties.Decryption_Key));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Unable to decrypt, App name = " + app.getName(),
+ EcompPortalUtils.getStackTrace(e));
+ }
+ }
+ return result;
+ }
+
+ private String encryptedPassword(String decryptedAppPwd, EPApp app) {
+ String result = "";
+ if (decryptedAppPwd != null & decryptedAppPwd.length() > 0) {
+ try {
+ result = CipherUtil.encrypt(decryptedAppPwd,
+ SystemProperties.getProperty(SystemProperties.Decryption_Key));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Unable to encrypt, App name = " + app,
+ EcompPortalUtils.getStackTrace(e));
+ }
+ }
+ return result;
+ }
+
+ public void writeAppsImagesToDiskCacheIfNecessary() {
+ List<EPApp> apps = getAppsFullList();
+ for (EPApp app : apps) {
+ String imageFullFilePath = ecompportalPath + PATH_SEPARATOR + app.getImageUrl();
+ File f = new File(imageFullFilePath);
+ if (f.exists() && !f.isDirectory()) {
+ continue;// logger.debug("verified existence.");
+ }
+
+ if (app.getThumbnail() == null) {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "no thumbnail blob available for this app, cannot write to disk " + app.getName());
+ continue;
+ }
+
+ FileOutputStream osf = null;
+ try {
+ logger.info(EELFLoggerDelegate.debugLogger,
+ "Rewriting image for " + app.getName() + " from db to: " + imageFullFilePath);
+ osf = writeImageAsBase64(app.getThumbnail(), imageFullFilePath);
+ logger.debug(EELFLoggerDelegate.debugLogger, "missing, wrote to disk.");
+ } catch (IOException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "failed to save image to " + imageFullFilePath,
+ EcompPortalUtils.getStackTrace(e));
+ } finally {
+ try {
+ if (osf != null)
+ osf.close();
+ } catch (IOException e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "writeAppsImagesToDiskCacheIfNecessary: failed to close output stream for image "
+ + imageFullFilePath,
+ EcompPortalUtils.getStackTrace(e));
+ }
+ }
+ }
+ }
+
+ private void writeAppImageToDiskCacheIfNecessary(EPApp app) {
+ if (app == null || app.getImageUrl() == null) {
+ return;
+ }
+
+ String imageFullFilePath = ecompportalPath + PATH_SEPARATOR + app.getImageUrl();
+ File f = new File(imageFullFilePath);
+
+ // Image file
+ if (f.exists() && !f.isDirectory()) {
+ return;// logger.debug("verified existence.");
+ }
+
+ if (app.getThumbnail() == null) {
+ logger.debug(EELFLoggerDelegate.debugLogger,
+ "no thumbnail blob available for this app, cannot write to disk " + app.getName());
+ return;
+ }
+
+ FileOutputStream osf = null;
+ try {
+ logger.info(EELFLoggerDelegate.debugLogger,
+ "Rewriting image for " + app.getName() + " from db to: " + imageFullFilePath);
+ osf = writeImageAsBase64(app.getThumbnail(), imageFullFilePath);
+ logger.debug(EELFLoggerDelegate.debugLogger, "missing, wrote to disk.");
+ } catch (IOException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "failed to save image to " + imageFullFilePath,
+ EcompPortalUtils.getStackTrace(e));
+ } finally {
+ try {
+ if (osf != null)
+ osf.close();
+ } catch (IOException e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "writeAppsImagesToDiskCacheIfNecessary: failed to close output stream for image "
+ + imageFullFilePath,
+ EcompPortalUtils.getStackTrace(e));
+ }
+ }
+ }
+
+ @Override
+ public List<EPApp> getUserRemoteApps(String id) {
+
+ StringBuilder query = new StringBuilder();
+
+ query.append("SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = FN_APP.APP_ID where ");
+ query.append(
+ "FN_USER_ROLE.USER_ID = " + id + " AND FN_USER_ROLE.ROLE_ID != " + SUPER_ADMIN_ROLE_ID);
+ query.append(" AND FN_APP.ENABLED = 'Y'");
+
+ TreeSet<EPApp> distinctApps = new TreeSet<EPApp>();
+
+ @SuppressWarnings("unchecked")
+ List<EPApp> adminApps = dataAccessService.executeSQLQuery(query.toString(), EPApp.class, null);
+ for (EPApp app : adminApps) {
+ // Write the image to disk in case if it is missing
+ writeAppImageToDiskCacheIfNecessary(app);
+
+ distinctApps.add(app);
+ }
+
+ List<EPApp> userApps = new ArrayList<EPApp>();
+ userApps.addAll(distinctApps);
+ return userApps;
+
+ }
+
+} \ No newline at end of file
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPAuditService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPAuditService.java
new file mode 100644
index 00000000..7983467b
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPAuditService.java
@@ -0,0 +1,26 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.Date;
+
+public interface EPAuditService {
+ public Date getGuestLastLogin(String attuid);
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPAuditServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPAuditServiceImpl.java
new file mode 100644
index 00000000..9d478fc1
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPAuditServiceImpl.java
@@ -0,0 +1,74 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import org.openecomp.portalsdk.core.service.DataAccessService;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+
+@Service("epAuditService")
+@Transactional
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class EPAuditServiceImpl implements EPAuditService {
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ @Override
+ /* get the guest last login time with attuid as param.
+ * If record not found in table, return null.
+ *
+ */
+ public Date getGuestLastLogin(String attuid) {
+ Map<String, String> params = new HashMap<>();
+ params.put("attuid", attuid);
+ List<Date> list = getDataAccessService().executeNamedQuery("getGuestLastLogin", params, null);
+ Date date=null;
+ if(list!=null){
+ if(list.size()==1) /* if list only contains one item, meaning this is the first time user logs in or record not found in db*/
+ date = list.get(0); /*the guest's current log in time*/
+ else if(list.size()==2)
+ date = list.get(1); /*most recent login date from db*/
+ }
+ return date;
+ }
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+
+} \ No newline at end of file
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPLdapService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPLdapService.java
new file mode 100644
index 00000000..8418bec1
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPLdapService.java
@@ -0,0 +1,31 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import org.openecomp.portalsdk.core.command.support.SearchResult;
+import org.openecomp.portalsdk.core.domain.support.DomainVo;
+
+
+public interface EPLdapService {
+
+ // search POST for users based on the criteria selected in the Request
+ SearchResult searchPost(DomainVo searchCriteria, String sortBy1, String sortBy2, String sortBy3, int pageNo, int dataSize, int orgUserId) throws Exception;
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPLdapServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPLdapServiceImpl.java
new file mode 100644
index 00000000..7cf5965a
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPLdapServiceImpl.java
@@ -0,0 +1,287 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.directory.Attribute;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.DirContext;
+import javax.naming.directory.SearchControls;
+
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.command.support.SearchResult;
+import org.openecomp.portalsdk.core.domain.support.DomainVo;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.service.support.FusionService;
+import org.openecomp.portalsdk.core.service.support.ServiceLocator;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service("epLdapService")
+@Transactional
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+public class EPLdapServiceImpl extends FusionService implements EPLdapService {
+ @Autowired
+ private ServiceLocator serviceLocator;
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPLdapServiceImpl.class);
+
+ @EPAuditLog
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ public SearchResult searchPost(DomainVo searchCriteria, String sortBy1, String sortBy2, String sortBy3,
+ int pageNo, int dataSize, int orgUserId) throws Exception {
+
+ String remoteHost = "";
+
+ // initialize the directory context to access POST
+ DirContext dirContext = serviceLocator.getDirContext(SystemProperties.getProperty(SystemProperties.POST_INITIAL_CONTEXT_FACTORY),
+ SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL),
+ SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL));
+
+ SearchResult searchResult = new SearchResult();
+
+ try {
+
+ remoteHost = String.format("%s/%s", SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL),
+ SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL));
+ MDC.put(EPSystemProperties.FULL_URL, remoteHost);
+
+ String[] postAttributes = {"nickname","givenName","initials","sn","employeeNumber","mail","telephoneNumber",
+ "departmentNumber","a1","street","roomNumber","l","st","postalCode","zip4","physicalDeliveryOfficeName","bc",
+ "friendlyCountryName","bd","bdname","bu","buname","jtname","mgrid","a2","compcode","compdesc",
+ "costcenter","silo","b2"};
+
+ SearchControls searchControls = new SearchControls();
+ searchControls.setTimeLimit(5000);
+ searchControls.setReturningAttributes(postAttributes);
+
+ StringBuffer filterClause = new StringBuffer("(&(objectClass=*)");
+
+ EPUser user = (EPUser)searchCriteria;
+
+ if(Utilities.nvl(user.getFirstName()).length() > 0) {
+ filterClause.append("(givenName=").append(user.getFirstName()).append("*)");
+ }
+ if(Utilities.nvl(user.getLastName()).length() > 0) {
+ filterClause.append("(sn=").append(user.getLastName()).append("*)");
+ }
+ if(Utilities.nvl(user.getHrid()).length() > 0) {
+ filterClause.append("(employeeNumber=").append(user.getHrid()).append("*)");
+ }
+ if(Utilities.nvl(user.getOrgManagerUserId()).length() > 0) {
+ filterClause.append("(mgrid=").append(user.getOrgManagerUserId()).append("*)");
+ }
+ if(Utilities.nvl(user.getOrgCode()).length() > 0) {
+ filterClause.append("(departmentNumber=").append(user.getOrgCode()).append("*)");
+ }
+ if(Utilities.nvl(user.getEmail()).length() > 0) {
+ filterClause.append("(mail=").append(user.getEmail()).append("*)");
+ }
+ if(Utilities.nvl(user.getOrgUserId()).length() > 0) {
+ filterClause.append("(a1=").append(user.getOrgUserId()).append("*)");
+ }
+ filterClause.append("(c3=N)"); // this has been added to filter CP09 entries on the LDAP server that are duplicates of existing individuals
+ filterClause.append(")");
+
+ List list = new ArrayList();
+ if (!filterClause.toString().equals("(&(objectClass=*))")) {
+ NamingEnumeration e = dirContext.search(SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL) + "/" +
+ SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL),
+ filterClause.toString(),
+ searchControls);
+ list = processResults(e);
+ }
+
+ Collections.sort(list);
+
+ searchResult = new SearchResult(list);
+ searchResult.setPageNo(pageNo);
+ if(dataSize >= 0) {
+ searchResult.setDataSize(dataSize);
+ }
+ else {
+ searchResult.setDataSize(list.size());
+ }
+ } catch(NamingException ne) {
+ String stackTrace = EcompPortalUtils.getStackTrace(ne);
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing the LDAP search. Details: " + stackTrace);
+ } catch(Exception e) {
+ String stackTrace = EcompPortalUtils.getStackTrace(e);
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing the LDAP search. Details: " + stackTrace);
+ }
+ finally {
+ dirContext.close();
+ }
+
+ return searchResult;
+ }
+
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ @EPMetricsLog
+ private ArrayList processResults(NamingEnumeration e) throws NamingException {
+ ArrayList results = new ArrayList();
+ int count = 0;
+
+ while (e.hasMore()) {
+ javax.naming.directory.SearchResult searchResult = (javax.naming.directory.SearchResult)e.next();
+ results.add(processAttributes(searchResult.getAttributes()));
+ count++;
+
+ if(count > Integer.parseInt(SystemProperties.getProperty(SystemProperties.POST_MAX_RESULT_SIZE))) {
+ break;
+ }
+ }
+ return results;
+ }
+
+
+ @SuppressWarnings("rawtypes")
+ @EPMetricsLog
+ private DomainVo processAttributes(Attributes resultAttributes) throws NamingException {
+ EPUser user = new EPUser();
+
+ try {
+ if (resultAttributes == null) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "This result has no attributes");
+ } else {
+ for (NamingEnumeration e = resultAttributes.getAll(); e.hasMore();) { //why the nested loop?
+ Attribute attribute = (Attribute)e.next();
+ for (NamingEnumeration ie = attribute.getAll(); ie.hasMore();) {
+ if (attribute.getID().equalsIgnoreCase("nickname")) {
+ user.setFirstName((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("initials")) {
+ user.setMiddleInitial((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("sn")) {
+ user.setLastName((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("employeeNumber")) {
+ user.setHrid((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("mail")) {
+ user.setEmail((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("telephoneNumber")) {
+ user.setPhone((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("departmentNumber")) {
+ user.setOrgCode((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("a1")) {
+ user.setOrgUserId((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("street")) {
+ user.setAddress1((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("roomNumber")) {
+ user.setAddress2((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("l")) {
+ user.setCity((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("st")) {
+ user.setState((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("postalCode")) {
+ user.setZipCode((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("zip4")) {
+ user.setZipCodeSuffix((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("physicalDeliveryOfficeName")) {
+ user.setLocationClli((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("bc")) {
+ user.setBusinessCountryCode((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("friendlyCountryName")) {
+ user.setBusinessCountryName((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("bd")) {
+ user.setDepartment((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("bdname")) {
+ user.setDepartmentName((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("jtname")) {
+ user.setJobTitle((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("mgrid")) {
+ user.setOrgManagerUserId((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("a2")) {
+ user.setCommandChain((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("compcode")) {
+ user.setCompanyCode((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("compdesc")) {
+ user.setCompany((String) ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("bu")) {
+ user.setBusinessUnit((String)ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("buname")) {
+ user.setBusinessUnitName((String)ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("silo")) {
+ user.setSiloStatus((String)ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("costcenter")) {
+ user.setCostCenter((String)ie.next());
+ }
+ else if (attribute.getID().equalsIgnoreCase("b2")) {
+ user.setFinancialLocCode((String)ie.next());
+ }
+ else { //we don't care about returned attribute, let's move on
+ ie.next();
+ }
+
+ }
+ }
+ }
+ } catch (NamingException e) {
+ String stackTrace = EcompPortalUtils.getStackTrace(e);
+ logger.error(EELFLoggerDelegate.errorLogger, "An error occurred while processing the following user from POST with an userId of " + user.getOrgUserId());
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occcurred while processing LDAP search results, Details: " + stackTrace);
+ } catch(Exception e) {
+ String stackTrace = EcompPortalUtils.getStackTrace(e);
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occcurred while processing LDAP search results, Details: " + stackTrace);
+ }
+
+ return user;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPLoginService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPLoginService.java
new file mode 100644
index 00000000..4d0337a5
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPLoginService.java
@@ -0,0 +1,42 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+
+import java.util.HashMap;
+
+import org.openecomp.portalapp.command.EPLoginBean;
+import org.openecomp.portalapp.portal.domain.EPUser;
+
+
+public interface EPLoginService {
+
+ // validate user exists in the system
+ @SuppressWarnings("rawtypes")
+ EPLoginBean findUser(EPLoginBean bean, String menuPropertiesFilename, HashMap additionalParams) throws Exception;
+
+ @SuppressWarnings("rawtypes")
+ EPLoginBean findUser(EPLoginBean bean, String menuPropertiesFilename, HashMap additionalParams, boolean matchPassword) throws Exception;
+
+ public EPUser findUserWithoutPwd(String loginId);
+
+ @SuppressWarnings("rawtypes")
+ public EPLoginBean findUserWithoutPassword(EPLoginBean bean, String menuPropertiesFilename, HashMap additionalParams ) throws Exception;
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPLoginServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPLoginServiceImpl.java
new file mode 100644
index 00000000..48e06be6
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPLoginServiceImpl.java
@@ -0,0 +1,235 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.openecomp.portalapp.command.EPLoginBean;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.domain.EPUserApp;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
+import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalapp.util.EPUserUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.menu.MenuBuilder;
+import org.openecomp.portalsdk.core.service.DataAccessService;
+import org.openecomp.portalsdk.core.service.support.FusionService;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.openecomp.portalsdk.core.web.support.AppUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service("eploginService")
+@Transactional
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class EPLoginServiceImpl extends FusionService implements EPLoginService {
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPLoginServiceImpl.class);
+
+ @SuppressWarnings("unused")
+ private MenuBuilder menuBuilder;
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+
+ @SuppressWarnings("rawtypes")
+ public EPLoginBean findUser(EPLoginBean bean, String menuPropertiesFilename, HashMap additionalParams ) throws Exception {
+ return findUser(bean, menuPropertiesFilename, additionalParams, true);
+ }
+
+ @SuppressWarnings("rawtypes")
+ public EPLoginBean findUser(EPLoginBean bean, String menuPropertiesFilename, HashMap additionalParams, boolean matchPassword) throws Exception {
+ EPUser user = null;
+ EPUser userCopy = null;
+
+ if (bean.getOrgUserId() != null) {
+ user = (EPUser) findUser(bean);
+ } else {
+ if (matchPassword)
+ user = (EPUser) findUser(bean.getLoginId(), bean.getLoginPwd());
+ else
+ user = (EPUser) findUserWithoutPwd(bean.getLoginId());
+ }
+
+ if (user != null) {
+
+ // raise an error if the application is locked and the user does not have system administrator privileges
+ if (AppUtils.isApplicationLocked() && !EPUserUtils.hasRole(user, SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID))) {
+ bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_APPLICATION_LOCKED);
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeUserAdminPrivilegesInfo, user.getLoginId());
+ }
+
+ // raise an error if the user is inactive
+ if (!user.getActive()) {
+ bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE);
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeUserInactiveWarning, user.getLoginId());
+ }
+
+/*
+ * Original SDK from QUANTUM
+ boolean hasActiveRole = false;
+ Iterator roles = user.getRoles().iterator();
+ while (roles.hasNext()) {
+ Role role = (Role) roles.next();
+ hasActiveRole = true;
+ if (role.getActive()) {
+ break;
+ }
+ }
+ */
+
+ // raise an error if no active roles exist for the user
+ if (!userHasActiveRoles(user.getEPUserApps())) {
+ bean.setLoginErrorMessage(SystemProperties.MESSAGE_KEY_LOGIN_ERROR_USER_INACTIVE);
+ }
+
+ // only login the user if no errors have occurred
+ if (bean.getLoginErrorMessage() == null) {
+
+ // this will be a snapshot of the user's information as retrieved from the database
+ userCopy = (EPUser) user.clone();
+
+ // update the last logged in date for the user
+ user.setLastLoginDate(new Date());
+ getDataAccessService().saveDomainObject(user, additionalParams);
+
+ // update the audit log of the user
+ // Check for the client device type and set log attributes appropriately
+
+ // save the above changes to the User and their audit trail
+
+ // create the application menu based on the user's privileges
+ Set appMenu = getMenuBuilder().getMenu(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_SET_NAME), dataAccessService);
+ bean.setMenu(appMenu != null ? appMenu : new HashSet());
+ Set businessDirectMenu = getMenuBuilder().getMenu(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_SET_NAME), dataAccessService);
+ bean.setBusinessDirectMenu(businessDirectMenu != null ? businessDirectMenu : new HashSet());
+
+ bean.setUser(userCopy);
+ }
+
+ } else {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeUserMissingError, bean.getOrgUserId());
+ }
+
+
+ return bean;
+ }
+
+ private boolean userHasActiveRoles(Set<EPUserApp> userApps) {
+ for (EPUserApp userApp : userApps) {
+ if (userApp.getRole().getActive()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @SuppressWarnings("rawtypes")
+ public EPLoginBean findUserWithoutPassword(EPLoginBean bean, String menuPropertiesFilename, HashMap additionalParams ) throws Exception {
+ return findUser(bean, menuPropertiesFilename, additionalParams, false);
+ }
+
+ public EPUser findUser(String loginId, String password) {
+ List<?> list = null;
+
+ StringBuffer criteria = new StringBuffer();
+ criteria.append(" where login_id = '").append(loginId).append("'")
+ .append(" and login_pwd = '").append(password).append("'");
+
+ try {
+ list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null);
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ String stackTrace = EcompPortalUtils.getStackTrace(e);
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing findUser operation. Details: " + stackTrace);
+ }
+
+ return (list == null || list.size() == 0) ? null : (EPUser) list.get(0);
+ }
+
+ @Override
+ public EPUser findUserWithoutPwd(String loginId) {
+ List<?> list = null;
+
+ StringBuffer criteria = new StringBuffer();
+ criteria.append(" where login_id = '").append(loginId).append("'");
+
+ try {
+ list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null);
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ String stackTrace = EcompPortalUtils.getStackTrace(e);
+ String message = "Exception occurred while performing findUser: '" + loginId + "'. Details: ";
+ logger.error(EELFLoggerDelegate.errorLogger, message + stackTrace);
+ }
+
+ return (list == null || list.size() == 0) ? null : (EPUser)list.get(0);
+ }
+
+
+ public EPUser findUser(EPLoginBean bean) {
+ List<?> list = null;
+
+ StringBuffer criteria = new StringBuffer();
+ criteria.append(" where org_user_id = '").append(bean.getOrgUserId()).append("'");
+
+ try {
+ list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null);
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ String stackTrace = EcompPortalUtils.getStackTrace(e);
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing findUser operation. Details: " + stackTrace);
+ }
+
+ return (list == null || list.size() == 0) ? null : (EPUser)list.get(0);
+ }
+
+
+ public MenuBuilder getMenuBuilder() {
+ return new MenuBuilder();
+ }
+
+
+ public void setMenuBuilder(MenuBuilder menuBuilder) {
+ this.menuBuilder = menuBuilder;
+ }
+
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPRoleService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPRoleService.java
new file mode 100644
index 00000000..91aa77b1
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPRoleService.java
@@ -0,0 +1,32 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import org.openecomp.portalapp.portal.domain.EPRole;
+
+
+public interface EPRoleService {
+
+ // Used by ECOMP. Get cached role by two columns used by ECOMP only. app id, and external app role id.
+ EPRole getRole(Long appId, Long appRoleid);
+ public void saveRole(EPRole domainRole);
+
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPRoleServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPRoleServiceImpl.java
new file mode 100644
index 00000000..467b9007
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/EPRoleServiceImpl.java
@@ -0,0 +1,149 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.openecomp.portalapp.portal.domain.EPRole;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalsdk.core.domain.RoleFunction;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.service.DataAccessService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service("epRoleService")
+@Transactional
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class EPRoleServiceImpl implements EPRoleService{
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPRoleServiceImpl.class);
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ @SuppressWarnings("unchecked")
+ public List<RoleFunction> getRoleFunctions() {
+ //List msgDB = getDataAccessService().getList(Profile.class, null);
+ return getDataAccessService().getList(RoleFunction.class, null);
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<EPRole> getAvailableChildRoles(Long roleId) {
+ List<EPRole> availableChildRoles = (List<EPRole>)getDataAccessService().getList(EPRole.class,null);
+ if(roleId==null || roleId==0){
+ return availableChildRoles;
+ }
+
+ EPRole currentRole = (EPRole)getDataAccessService().getDomainObject(EPRole.class,roleId,null);
+ Set<EPRole> allParentRoles = new TreeSet<EPRole>();
+ allParentRoles = getAllParentRolesAsList(currentRole, allParentRoles);
+
+
+ Iterator<EPRole> availableChildRolesIterator = availableChildRoles.iterator();
+ while (availableChildRolesIterator.hasNext()) {
+ EPRole role = availableChildRolesIterator.next();
+ if(!role.getActive() || allParentRoles.contains(role) || role.getId().equals(roleId)){
+ availableChildRolesIterator.remove();
+ }
+ }
+ return availableChildRoles;
+ }
+
+ private Set<EPRole> getAllParentRolesAsList(EPRole role, Set<EPRole> allParentRoles) {
+ Set<EPRole> parentRoles = role.getParentRoles();
+ allParentRoles.addAll(parentRoles);
+ Iterator<EPRole> parentRolesIterator = parentRoles.iterator();
+ while (parentRolesIterator.hasNext()) {
+ getAllParentRolesAsList(parentRolesIterator.next(),allParentRoles);
+ }
+ return allParentRoles;
+ }
+
+ public RoleFunction getRoleFunction(String code) {
+ return (RoleFunction)getDataAccessService().getDomainObject(RoleFunction.class, code, null);
+ }
+
+ public void saveRoleFunction(RoleFunction domainRoleFunction) {
+ getDataAccessService().saveDomainObject(domainRoleFunction, null);
+ }
+
+ public void deleteRoleFunction(RoleFunction domainRoleFunction) {
+ getDataAccessService().deleteDomainObject(domainRoleFunction, null);
+ }
+
+ public EPRole getRole(Long id) {
+ return (EPRole)getDataAccessService().getDomainObject(EPRole.class, id, null);
+ }
+
+ // TODO: refactor
+ private static final String getAppRoleSqlFormat ="SELECT * FROM fn_role where APP_ID = %s AND APP_ROLE_ID = %s";
+
+ @SuppressWarnings("unchecked")
+ public EPRole getRole(Long appId, Long appRoleid) {
+ if(appId == null || appRoleid == null){
+ logger.error(EELFLoggerDelegate.errorLogger, String.format("getRole does not support null appId or roleId. appRoleid=%s, appRoleid=%s", appId, appRoleid));
+ return null;
+ }
+
+ String sql = String.format(getAppRoleSqlFormat, appId, appRoleid);
+
+ List<EPRole> roles = (List<EPRole>)dataAccessService.executeSQLQuery(sql, EPRole.class, null);
+ int resultsCount = roles.size();
+ if(resultsCount > 1){
+ logger.error(EELFLoggerDelegate.errorLogger, String.format("search by appId=%s, appRoleid=%s should have returned 0 or 1 results. Got %d. This is an internal server error.", appId, appRoleid, resultsCount));
+ logger.error(EELFLoggerDelegate.errorLogger, "Trying to recover from duplicates by returning the first search result. This issue should be treated, it is probably not critical because duplicate roles should be similar.");
+ return roles.get(0);
+ } else if(resultsCount == 1){
+ return roles.get(0);
+ }
+ return null;
+ }
+
+ public void saveRole(EPRole domainRole) {
+ getDataAccessService().saveDomainObject(domainRole, null);
+ }
+
+ public void deleteRole(EPRole domainRole) {
+ getDataAccessService().deleteDomainObject(domainRole, null);
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<EPRole> getAvailableRoles() {
+ return getDataAccessService().getList(EPRole.class, null);
+ }
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+}
+
+
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/FunctionalMenuService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/FunctionalMenuService.java
new file mode 100644
index 00000000..9de45996
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/FunctionalMenuService.java
@@ -0,0 +1,50 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.List;
+
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItem;
+import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson;
+import org.openecomp.portalapp.portal.transport.FieldsValidator;
+import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
+import org.openecomp.portalapp.portal.transport.FunctionalMenuItemJson;
+
+public interface FunctionalMenuService {
+ List<FunctionalMenuItem> getFunctionalMenuItems (EPUser user);
+ // return all active menu items
+ List<FunctionalMenuItem> getFunctionalMenuItems ();
+ // return all active menu items. If all is true, return all active and inactive menu items.
+ List<FunctionalMenuItem> getFunctionalMenuItems(Boolean all);
+ List<FunctionalMenuItem> getFunctionalMenuItemsForApp (Integer appId);
+ List<FunctionalMenuItem> getFunctionalMenuItemsForUser (String userId);
+ FunctionalMenuItem getFunctionalMenuItemDetails (Integer menuid);
+ FieldsValidator createFunctionalMenuItem (FunctionalMenuItemJson menuItemJson);
+ FieldsValidator editFunctionalMenuItem (FunctionalMenuItemJson menuItemJson);
+ FieldsValidator deleteFunctionalMenuItem (Long menuId);
+ FieldsValidator regenerateAncestorTable ();
+ //Methods relevant to favorites
+ FieldsValidator setFavoriteItem(FavoritesFunctionalMenuItem menuItemJson);
+ List<FavoritesFunctionalMenuItemJson> getFavoriteItems(Long userId);
+ FieldsValidator removeFavoriteItem (Long userId, Long menuId);
+ //Assign URLs under Help Menu
+ void assignHelpURLs(List<FunctionalMenuItem> menuItems);
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/FunctionalMenuServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/FunctionalMenuServiceImpl.java
new file mode 100644
index 00000000..30aaf5d3
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/FunctionalMenuServiceImpl.java
@@ -0,0 +1,862 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.annotation.PostConstruct;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.lang3.StringUtils;
+import org.hibernate.Criteria;
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.Transaction;
+import org.hibernate.criterion.Projections;
+import org.hibernate.criterion.Restrictions;
+import org.openecomp.portalapp.portal.domain.EPApp;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItem;
+import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson;
+import org.openecomp.portalapp.portal.transport.FieldsValidator;
+import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
+import org.openecomp.portalapp.portal.transport.FunctionalMenuItemJson;
+import org.openecomp.portalapp.portal.transport.FunctionalMenuRole;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.service.DataAccessService;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+
+@Service("functionalMenuService")
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class FunctionalMenuServiceImpl implements FunctionalMenuService {
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FunctionalMenuServiceImpl.class);
+
+ private Long ACCOUNT_ADMIN_ROLE_ID = 999L;
+ private String RESTRICTED_APP_ROLE_ID = "900";
+
+ @Autowired
+ private DataAccessService dataAccessService;
+ @Autowired
+ private SessionFactory sessionFactory;
+
+ @PostConstruct
+ private void init() {
+ try {
+ ACCOUNT_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPSystemProperties.ACCOUNT_ADMIN_ROLE_ID));
+ RESTRICTED_APP_ROLE_ID = SystemProperties.getProperty(EPSystemProperties.RESTRICTED_APP_ROLE_ID);
+ } catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+ }
+
+ public List<FunctionalMenuItem> getFunctionalMenuItems(EPUser user) {
+ List<FunctionalMenuItem> menuItems = new ArrayList<FunctionalMenuItem>();
+ return menuItems;
+ }
+
+ public List<FunctionalMenuItem> getFunctionalMenuItems() {
+ return getFunctionalMenuItems(false);
+ }
+
+ public List<FunctionalMenuItem> getFunctionalMenuItems(Boolean all) {
+ // Divide this into 2 queries: one which returns the bottom-level menu items associated with Restricted apps,
+ // and one that returns all the other menu items. Then we can easily add the boolean flag
+ // restrictedApp to each FunctionalMenuItem, to be used by the front end.
+ String activeWhereClause = "";
+ if (! all) {
+ activeWhereClause = " AND UPPER(m.active_yn) = 'Y' ";
+ }
+ String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
+ + "FROM fn_menu_functional m, fn_menu_functional_roles r "
+ + "WHERE m.menu_id = r.menu_id "
+ + activeWhereClause //" AND UPPER(m.active_yn) = 'Y' "
+ + " AND r.role_id != '" + RESTRICTED_APP_ROLE_ID + "' "
+ + " UNION "
+ + " SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
+ + " FROM fn_menu_functional m "
+ + " WHERE m.url='' "
+ + activeWhereClause; //" AND UPPER(m.active_yn) = 'Y' ";
+ logQuery(sql);
+
+ @SuppressWarnings("unchecked")
+ List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
+ for (FunctionalMenuItem menuItem : menuItems) {
+ menuItem.restrictedApp = false;
+ }
+
+ sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
+ + "FROM fn_menu_functional m, fn_menu_functional_roles r "
+ + "WHERE m.menu_id = r.menu_id "
+ + activeWhereClause //" AND UPPER(m.active_yn) = 'Y' "
+ + " AND r.role_id = '" + RESTRICTED_APP_ROLE_ID + "' ";
+ logQuery(sql);
+ @SuppressWarnings("unchecked")
+ List<FunctionalMenuItem> menuItems2 = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
+ for (FunctionalMenuItem menuItem : menuItems2) {
+ menuItem.restrictedApp = true;
+ menuItems.add(menuItem);
+ }
+
+ return menuItems;
+ }
+
+ public List<FunctionalMenuItem> getFunctionalMenuItemsForApp(Integer appId) {
+ String sql = "SELECT DISTINCT m1.menu_id, m1.column_num, m1.text, m1.parent_menu_id, m1.url, m.active_yn "
+ + " FROM fn_menu_functional m, fn_menu_functional m1, fn_menu_functional_ancestors a, fn_menu_functional_roles mr "
+ + " WHERE " + " mr.app_id='" + appId + "' " + " AND mr.menu_id = m.menu_id " + " AND UPPER(m.active_yn) = 'Y'"
+ + " AND UPPER(m1.active_yn) ='Y'" + " AND a.menu_id = m.menu_id " + " AND a.ancestor_menu_id = m1.menu_id";
+ logQuery(sql);
+ logger.debug(EELFLoggerDelegate.debugLogger, "getFunctionalMenuItemsForApp: logged the query");
+
+ @SuppressWarnings("unchecked")
+ List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
+
+ return menuItems;
+ }
+
+ public List<FunctionalMenuItem> getFunctionalMenuItemsForUser(String orgUserId) {
+ // m represents the functional menu items that are the leaf nodes
+ // m1 represents the functional menu items for all the nodes
+
+ // Divide this into 2 queries: one which returns the bottom-level menu items associated with Restricted apps,
+ // and one that returns all the other menu items. Then we can easily add the boolean flag
+ // restrictedApp to each FunctionalMenuItem, to be used by the front end.
+ String sql = "SELECT DISTINCT m1.menu_id, m1.column_num, m1.text, m1.parent_menu_id, m1.url, m.active_yn "
+ + " FROM fn_menu_functional m, fn_menu_functional m1, fn_menu_functional_ancestors a, "
+ + " fn_menu_functional_roles mr, fn_user u , fn_user_role ur " + " WHERE " + " u.org_user_id='" + orgUserId
+ + "' " + " AND u.user_id = ur.user_id " + " AND ur.app_id = mr.app_id " +
+ // " AND ur.role_id = mr.role_id " +
+ " AND (ur.role_id = mr.role_id " + " OR ur.role_id = '" + ACCOUNT_ADMIN_ROLE_ID + "') "
+ + " AND m.menu_id = mr.menu_id " + " AND UPPER(m.active_yn) = 'Y'" + " AND UPPER(m1.active_yn) ='Y' "
+ + " AND a.menu_id = m.menu_id " + " AND a.ancestor_menu_id = m1.menu_id "
+ + " UNION "
+ // the ancestors of the restricted app menu items
+ + " select m1.menu_id, m1.column_num, m1.text, m1.parent_menu_id, m1.url, m1.active_yn "
+ + " FROM fn_menu_functional m, fn_menu_functional_roles mr, fn_menu_functional m1, "
+ + " fn_menu_functional_ancestors a "
+ + " where a.menu_id = m.menu_id "
+ + " AND a.ancestor_menu_id = m1.menu_id "
+ + " AND m.menu_id != m1.menu_id "
+ + " AND m.menu_id = mr.menu_id "
+ + " AND mr.role_id = '" + RESTRICTED_APP_ROLE_ID + "' "
+ + " AND UPPER(m.active_yn) = 'Y'" + " AND UPPER(m1.active_yn) ='Y' "
+ // Add the Favorites menu item
+ + " UNION "
+ + " SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
+ + " FROM fn_menu_functional m "
+ + " WHERE m.text in ('Favorites','Get Access','Contact Us','Support','User Guide','Help')";
+
+ logQuery(sql);
+ logger.debug(EELFLoggerDelegate.debugLogger, "getFunctionalMenuItemsForUser: logged the query");
+
+ @SuppressWarnings("unchecked")
+ List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
+ for (FunctionalMenuItem menuItem : menuItems) {
+ menuItem.restrictedApp = false;
+ }
+
+ sql = " SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn "
+ + " FROM fn_menu_functional m, fn_menu_functional_roles r "
+ + " WHERE m.menu_id = r.menu_id "
+ + " AND UPPER(m.active_yn) = 'Y' "
+ + " AND r.role_id = '" + RESTRICTED_APP_ROLE_ID + "' ";
+ logQuery(sql);
+ @SuppressWarnings("unchecked")
+ List<FunctionalMenuItem> menuItems2 = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
+ for (FunctionalMenuItem menuItem : menuItems2) {
+ menuItem.restrictedApp = true;
+ menuItems.add(menuItem);
+ }
+
+ return menuItems;
+ }
+
+ public FunctionalMenuItem getFunctionalMenuItemDetails(Integer menuid) {
+ // First, fill in the fields that apply to all menu items
+
+ String sql = "SELECT * FROM fn_menu_functional WHERE menu_id = '" + menuid + "'";
+ logQuery(sql);
+ @SuppressWarnings("unchecked")
+ List<FunctionalMenuItem> menuItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null);
+ FunctionalMenuItem menuItem = (menuItems == null || menuItems.isEmpty() ? null : menuItems.get(0));
+ // If it is a bottom-level menu item, must fill in the appid and the
+ // roles
+ sql = "SELECT * FROM fn_menu_functional_roles WHERE menu_id = '" + menuid + "'";
+ logQuery(sql);
+ @SuppressWarnings("unchecked")
+ List<FunctionalMenuRole> roleItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuRole.class, null);
+ if (roleItems.size() > 0) {
+ Integer appid = roleItems.get(0).appId;
+ menuItem.appid = appid;
+ List<Integer> roles = new ArrayList<Integer>();
+ for (FunctionalMenuRole roleItem : roleItems) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: app_id: " + roleItem.appId + "; role_id: " + roleItem.roleId + "\n");
+ roles.add(roleItem.roleId);
+ }
+ menuItem.roles = roles;
+ }
+
+ return menuItem;
+ }
+
+ private FieldsValidator menuItemFieldsChecker(FunctionalMenuItemJson menuItemJson) {
+ FieldsValidator fieldsValidator = new FieldsValidator();
+ try {
+ // TODO: validate all the fields
+ @SuppressWarnings("unchecked")
+ List<FunctionalMenuItem> functionalMenuItems = dataAccessService.getList(FunctionalMenuItem.class,
+ " where text = '" + menuItemJson.text + "'", null, null);
+
+ boolean dublicatedName = false;
+ for (FunctionalMenuItem fnMenuItem : functionalMenuItems) {
+ if (menuItemJson.menuId != null && menuItemJson.menuId.equals(fnMenuItem.menuId)) {
+ // FunctionalMenuItem should not be compared with itself
+ continue;
+ }
+
+ if (!dublicatedName && fnMenuItem.text.equalsIgnoreCase(menuItemJson.text)) {
+ dublicatedName = true;
+ break;
+ }
+ }
+ if (dublicatedName) {
+ fieldsValidator.addProblematicFieldName("text");
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
+ fieldsValidator.errorCode = new Long(EPSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
+ logger.debug(EELFLoggerDelegate.debugLogger, "In menuItemFieldsChecker, Error: we have an duplicate text field");
+ } else if (StringUtils.isEmpty(menuItemJson.text) && menuItemJson.menuId == null) {
+ // text must be non empty for a create. For an edit, can be empty, which means it is a move request.
+ // a null menuId indicates a create.
+ fieldsValidator.addProblematicFieldName("text");
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
+ logger.debug(EELFLoggerDelegate.debugLogger, "In menuItemFieldsChecker, Error: we have an empty text field");
+ } else {
+ // The url, appid, and roles must either be all filled or all empty.
+ Boolean urlIsEmpty = StringUtils.isEmpty(menuItemJson.url);
+ Boolean rolesIsEmpty = menuItemJson.roles == null || menuItemJson.roles.isEmpty();
+ Boolean appidIsEmpty = menuItemJson.appid == null || menuItemJson.appid == 0;
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: menuItemfieldsChecker: urlIsEmpty: " + urlIsEmpty + "; rolesIsEmpty: " + rolesIsEmpty + "; appidIsEmpty: " + appidIsEmpty +"\n");
+ if (!((urlIsEmpty && rolesIsEmpty && appidIsEmpty) || (!urlIsEmpty && !rolesIsEmpty && !appidIsEmpty)))
+ {
+ fieldsValidator.addProblematicFieldName("url,roles,appid");
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
+ logger.debug(EELFLoggerDelegate.debugLogger, "In menuItemFieldsChecker, Error: we don't have: either all 3 fields empty or all 3 fields nonempty");
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "In menuItemFieldsChecker, Success: either all 3 fields empty or all 3 fields nonempty");
+ }
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while validating the FunctionalMenuItems. Details: " + EcompPortalUtils.getStackTrace(e));
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+
+ return fieldsValidator;
+ }
+
+ // Turn foreign key checks on or off
+ protected void setForeignKeys(Session localSession, Boolean on) {
+ String keyCheck = "0";
+ if (on) {
+ keyCheck = "1";
+ }
+ String sql = "set FOREIGN_KEY_CHECKS="+keyCheck;
+ logQuery(sql);
+ Query query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ }
+
+ public FieldsValidator createFunctionalMenuItem(FunctionalMenuItemJson menuItemJson) {
+ FieldsValidator fieldsValidator = menuItemFieldsChecker(menuItemJson);
+ if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: createFunctionalMenuItem: test 1");
+ boolean result = false;
+ Session localSession = null;
+ Transaction transaction = null;
+ try {
+ FunctionalMenuItem menuItem = new FunctionalMenuItem();
+ menuItem.appid = menuItemJson.appid;
+ menuItem.roles = menuItemJson.roles;
+ menuItem.url = menuItemJson.url;
+ menuItem.text = menuItemJson.text;
+ menuItem.parentMenuId = menuItemJson.parentMenuId;
+ menuItem.active_yn = "Y";
+ localSession = sessionFactory.openSession();
+
+ // If the app is disabled, deactivate the menu item.
+ if (menuItemJson.appid != null) {
+ Long appidLong = Long.valueOf(menuItemJson.appid);
+ EPApp app = (EPApp) localSession.get(EPApp.class, appidLong);
+ if (app != null && ! app.getEnabled()) {
+ menuItem.active_yn = "N";
+ }
+ }
+
+ // Set the column number to 1 higher than the highest column
+ // number under this parent.
+ Criteria criteria = localSession.createCriteria(FunctionalMenuItem.class);
+ criteria.setProjection(Projections.max("column"));
+ criteria.add(Restrictions.eq("parentMenuId", menuItem.parentMenuId));
+ Integer maxColumn = (Integer) criteria.uniqueResult();
+ if (maxColumn == null) {
+ maxColumn = 0;
+ }
+ menuItem.column = maxColumn + 1;
+ logger.debug(EELFLoggerDelegate.debugLogger, "about to create menu item: " + menuItem.toString());
+
+ transaction = localSession.beginTransaction();
+ // localSession.saveOrUpdate(newMenuItem);
+ localSession.save(menuItem);
+ Long menuid = menuItem.menuId;
+ menuItemJson.menuId = menuid;
+ logger.debug(EELFLoggerDelegate.debugLogger, "after saving menu object, new id: " + menuid);
+
+ // Next, save all the roles
+
+ addRoles(menuItemJson, localSession);
+ transaction.commit();
+ result = true;
+ } catch (Exception e) {
+ EcompPortalUtils.rollbackTransaction(transaction,
+ "createFunctionalMenuItem rollback, exception = " + e);
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ } finally {
+ EcompPortalUtils.closeLocalSession(localSession, "createFunctionalMenuItem");
+ }
+ if (result) {
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: createFunctionalMenuItem: no result. setting httpStatusCode to "
+ + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+ } else {
+ logger.error(EELFLoggerDelegate.errorLogger, "FunctionalMenuServiceImpl.createFunctionalMenuItem: bad request");
+ }
+ return fieldsValidator;
+ }
+
+ /* Add all the roles in the menu item to the database */
+ public void addRoles(FunctionalMenuItemJson menuItemJson, Session localSession) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "entering addRoles.");
+ List<Integer> roles = menuItemJson.roles;
+ if (roles != null && roles.size() > 0) {
+ Integer appid = menuItemJson.appid;
+ Long menuid = menuItemJson.menuId;
+ for (Integer roleid : roles) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "about to create record for role: " + roleid);
+ FunctionalMenuRole role = new FunctionalMenuRole();
+ role.appId = appid;
+ role.menuId = menuid;
+ role.roleId = roleid;
+ localSession.save(role);
+ logger.debug(EELFLoggerDelegate.debugLogger, "after saving role menu object, new id: " + role.id);
+ }
+ }
+ }
+
+ /* Delete all the roles associated with the menu item from the database */
+ public void deleteRoles(Long menuId) {
+ dataAccessService.deleteDomainObjects(FunctionalMenuRole.class, "menu_id='" + menuId + "'", null);
+ }
+
+ /* Delete all favorites associated with the menu item from the database */
+ public void deleteFavorites(Long menuId) {
+ dataAccessService.deleteDomainObjects(FavoritesFunctionalMenuItem.class, "menu_id='" + menuId + "'", null);
+ }
+
+ private Boolean parentMenuIdEqual(Integer menuId1, Integer menuId2) {
+ return ((menuId1 == null && menuId2 == null) || (menuId1 != null && menuId1.equals(menuId2)));
+ }
+
+ private void updateColumnForSiblings(Session localSession, Long menuId, Integer oldParentMenuId,
+ Integer newParentMenuId, Integer oldColumn, Integer newColumn) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "entering updateColumnForSiblings");
+ Criteria criteria = localSession.createCriteria(FunctionalMenuItem.class);
+ criteria.add(Restrictions.ne("menuId", menuId));
+ if (parentMenuIdEqual(oldParentMenuId, newParentMenuId)) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "moving under the same parent");
+ // We are moving to a new position under the same parent
+ if (newParentMenuId == null) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "newParentMenuId is null, so using isNull");
+ criteria.add(Restrictions.isNull("parentMenuId"));
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "newParentMenuId is NOT null, so using eq");
+ criteria.add(Restrictions.eq("parentMenuId", newParentMenuId));
+ }
+ if (oldColumn > newColumn) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "moving to a lower column under the same parent");
+ // We are moving to a lower column under the same parent
+ criteria.add(Restrictions.ge("column", newColumn));
+ criteria.add(Restrictions.lt("column", oldColumn));
+ @SuppressWarnings("unchecked")
+ List<FunctionalMenuItem> menuItems = criteria.list();
+ for (FunctionalMenuItem menuItem : menuItems) {
+ menuItem.column += 1;
+ localSession.save(menuItem);
+ }
+ } else if (oldColumn < newColumn) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "moving to a higher column under the same parent");
+ // We are moving to a higher column under the same parent
+ criteria.add(Restrictions.gt("column", oldColumn));
+ criteria.add(Restrictions.le("column", newColumn));
+ @SuppressWarnings("unchecked")
+ List<FunctionalMenuItem> menuItems = criteria.list();
+ for (FunctionalMenuItem menuItem : menuItems) {
+ menuItem.column -= 1;
+ localSession.save(menuItem);
+ }
+ } else {
+ // No info has changed
+ logger.debug(EELFLoggerDelegate.debugLogger, "no info has changed, so we are not moving");
+ }
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "moving under a new parent");
+ // We are moving under a new parent.
+
+ // Adjust the children under the old parent
+ logger.debug(EELFLoggerDelegate.debugLogger, "about to adjust the children under the old parent");
+
+ // If the parentId is null, must check for its children differently
+ if (oldParentMenuId == null) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "oldParentMenuId is null, so using isNull");
+ criteria.add(Restrictions.isNull("parentMenuId"));
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "oldParentMenuId is NOT null, so using eq");
+ criteria.add(Restrictions.eq("parentMenuId", oldParentMenuId));
+ }
+
+ criteria.add(Restrictions.gt("column", oldColumn));
+ @SuppressWarnings("unchecked")
+ List<FunctionalMenuItem> menuItems1 = criteria.list();
+ for (FunctionalMenuItem menuItem : menuItems1) {
+ menuItem.column -= 1;
+ localSession.save(menuItem);
+ }
+ // Adjust the children under the new parent.
+ logger.debug(EELFLoggerDelegate.debugLogger, "about to adjust the children under the new parent");
+ logger.debug(EELFLoggerDelegate.debugLogger, "get all menu items where menuId!=" + menuId + "; parentMenuId==" + newParentMenuId
+ + "; column>=" + newColumn);
+ criteria = localSession.createCriteria(FunctionalMenuItem.class);
+ criteria.add(Restrictions.ne("menuId", menuId));
+ if (newParentMenuId == null) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "newParentMenuId is null, so using isNull");
+ criteria.add(Restrictions.isNull("parentMenuId"));
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "newParentMenuId is NOT null, so using eq");
+ criteria.add(Restrictions.eq("parentMenuId", newParentMenuId));
+ }
+
+ criteria.add(Restrictions.ge("column", newColumn));
+ @SuppressWarnings("unchecked")
+ List<FunctionalMenuItem> menuItems2 = criteria.list();
+ if (menuItems2 != null) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "found " + menuItems2.size() + " menu items");
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "found null menu items");
+ }
+ for (FunctionalMenuItem menuItem : menuItems2) {
+ menuItem.column += 1;
+ localSession.save(menuItem);
+ }
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger, "done with updateColumnForSiblings");
+ }
+
+ public void removeAppInfo(Session localSession, Long menuId) {
+ // Remove the url, role, and app info from a menu item
+ FunctionalMenuItem menuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class, menuId);
+ menuItem.url = "";
+ deleteRoles(menuId);
+ }
+
+ public FieldsValidator editFunctionalMenuItem(FunctionalMenuItemJson menuItemJson) {
+ boolean result = false;
+ Session localSession = null;
+ Transaction transaction = null;
+ Long menuId = menuItemJson.menuId;
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: editFunctionalMenuItem: test 1");
+ FieldsValidator fieldsValidator = menuItemFieldsChecker(menuItemJson);
+ if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
+ // TODO: make sure menuId is here. And, it might not already exist
+ // in db table.
+ if (menuId == null) {
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
+ logger.error(EELFLoggerDelegate.errorLogger, "FunctionalMenuServiceImpl.editFunctionalMenuItem: bad request");
+ } else {
+ // To simplify the code, assume we will have a transaction
+ try {
+ localSession = sessionFactory.openSession();
+ transaction = localSession.beginTransaction();
+
+ // Get the existing info associated with menuItem from the DB
+ FunctionalMenuItem menuItem = (FunctionalMenuItem) localSession.get(FunctionalMenuItem.class, menuId);
+ Integer oldColumn = menuItem.column;
+ Integer oldParentMenuId = menuItem.parentMenuId;
+ Integer newColumn = menuItemJson.column;
+ Integer newParentMenuId = menuItemJson.parentMenuId;
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "prev info: column: " + oldColumn + "; parentMenuId: " + oldParentMenuId);
+
+ if (menuItemJson.appid != null && menuItemJson.roles != null && !menuItemJson.roles.isEmpty()
+ && menuItemJson.url != null && !menuItemJson.url.isEmpty() && menuItemJson.text != null
+ && !menuItemJson.text.isEmpty()) {
+ // Scenario: appid, roles, url and text are all non-null.
+ // This menu item is associated with an app.
+ // (Note: this should only occur for a bottom-level menu
+ // item with no children.)
+ // 1) Remove all the records from fn_menu_functional_role
+ // for this menuId.
+ // 2) Add records to the fn_menu_function_role table for the
+ // appId and each roleId
+ // 3) Update the url and text for this menu item.
+
+ // Because of foreign key constraints, delete the roles,
+ // then update the menuItem then add the roles.
+ deleteRoles(menuId);
+ // Assumption: this is not a Move, so don't change the
+ // parentMenuId and column.
+ menuItem.appid = menuItemJson.appid;
+ menuItem.roles = menuItemJson.roles;
+ menuItem.url = menuItemJson.url;
+ menuItem.text = menuItemJson.text;
+
+ // If the app is disabled, deactivate the menu item.
+ Long appidLong = Long.valueOf(menuItemJson.appid);
+ EPApp app = (EPApp) localSession.get(EPApp.class, appidLong);
+ if (app != null && ! app.getEnabled()) {
+ menuItem.active_yn = "N";
+ } else {
+ menuItem.active_yn = "Y";
+ }
+
+
+ localSession.update(menuItem);
+ addRoles(menuItemJson, localSession);
+
+ } else if (menuItemJson.appid == null && (menuItemJson.roles == null || menuItemJson.roles.isEmpty())
+ && (menuItemJson.url == null || menuItemJson.url.isEmpty()) && menuItemJson.text != null
+ && !menuItemJson.text.isEmpty()) {
+ // Scenario: appid, roles and url are all null; text is
+ // non-null.
+ // This menu item is NOT associated with an app.
+ // 1) Remove all the records from fn_menu_functional_role
+ // for this menuId
+ // (in case it was previously associated with an app).
+ // 2) Update the text for this menu item.
+ // 3) Set the url to ""
+ deleteRoles(menuId);
+ // Assumption: this is not a Move, so don't change the
+ // parentMenuId and column.
+ menuItem.text = menuItemJson.text;
+ menuItem.url = "";
+ menuItem.active_yn = "Y";
+ localSession.update(menuItem);
+
+ } else if (newColumn != null) {
+ // This is a "move" request.
+ // Menu item has been moved to a different position under
+ // the same parent, or under a new parent.
+ logger.debug(EELFLoggerDelegate.debugLogger, "Doing a move operation.");
+ if (parentMenuIdEqual(oldParentMenuId, newParentMenuId)) {
+ // The parent is the same. We have just changed the
+ // column
+ logger.debug(EELFLoggerDelegate.debugLogger, "moving under the same parent");
+ menuItem.column = newColumn;
+ localSession.update(menuItem);
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "moving under a different parent");
+ menuItem.parentMenuId = newParentMenuId;
+ menuItem.column = newColumn;
+ localSession.update(menuItem);
+ // If we are moving under a new parent, must delete any
+ // app/role info from
+ // the new parent, since it is no longer a leaf menu
+ // item and cannot have app info
+ // associated with it. The front end will have warned
+ // the user and gotten confirmation.
+ if (menuItemJson.parentMenuId != null) {
+ Long parentMenuIdLong = new Long(menuItemJson.parentMenuId);
+ removeAppInfo(localSession, parentMenuIdLong);
+ // deleteRoles(parentMenuIdLong);
+ }
+ }
+ // must update the column for all old and new sibling menu
+ // items
+ updateColumnForSiblings(localSession, menuId, oldParentMenuId, newParentMenuId, oldColumn,
+ newColumn);
+ }
+
+ transaction.commit();
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: editFunctionalMenuItem: finished committing transaction");
+ result = true;
+ } catch (Exception e) {
+ EcompPortalUtils.rollbackTransaction(transaction,
+ "createFunctionalMenuItem rollback, exception = " + e);
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ } finally {
+ EcompPortalUtils.closeLocalSession(localSession, "editFunctionalMenuItem");
+ }
+
+ if (result) {
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: createFunctionalMenuItem: no result. setting httpStatusCode to "
+ + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+ }
+ }
+
+ return fieldsValidator;
+ }
+
+ public FieldsValidator deleteFunctionalMenuItem(Long menuId) {
+ FieldsValidator fieldsValidator = new FieldsValidator();
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: deleteFunctionalMenuItem: test 1");
+ boolean result = false;
+ Session localSession = null;
+ Transaction transaction = null;
+
+ try {
+ localSession = sessionFactory.openSession();
+ transaction = localSession.beginTransaction();
+ // We must turn off foreign keys before deleting a menu item. Otherwise there will be a
+ // constraint violation from the ancestors table.
+ setForeignKeys(localSession, false);
+ deleteRoles(menuId);
+ logger.debug(EELFLoggerDelegate.debugLogger, "deleteFunctionalMenuItem: after deleting roles");
+ deleteFavorites(menuId);
+ logger.debug(EELFLoggerDelegate.debugLogger, "deleteFunctionalMenuItem: after deleting favorites");
+ localSession.delete(localSession.get(FunctionalMenuItem.class, menuId));
+ logger.debug(EELFLoggerDelegate.debugLogger, "deleteFunctionalMenuItem: about to commit");
+ transaction.commit();
+ result = true;
+ } catch (Exception e) {
+ EcompPortalUtils.rollbackTransaction(transaction,
+ "deleteFunctionalMenuItem rollback, exception = " + e);
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ } finally {
+ EcompPortalUtils.closeLocalSession(localSession, "deleteFunctionalMenuItem");
+ }
+ if (result) {
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: deleteFunctionalMenuItem: no result. setting httpStatusCode to "
+ + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+ return fieldsValidator;
+ }
+
+ // Regenerate the fn_menu_functional_ancestors table, which is used
+ // by the queries that return the functional menu items.
+ public FieldsValidator regenerateAncestorTable() {
+ FieldsValidator fieldsValidator = new FieldsValidator();
+ Session localSession = null;
+ Transaction transaction = null;
+
+ try {
+ localSession = sessionFactory.openSession();
+ transaction = localSession.beginTransaction();
+ String sql = "DELETE FROM fn_menu_functional_ancestors";
+ logQuery(sql);
+ Query query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ logger.debug(EELFLoggerDelegate.debugLogger, "regenerateAncestorTable: finished query 1");
+
+ sql = "ALTER TABLE fn_menu_functional_ancestors AUTO_INCREMENT=1";
+ logQuery(sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ logger.debug(EELFLoggerDelegate.debugLogger, "regenerateAncestorTable: reset AUTO_INCREMENT to 1");
+
+ int depth = 0;
+ sql = "INSERT INTO fn_menu_functional_ancestors(menu_id, ancestor_menu_id, depth) "
+ + "SELECT m.menu_id, m.menu_id, " + depth + " FROM fn_menu_functional m";
+ logQuery(sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ logger.debug(EELFLoggerDelegate.debugLogger, "regenerateAncestorTable: finished query 2");
+ for (depth = 0; depth < 3; depth++) {
+ int depthPlusOne = depth + 1;
+ sql = "INSERT INTO fn_menu_functional_ancestors(menu_id, ancestor_menu_id, depth) "
+ + " SELECT a.menu_id, m.parent_menu_id, " + depthPlusOne
+ + " FROM fn_menu_functional m, fn_menu_functional_ancestors a " + " WHERE a.depth='" + depth
+ + "' AND " + " a.ancestor_menu_id = m.menu_id AND " + " m.parent_menu_id != '-1'";
+ logQuery(sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger, "regenerateAncestorTable: finished query 3");
+ transaction.commit();
+ } catch (Exception e) {
+ EcompPortalUtils.rollbackTransaction(transaction,
+ "regenerateAncestorTable rollback, exception = " + e);
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ } finally {
+ EcompPortalUtils.closeLocalSession(localSession, "regenerateAncestorTable");
+ }
+ return fieldsValidator;
+ }
+
+ private void logQuery(String sql) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ }
+
+ public FieldsValidator setFavoriteItem(FavoritesFunctionalMenuItem menuItemJson) {
+ boolean result = false;
+ FieldsValidator fieldsValidator = new FieldsValidator();
+
+ Session localSession = null;
+ Transaction transaction = null;
+
+ try {
+ logger.debug(EELFLoggerDelegate.debugLogger, String.format("Before adding favorite for user id:{0} and menu id:{1} ",menuItemJson.userId,menuItemJson.menuId));
+ localSession = sessionFactory.openSession();
+ transaction = localSession.beginTransaction();
+ localSession.save(menuItemJson);
+ transaction.commit();
+ result = true;
+ logger.debug(EELFLoggerDelegate.debugLogger, String.format("After adding favorite for user id:{0} and menu id:{1} ",menuItemJson.userId,menuItemJson.menuId));
+ } catch (Exception e) {
+ EcompPortalUtils.rollbackTransaction(transaction,"setFavoriteItem rollback, exception = " + e);
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ } finally {
+ EcompPortalUtils.closeLocalSession(localSession, "setFavoriteItem");
+ }
+
+ if(result) {
+ }
+ else {
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+
+ return fieldsValidator;
+ }
+
+ public List<FavoritesFunctionalMenuItemJson> getFavoriteItems(Long userId) {
+ try {
+ logger.debug(EELFLoggerDelegate.debugLogger, "Before getting favorites for user id: " + userId);
+
+ // Divide this into 2 queries: one which returns the favorites items associated with Restricted apps,
+ // and one that returns all the other favorites items. Then we can easily add the boolean flag
+ // restrictedApp to each FavoritesFunctionalMenuItemJson, to be used by the front end.
+
+ String sql = "SELECT f.user_id,f.menu_id,m.text,m.url "
+ + " FROM fn_menu_favorites f, fn_menu_functional m, fn_menu_functional_roles mr "
+ + " WHERE f.user_id='" + userId + "' AND f.menu_id = m.menu_id "
+ + " AND f.menu_id = mr.menu_id "
+ + " AND mr.role_id = '" + RESTRICTED_APP_ROLE_ID + "' ";
+
+ @SuppressWarnings("unchecked")
+ List<FavoritesFunctionalMenuItemJson> menuItems = dataAccessService.executeSQLQuery(sql, FavoritesFunctionalMenuItemJson.class, null);
+ for (FavoritesFunctionalMenuItemJson menuItem : menuItems) {
+ menuItem.restrictedApp = true;
+ }
+
+ sql = "SELECT DISTINCT f.user_id,f.menu_id,m.text,m.url "
+ + " FROM fn_menu_favorites f, fn_menu_functional m, fn_menu_functional_roles mr "
+ + " WHERE f.user_id='" + userId + "' AND f.menu_id = m.menu_id "
+ + " AND f.menu_id = mr.menu_id "
+ + " AND mr.role_id != '" + RESTRICTED_APP_ROLE_ID + "' ";
+ @SuppressWarnings("unchecked")
+ List<FavoritesFunctionalMenuItemJson> menuItems2 = dataAccessService.executeSQLQuery(sql, FavoritesFunctionalMenuItemJson.class, null);
+ for (FavoritesFunctionalMenuItemJson menuItem : menuItems2) {
+ menuItem.restrictedApp = false;
+ menuItems.add(menuItem);
+ }
+
+ return menuItems;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in FunctionalMenuServiceImpl.getFavoriteItems. Details: " + EcompPortalUtils.getStackTrace(e));
+ List<FavoritesFunctionalMenuItemJson> menuItems = new ArrayList<FavoritesFunctionalMenuItemJson>();
+ return menuItems;
+ }
+ }
+
+ public FieldsValidator removeFavoriteItem(Long userId, Long menuId) {
+ boolean result = false;
+ FieldsValidator fieldsValidator = new FieldsValidator();
+
+ Session localSession = null;
+ Transaction transaction = null;
+
+ try {
+
+ FavoritesFunctionalMenuItem menuItemJson = new FavoritesFunctionalMenuItem();
+ menuItemJson.userId = userId;
+ menuItemJson.menuId = menuId;
+
+ localSession = sessionFactory.openSession();
+ transaction = localSession.beginTransaction();
+ localSession.delete(menuItemJson);
+ localSession.flush();
+ transaction.commit();
+ result = true;
+ logger.debug(EELFLoggerDelegate.debugLogger, String.format("After removing favorite for user id: " + userId + "; menu id: " + menuId));
+ } catch (Exception e) {
+ EcompPortalUtils.rollbackTransaction(transaction,"removeFavoriteItem rollback, exception = " + e);
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ } finally {
+ EcompPortalUtils.closeLocalSession(localSession, "removeFavoriteItem");
+ }
+
+ if(result) {
+ }
+ else {
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+
+ return fieldsValidator;
+ }
+
+ @Override
+ public void assignHelpURLs(List<FunctionalMenuItem> menuItems) {
+ try {
+ String user_guide_link = SystemProperties.getProperty(EPSystemProperties.USER_GUIDE_URL);
+
+ for(FunctionalMenuItem menuItem: menuItems){
+ if(menuItem.text.equalsIgnoreCase("Contact Us")){
+ menuItem.setUrl("contactUs");
+ //menuItem.setRestrictedApp(true);
+ }
+ if(menuItem.text.equalsIgnoreCase("Get Access")) {
+ menuItem.setUrl("getAccess");
+ }
+ if(menuItem.text.equalsIgnoreCase("User Guide")) {
+ menuItem.setUrl(user_guide_link);
+ menuItem.setRestrictedApp(true);
+ }
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "assignHelpURLs process failed. Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/GetAccessService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/GetAccessService.java
new file mode 100644
index 00000000..c4ddc75e
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/GetAccessService.java
@@ -0,0 +1,32 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.List;
+
+import org.openecomp.portalapp.portal.domain.GetAccessResult;
+
+public interface GetAccessService {
+ /**
+ * @return One entry per application function AND role; i.e., each application
+ * appears many times.
+ */
+ List<GetAccessResult> getAppAccessList();
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/GetAccessServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/GetAccessServiceImpl.java
new file mode 100644
index 00000000..a4e36337
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/GetAccessServiceImpl.java
@@ -0,0 +1,50 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.List;
+
+import org.openecomp.portalapp.portal.domain.GetAccessResult;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalsdk.core.service.DataAccessService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service("getAccessService")
+@Transactional
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class GetAccessServiceImpl implements GetAccessService{
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<GetAccessResult> getAppAccessList() {
+ List<GetAccessResult> appAccessList = (List<GetAccessResult>) dataAccessService
+ .executeNamedQuery("getAppAccessFunctionRole", null, null);
+ return appAccessList;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/ManifestService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/ManifestService.java
new file mode 100644
index 00000000..263811dc
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/ManifestService.java
@@ -0,0 +1,34 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.io.IOException;
+import java.util.jar.Attributes;
+
+public interface ManifestService {
+ /**
+ * Gets the content of the webapp manifest file META-INF/MANIFEST.MF.
+ *
+ * @return Attributes object with key-value pairs from the manifest
+ * @throws IOException
+ */
+ public Attributes getWebappManifest() throws IOException;
+}
+
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/ManifestServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/ManifestServiceImpl.java
new file mode 100644
index 00000000..fe2895d8
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/ManifestServiceImpl.java
@@ -0,0 +1,65 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import javax.servlet.ServletContext;
+
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+
+
+
+@Service("manifestService")
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class ManifestServiceImpl implements ManifestService {
+
+
+ @Autowired
+ ServletContext context;
+
+
+ // * (non-Javadoc)
+ // *
+
+ public Attributes getWebappManifest() throws IOException {
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ManifestServiceImpl.class);
+ // Path to resource on classpath
+ final String MANIFEST_RESOURCE_PATH = "/META-INF/MANIFEST.MF";
+ // Manifest is formatted as Java-style properties
+ try {
+ InputStream inputStream = context.getResourceAsStream(MANIFEST_RESOURCE_PATH);
+ Manifest manifest = new Manifest(inputStream);
+ inputStream.close();
+ return manifest.getMainAttributes();
+ } catch (IOException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "getWebappManifest: failed to read/find manifest");
+ throw e;
+ }
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/PersUserAppService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/PersUserAppService.java
new file mode 100644
index 00000000..8096bc3c
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/PersUserAppService.java
@@ -0,0 +1,24 @@
+package org.openecomp.portalapp.portal.service;
+
+import org.openecomp.portalapp.portal.domain.EPApp;
+import org.openecomp.portalapp.portal.domain.EPUser;
+
+public interface PersUserAppService {
+
+
+ /**
+ * Sets the appropriate code in the user personalization table to indicate
+ * the application is (de)selected and/or pending.
+ *
+ * @param user
+ * EP User
+ * @param app
+ * EP Application
+ * @param select
+ * True or false
+ * @param select
+ * True or false
+ */
+ void setPersUserAppValue(EPUser user, EPApp app, boolean select, boolean pending);
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/PersUserAppServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/PersUserAppServiceImpl.java
new file mode 100644
index 00000000..5a67dee7
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/PersUserAppServiceImpl.java
@@ -0,0 +1,117 @@
+package org.openecomp.portalapp.portal.service;
+
+
+import java.util.List;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.service.DataAccessService;
+import org.openecomp.portalapp.portal.domain.EPApp;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.domain.EPUserApp;
+import org.openecomp.portalapp.portal.domain.PersUserAppSelection;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+
+@Service("persUserAppService")
+@Transactional
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class PersUserAppServiceImpl implements PersUserAppService {
+
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PersUserAppServiceImpl.class);
+
+ @Autowired
+ private DataAccessService dataAccessService;
+ @Autowired
+ private AdminRolesService adminRolesService;
+ @Autowired
+ private UserRolesService userRolesService;
+
+
+ @Override
+ public void setPersUserAppValue(EPUser user, EPApp app, boolean select, boolean pending) {
+ if (user == null || app == null)
+ throw new IllegalArgumentException("setPersUserAppValue: Null values");
+
+ // Find the record for this user-app combo, if any
+ String filter = " where user_id = " + Long.toString(user.getId()) + " and app_id = "
+ + Long.toString(app.getId());
+ @SuppressWarnings("unchecked")
+ List<PersUserAppSelection> persList = dataAccessService.getList(PersUserAppSelection.class, filter, null, null);
+
+ // Key constraint limits to 1 row
+ PersUserAppSelection persRow = null;
+ if (persList.size() == 1)
+ persRow = persList.get(0);
+ else
+ persRow = new PersUserAppSelection(null, user.getId(), app.getId(), null);
+
+ if (app.getOpen()) {
+ // Pending status is not meaningful for open apps.
+ if (pending)
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "setPersUserAppValue: invalid request, ignoring set-pending for open app");
+
+ // Open apps have same behavior for regular and admin users
+ if (select) {
+ // Selection of an open app requires a record
+ persRow.setStatusCode("S"); // show
+ dataAccessService.saveDomainObject(persRow, null);
+ } else {
+ // De-selection of an open app requires no record
+ if (persRow.getId() != null)
+ dataAccessService.deleteDomainObject(persRow, null);
+ }
+ } else {
+ // Non-open app.
+
+ // Pending overrides select.
+ if (pending) {
+ persRow.setStatusCode("P");
+ dataAccessService.saveDomainObject(persRow, null);
+ } else {
+ // Behavior depends on Portal (super) admin status, bcos an
+ // admin can force an app onto the dashboard.
+ boolean isPortalAdmin = adminRolesService.isSuperAdmin(user);
+ boolean adminUserHasAppRole = false;
+ if (isPortalAdmin) {
+ List<EPUserApp> roles = userRolesService.getCachedAppRolesForUser(app.getId(), user.getId());
+ adminUserHasAppRole = (roles.size() > 0);
+ logger.debug(EELFLoggerDelegate.debugLogger, "setPersUserAppValue: app {}, admin user {}, role count {}",
+ app.getId(), user.getId(), roles.size());
+ }
+
+ if (select) {
+ if (isPortalAdmin && !adminUserHasAppRole) {
+ // The special case: portal admin, no role
+ persRow.setStatusCode("S"); // show
+ dataAccessService.saveDomainObject(persRow, null);
+ } else {
+ // User has role-based access to the app.
+ // Showing an accessible app requires no record.
+ if (persRow.getId() != null)
+ dataAccessService.deleteDomainObject(persRow, null);
+ }
+ } // select
+ else {
+ if (isPortalAdmin && !adminUserHasAppRole) {
+ // The special case: portal admin, no role
+ if (persRow.getId() != null)
+ dataAccessService.deleteDomainObject(persRow, null);
+ } else {
+ // User has role-based access to the app.
+ // Hiding an accessible app requires a record
+ persRow.setStatusCode("H"); // hide
+ dataAccessService.saveDomainObject(persRow, null);
+ }
+ } // deselect
+ }
+ }
+ }
+
+} \ No newline at end of file
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminService.java
new file mode 100644
index 00000000..5cf52e51
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminService.java
@@ -0,0 +1,31 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.List;
+
+import org.openecomp.portalapp.portal.transport.FieldsValidator;
+import org.openecomp.portalapp.portal.transport.PortalAdmin;
+
+public interface PortalAdminService {
+ List<PortalAdmin> getPortalAdmins ();
+ FieldsValidator createPortalAdmin(String orgUserId);
+ FieldsValidator deletePortalAdmin(Long userId);
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminServiceImpl.java
new file mode 100644
index 00000000..d8e427fd
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminServiceImpl.java
@@ -0,0 +1,179 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.List;
+
+import javax.annotation.PostConstruct;
+import javax.servlet.http.HttpServletResponse;
+
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.Transaction;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.transport.FieldsValidator;
+import org.openecomp.portalapp.portal.transport.PortalAdmin;
+import org.openecomp.portalapp.portal.transport.PortalAdminUserRole;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.service.DataAccessService;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+
+@Service("portalAdminService")
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class PortalAdminServiceImpl implements PortalAdminService {
+
+ private String SYS_ADMIN_ROLE_ID = "1";
+ private String ECOMP_APP_ID = "1";
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalAdminServiceImpl.class);
+
+ @Autowired
+ private SessionFactory sessionFactory;
+ @Autowired
+ private DataAccessService dataAccessService;
+ @Autowired
+ SearchService searchService;
+
+ @PostConstruct
+ private void init() {
+ SYS_ADMIN_ROLE_ID = SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID);
+ ECOMP_APP_ID = SystemProperties.getProperty(EPSystemProperties.ECOMP_APP_ID);
+ }
+
+ public List<PortalAdmin> getPortalAdmins() {
+ try {
+ String sql = "SELECT u.user_id, u.first_name, u.last_name, u.login_id " +
+ " FROM fn_user u, fn_user_role ur " +
+ " WHERE u.user_id = ur.user_id " +
+ " AND ur.role_id=" + SYS_ADMIN_ROLE_ID;
+ logQuery(sql);
+
+ @SuppressWarnings("unchecked")
+ List<PortalAdmin> portalAdmins = dataAccessService.executeSQLQuery(sql, PortalAdmin.class, null);
+ logger.debug(EELFLoggerDelegate.debugLogger, portalAdmins.toString());
+ return portalAdmins;
+
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing getPortalAdmins operation, Details: " + EcompPortalUtils.getStackTrace(e));
+ return null;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public FieldsValidator createPortalAdmin(String orgUserId) {
+ FieldsValidator fieldsValidator = new FieldsValidator();
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: createPortalAdmin: test 1");
+ boolean result = false;
+ EPUser user = null;
+ boolean createNewUser = false;
+ List<EPUser> localUserList = dataAccessService.getList(EPUser.class, " where org_user_id='" + orgUserId + "'",
+ null, null);
+ if (localUserList.size() > 0) {
+ user = localUserList.get(0);
+ } else {
+ createNewUser = true;
+ }
+ if (user != null || createNewUser) {
+ Session localSession = null;
+ Transaction transaction = null;
+ try {
+ localSession = sessionFactory.openSession();
+
+ transaction = localSession.beginTransaction();
+ if (createNewUser) {
+ user = this.searchService.searchUserByUserId(orgUserId);
+ if (user != null) {
+ // insert the user with active true in order to
+ // pass login phase.
+ user.setActive(true);
+ localSession.save(EPUser.class.getName(), user);
+ }
+ }
+ if (user != null) {
+ Long userId = user.getId();
+ PortalAdminUserRole userRole = new PortalAdminUserRole();
+ userRole.userId = userId;
+ userRole.roleId = Long.valueOf(SYS_ADMIN_ROLE_ID);
+ userRole.appId = Long.valueOf(ECOMP_APP_ID);
+
+ localSession.save(PortalAdminUserRole.class.getName(), userRole);
+ }
+// logger.debug(EELFLoggerDelegate.debugLogger, "after saving menu object, new id: " + userId);
+
+ transaction.commit();
+ result = true;
+ } catch (Exception e) {
+ EcompPortalUtils.rollbackTransaction(transaction,
+ "createPortalAdmin rollback, exception = " + e);
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ } finally {
+ EcompPortalUtils.closeLocalSession(localSession, "createPortalAdmin");
+ }
+ if (!result) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: createPortalAdmin: no result. setting httpStatusCode to "
+ + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+ logger.error(EELFLoggerDelegate.errorLogger, "PortalAdminServiceImpl.createPortalAdmin: bad request");
+ }
+ return fieldsValidator;
+ }
+
+ public FieldsValidator deletePortalAdmin(Long userId) {
+ FieldsValidator fieldsValidator = new FieldsValidator();
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: deletePortalAdmin: test 1");
+ boolean result = false;
+ Session localSession = null;
+ Transaction transaction = null;
+
+ try {
+ localSession = sessionFactory.openSession();
+ transaction = localSession.beginTransaction();
+ dataAccessService.deleteDomainObjects(PortalAdminUserRole.class, "user_id='" + userId + "' AND role_id='" + SYS_ADMIN_ROLE_ID + "'", null);
+ transaction.commit();
+ result = true;
+ } catch (Exception e) {
+ EcompPortalUtils.rollbackTransaction(transaction,
+ "deletePortalAdmin rollback, exception = " + e);
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ } finally {
+ EcompPortalUtils.closeLocalSession(localSession, "deletePortalAdmin");
+ }
+ if (result) {
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "LR: deletePortalAdmin: no result. setting httpStatusCode to "
+ + HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+ return fieldsValidator;
+ }
+
+ private void logQuery(String sql) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/SearchService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/SearchService.java
new file mode 100644
index 00000000..5254e20b
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/SearchService.java
@@ -0,0 +1,38 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.List;
+
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.transport.UserWithNameSurnameTitle;
+
+public interface SearchService {
+
+
+ public String searchUsersInFnTable(String searchString);
+
+ public List<UserWithNameSurnameTitle> searchUsersByName(EPUser attrUser);
+
+ public List<UserWithNameSurnameTitle> searchUsersByUserId(EPUser attrUser);
+
+ public EPUser searchUserByUserId(String orgUserId);
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/SearchServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/SearchServiceImpl.java
new file mode 100644
index 00000000..020b7496
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/SearchServiceImpl.java
@@ -0,0 +1,188 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.transport.UserWithNameSurnameTitle;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Service("searchService")
+@Transactional
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class SearchServiceImpl implements SearchService {
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SearchServiceImpl.class);
+
+ // TODO: the values below should be defined in other place
+ private static final int maxSizeOfSearchResult = 100;
+
+ @Autowired
+ UserService userService;
+
+
+ @Override
+ public String searchUsersInFnTable(String searchString) {
+ String orgUserId = null;
+ List<String> tokens = EcompPortalUtils.parsingByRegularExpression(searchString, " ");
+ for (int i = 0; i < tokens.size(); i++) { // find userid if possible and remove it from tokens
+ if (tokens.get(i).matches(".*\\d+.*")) {
+ orgUserId = tokens.get(i);
+ tokens.remove(i);
+ }
+ }
+ while (tokens.size() > 2) { // we use no more then first 2 tokens (userId is removed, see above)
+ tokens.remove(tokens.size() - 1);
+ }
+ EPUser attrUser = new EPUser();
+ attrUser.setOrgUserId(orgUserId);
+ List<UserWithNameSurnameTitle> resultOfSearch = new ArrayList<UserWithNameSurnameTitle>(), resultOfAdditionalSearch = null;
+ if (tokens.size() == 2) {
+ attrUser.setFirstName(tokens.get(0));
+ attrUser.setLastName(tokens.get(1));
+ resultOfSearch = this.searchUsersByName(attrUser);
+ resultOfSearch = this.removeWrongFirstNames(resultOfSearch, tokens.get(0));
+ resultOfSearch = this.removeWrongLastNames(resultOfSearch, tokens.get(1));
+ if (resultOfSearch.size() < maxSizeOfSearchResult) {
+ attrUser.setFirstName(tokens.get(1));
+ attrUser.setLastName(tokens.get(0));
+ resultOfAdditionalSearch = this.searchUsersByName(attrUser);
+ resultOfAdditionalSearch = this.removeWrongFirstNames(resultOfAdditionalSearch, tokens.get(1));
+ resultOfAdditionalSearch = this.removeWrongLastNames(resultOfAdditionalSearch, tokens.get(0));
+ }
+ } else if (tokens.size() == 1) {
+ attrUser.setFirstName(tokens.get(0));
+ resultOfSearch = this.searchUsersByName(attrUser);
+ resultOfSearch = this.removeWrongFirstNames(resultOfSearch, tokens.get(0));
+ if (resultOfSearch.size() < maxSizeOfSearchResult) {
+ attrUser.setFirstName(null);
+ attrUser.setLastName(tokens.get(0));
+ resultOfAdditionalSearch = this.searchUsersByName(attrUser);
+ resultOfAdditionalSearch = this.removeWrongLastNames(resultOfAdditionalSearch, tokens.get(0));
+ }
+ } else if (orgUserId != null) {
+ resultOfSearch = this.searchUsersByUserId(attrUser);
+ }
+ if (resultOfAdditionalSearch != null) {
+ resultOfSearch.addAll(resultOfAdditionalSearch);
+ }
+ resultOfSearch = this.cutSearchResultToMaximumSize(resultOfSearch);
+ ObjectMapper mapper = new ObjectMapper();
+ String result = "[]";
+ try {
+ result = mapper.writeValueAsString(resultOfSearch);
+ } catch (JsonProcessingException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "searchUsersInPhoneBook Exception = " + EcompPortalUtils.getStackTrace(e));
+ }
+ return result;
+ }
+
+
+ @SuppressWarnings("rawtypes")
+ public List<UserWithNameSurnameTitle> searchUsersByUserId(EPUser attrUser) {
+ List<UserWithNameSurnameTitle> foundUsers = new ArrayList<UserWithNameSurnameTitle>();
+ try {
+ List searchResult = this.userService.getUserByUserId(attrUser.getOrgUserId());
+ for (Object obj : searchResult) {
+ EPUser user = (EPUser) obj;
+ UserWithNameSurnameTitle foundUser = new UserWithNameSurnameTitle(user.getOrgUserId(), user.getFirstName(), user.getLastName(), user.getJobTitle());
+ foundUsers.add(foundUser);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "searchInPhoneBookWithToken Exception = " + EcompPortalUtils.getStackTrace(e));
+ }
+ return foundUsers;
+ }
+
+ @SuppressWarnings("rawtypes")
+ public List<UserWithNameSurnameTitle> searchUsersByName(EPUser attrUser) {
+ List<UserWithNameSurnameTitle> foundUsers = new ArrayList<UserWithNameSurnameTitle>();
+ try {
+ List searchResult = this.userService.getUserByFirstLastName(attrUser.getFirstName(),attrUser.getLastName());
+ for (Object obj : searchResult) {
+ EPUser user = (EPUser) obj;
+ UserWithNameSurnameTitle foundUser = new UserWithNameSurnameTitle(user.getOrgUserId(), user.getFirstName(), user.getLastName(), user.getJobTitle());
+ foundUsers.add(foundUser);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "searchInPhoneBookWithToken Exception = " + EcompPortalUtils.getStackTrace(e));
+ }
+ return foundUsers;
+ }
+
+ private List<UserWithNameSurnameTitle> removeWrongFirstNames(List<UserWithNameSurnameTitle> resultOfSearch, String firstName) {
+ firstName = firstName.toUpperCase();
+ for (int i = resultOfSearch.size() - 1; i >= 0; i--) {
+ UserWithNameSurnameTitle user = resultOfSearch.get(i);
+ if ((user.firstName == null) || !user.firstName.toUpperCase().startsWith(firstName)) {
+ resultOfSearch.remove(i);
+ }
+ }
+ return resultOfSearch;
+ }
+
+ private List<UserWithNameSurnameTitle> removeWrongLastNames(List<UserWithNameSurnameTitle> resultOfSearch, String lastName) {
+ lastName = lastName.toUpperCase();
+ for (int i = resultOfSearch.size() - 1; i >= 0; i--) {
+ UserWithNameSurnameTitle user = resultOfSearch.get(i);
+ if ((user.lastName == null) || !user.lastName.toUpperCase().startsWith(lastName)) {
+ resultOfSearch.remove(i);
+ }
+ }
+ return resultOfSearch;
+ }
+
+ private List<UserWithNameSurnameTitle> cutSearchResultToMaximumSize(List<UserWithNameSurnameTitle> resultOfSearch) {
+ for (int i = resultOfSearch.size() - 1; i >= maxSizeOfSearchResult; i--) {
+ resultOfSearch.remove(i);
+ }
+ return resultOfSearch;
+ }
+
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public EPUser searchUserByUserId(String orgUserId) {
+ List<EPUser> foundUsers = new ArrayList<EPUser>();
+ try {
+ List searchResult = this.userService.getUserByUserId(orgUserId);
+ for (Object obj : searchResult) {
+ EPUser user = (EPUser) obj;
+ foundUsers.add(user);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "searchInPhoneBookWithToken Exception = " + EcompPortalUtils.getStackTrace(e));
+ }
+ return foundUsers.get(0);
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/SharedContextService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/SharedContextService.java
new file mode 100644
index 00000000..647c9d1b
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/SharedContextService.java
@@ -0,0 +1,98 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.List;
+
+import org.openecomp.portalapp.portal.domain.SharedContext;
+
+/**
+ * Defines the methods exposed by the service that manages shared context
+ * objects in the database via Hibernate.
+ */
+public interface SharedContextService {
+
+ /**
+ * Gets all shared context objects for the specified context ID.
+ *
+ * @return List of SharedContext objects
+ */
+ List<SharedContext> getSharedContexts(String contextId);
+
+ /**
+ * Gets the shared context with the specified context ID and key.
+ *
+ * @param contextId
+ * Context ID; usually a session ID
+ * @param key
+ * Key for the key-value pair
+ * @return Value found in the database, null if any parameter is null or no
+ * shared context exists with that context ID - key pair.
+ */
+ SharedContext getSharedContext(String contextId, String key);
+
+ /**
+ * Creates a new shared context in the database with the specified context
+ * ID, key and value.
+ *
+ * @param context
+ * SharedContext object to save.
+ * @param key
+ * Key for the key-value pair.
+ * @param value
+ * Value for the key-value pair.
+ */
+ void addSharedContext(String contextId, String key, String value);
+
+ /**
+ * Saves the specified shared context to the database.
+ *
+ * @param context
+ * SharedContext object to save.
+ */
+ void saveSharedContext(SharedContext context);
+
+ /**
+ * Deletes the specified shared context from the database.
+ *
+ * @param context
+ * SharedContext object to delete.
+ */
+ void deleteSharedContext(SharedContext context);
+
+ /**
+ * Deletes all shared contexts with the specified context ID.
+ *
+ * @param contextId
+ * Context ID; usually a session ID
+ * @return number of shared-context objects deleted
+ */
+ int deleteSharedContexts(String contextId);
+
+ /**
+ * Deletes all shared contexts that are older (judged from creation
+ * timestamp) than the specified value.
+ *
+ * @param ageInSeconds
+ * Expiration threshold in seconds
+ */
+ void expireSharedContexts(int ageInSeconds);
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/SharedContextServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/SharedContextServiceImpl.java
new file mode 100644
index 00000000..02e6f8bf
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/SharedContextServiceImpl.java
@@ -0,0 +1,173 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import org.hibernate.criterion.Criterion;
+import org.hibernate.criterion.Restrictions;
+import org.openecomp.portalapp.portal.domain.SharedContext;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.service.DataAccessService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+/**
+ * Implementation of the shared-context service that talks to the database.
+ */
+@Service("sharedContextService")
+@Transactional
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class SharedContextServiceImpl implements SharedContextService {
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextServiceImpl.class);
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.openecomp.portalsdk.core.service.SharedContextService#getSharedContexts()
+ */
+ @Override
+ @SuppressWarnings("unchecked")
+ public List<SharedContext> getSharedContexts(String contextId) {
+ List<Criterion> restrictionsList = new ArrayList<Criterion>();
+ Criterion contextIdCrit = Restrictions.eq("context_id", contextId);
+ restrictionsList.add(contextIdCrit);
+ List<SharedContext> contexts = (List<SharedContext>) getDataAccessService().getList(SharedContext.class, null,
+ restrictionsList, null);
+
+ return contexts;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.openecomp.portalsdk.core.service.SharedContextService#getSharedContext(java.
+ * lang.String, java.lang.String)
+ */
+ @Override
+ public SharedContext getSharedContext(String contextId, String key) {
+ SharedContext context = null;
+ List<Criterion> restrictionsList = new ArrayList<Criterion>();
+ Criterion contextIdCrit = Restrictions.eq("context_id", contextId);
+ Criterion keyCrit = Restrictions.eq("ckey", key);
+ restrictionsList.add(contextIdCrit);
+ restrictionsList.add(keyCrit);
+ @SuppressWarnings("unchecked")
+ List<SharedContext> contexts = (List<SharedContext>) getDataAccessService().getList(SharedContext.class, null,
+ restrictionsList, null);
+ if (contexts != null && contexts.size() == 1)
+ context = contexts.get(0);
+
+ return context;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.openecomp.portalapp.portal.service.SharedContextService#
+ * addSharedContext(java.lang.String, java.lang.String, java.lang.String)
+ */
+ @Override
+ public void addSharedContext(String contextId, String key, String value) {
+ SharedContext context = new SharedContext(contextId, key, value);
+ saveSharedContext(context);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.openecomp.portalsdk.core.service.SharedContextService#saveSharedContext
+ */
+ @Override
+ public void saveSharedContext(SharedContext context) {
+ getDataAccessService().saveDomainObject(context, null);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.openecomp.portalsdk.core.service.SharedContextService#deleteSharedContext(org.
+ * openecomp.portalapp.portal.domain.SharedContext)
+ */
+ @Override
+ public void deleteSharedContext(SharedContext context) {
+ getDataAccessService().deleteDomainObject(context, null);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.openecomp.portalapp.portal.service.SharedContextService#
+ * deleteSharedContexts(java.lang.String)
+ */
+ @Override
+ public int deleteSharedContexts(String contextId) {
+ // Uses an inefficient method to avoid a where clause
+ // that could be used to mount a SQL injection attack.
+ List<SharedContext> contexts = getSharedContexts(contextId);
+ if (contexts == null)
+ return 0;
+
+ for (SharedContext sc : contexts)
+ deleteSharedContext(sc);
+
+ return contexts.size();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.openecomp.portalapp.portal.service.SharedContextService#
+ * expireSharedContexts(int)
+ */
+ @Override
+ public void expireSharedContexts(int ageInSeconds) {
+ // Specific to the MySQL database.
+ //final String whereClause = " where create_time < ADDDATE(NOW(), INTERVAL - " + ageInSeconds + " SECOND)";
+ final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ Date expiredDateTime = new Date(System.currentTimeMillis() - ageInSeconds*1000);
+ final String whereClause = " create_time < '" + dateFormat.format(expiredDateTime) + "'";
+ getDataAccessService().deleteDomainObjects(SharedContext.class, whereClause, null);
+ }
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/UserRolesService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/UserRolesService.java
new file mode 100644
index 00000000..d0964a88
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/UserRolesService.java
@@ -0,0 +1,58 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.List;
+
+import org.apache.cxf.transport.http.HTTPException;
+import org.openecomp.portalapp.portal.domain.EPRole;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.domain.EPUserApp;
+import org.openecomp.portalapp.portal.transport.AppWithRolesForUser;
+import org.openecomp.portalapp.portal.transport.RoleInAppForUser;
+import org.openecomp.portalapp.portal.transport.UserApplicationRoles;
+
+public interface UserRolesService {
+
+ public List<RoleInAppForUser> getAppRolesForUser(Long appId, String userId);
+
+ public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser);
+
+ public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException;
+
+ public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException;
+
+
+ /**
+ * Gets entries from the local fn_user_role table for the specified user and
+ * app.
+ *
+ * @param appId
+ * ID of row in fn_app
+ * @param userid
+ * ID of row in fn_user
+ * @return List of EPRole; empty if none found.
+ */
+ public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId);
+
+ public String updateRemoteUserProfile(String orgUserId, Long appId);
+
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/UserRolesServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/UserRolesServiceImpl.java
new file mode 100644
index 00000000..340c2d1a
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/UserRolesServiceImpl.java
@@ -0,0 +1,656 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+
+import javax.annotation.PostConstruct;
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.cxf.transport.http.HTTPException;
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.Transaction;
+import org.openecomp.portalapp.portal.domain.EPApp;
+import org.openecomp.portalapp.portal.domain.EPRole;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.domain.EPUserApp;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
+import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
+import org.openecomp.portalapp.portal.transport.AppWithRolesForUser;
+import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
+import org.openecomp.portalapp.portal.transport.FunctionalMenuRole;
+import org.openecomp.portalapp.portal.transport.RemoteUserWithRoles;
+import org.openecomp.portalapp.portal.transport.RoleInAppForUser;
+import org.openecomp.portalapp.portal.transport.RolesInAppForUser;
+import org.openecomp.portalapp.portal.transport.UserApplicationRoles;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.restful.domain.EcompRole;
+import org.openecomp.portalsdk.core.service.DataAccessService;
+import org.openecomp.portalsdk.core.service.UserProfileService;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Service("userRolesService")
+@Transactional
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class UserRolesServiceImpl implements UserRolesService {
+ private static Long ACCOUNT_ADMIN_ROLE_ID = 999L;
+
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesServiceImpl.class);
+
+ @Autowired
+ private SessionFactory sessionFactory;
+ @Autowired
+ private DataAccessService dataAccessService;
+ @Autowired
+ SearchService searchService;
+ @Autowired
+ EPAppService appsService;
+ @Autowired
+ EPLdapService ldapService;
+ @Autowired
+ ApplicationsRestClientService applicationsRestClientService;
+ @Autowired
+ EPRoleService epRoleService;
+ @Autowired
+ UserProfileService userProfileService;
+
+ @PostConstruct
+ private void init() {
+ try {
+ ACCOUNT_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPSystemProperties.ACCOUNT_ADMIN_ROLE_ID));
+ } catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+ }
+
+ private static HashMap<Long, EcompRole> hashMapFromEcompRoles(EcompRole[] ecompRoles) {
+ HashMap<Long, EcompRole> result = new HashMap<Long, EcompRole>();
+ if (ecompRoles!=null) {
+ for (int i = 0; i < ecompRoles.length; i++) {
+ if (ecompRoles[i].getId() != null) {
+ result.put(ecompRoles[i].getId(), ecompRoles[i]);
+ }
+ }
+ }
+ return result;
+ }
+
+ private void createLocalUserIfNecessary(String orgUserId) {
+ if (StringUtils.isEmpty(orgUserId)) {
+ logger.error(EELFLoggerDelegate.errorLogger, "createLocalUserIfNecessary : empty orgUserId!");
+ return;
+ }
+ Session localSession = null;
+ Transaction transaction = null;
+ try {
+ localSession = sessionFactory.openSession();
+ transaction = localSession.beginTransaction();
+ @SuppressWarnings("unchecked")
+ List<EPUser> userList = localSession.createQuery("from " + EPUser.class.getName() + " where org_user_id='" + orgUserId + "'").list();
+ if (userList.size() == 0) {
+ EPUser client = searchService.searchUserByUserId(orgUserId);
+ if (client == null) {
+ String msg = "cannot create user " + orgUserId + ", because he cannot be found in phonebook";
+ logger.error(EELFLoggerDelegate.errorLogger, msg);
+ } else {
+ client.setLoginId(orgUserId);
+ client.setActive(true);
+ localSession.save(client);
+ }
+ }
+ transaction.commit();
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ EcompPortalUtils.rollbackTransaction(transaction, "searchOrCreateUser rollback, exception = " + e);
+ } finally {
+ EcompPortalUtils.closeLocalSession(localSession, "searchOrCreateUser");
+ }
+ }
+
+ private static void syncUserRoles(SessionFactory sessionFactory, String orgUserId, Long appId, EcompRole[] userAppRoles) throws Exception {
+ HashMap<Long, EcompRole> newUserAppRolesMap = hashMapFromEcompRoles(userAppRoles);
+ boolean result = false;
+ Session localSession = null;
+ Transaction transaction = null;
+
+ try {
+ localSession = sessionFactory.openSession();
+ transaction = localSession.beginTransaction();
+ @SuppressWarnings("unchecked")
+ List<EPUser> userList = localSession.createQuery("from " + EPUser.class.getName() + " where org_user_id='" + orgUserId + "'").list();
+ if (userList.size() > 0) {
+ EPUser client = userList.get(0);
+ @SuppressWarnings("unchecked")
+ List<EPUserApp> userRoles = localSession
+ .createQuery("from " + EPUserApp.class.getName() + " where app.id=" + appId + " and userId=" + client.getId()).list();
+ for (EPUserApp userRole : userRoles) {
+ if (! userRole.getRoleId().equals(ACCOUNT_ADMIN_ROLE_ID)) {
+
+ Long userAppRoleId = userRole.getAppRoleId();
+ if (!newUserAppRolesMap.containsKey(userAppRoleId)) {
+ localSession.delete(userRole);
+ } else {
+ newUserAppRolesMap.remove(userAppRoleId);
+ }
+ }
+ }
+ Collection<EcompRole> newRolesToAdd = newUserAppRolesMap.values();
+ if (newRolesToAdd.size() > 0) {
+ EPApp app = (EPApp) localSession.get(EPApp.class, appId);
+ @SuppressWarnings("unchecked")
+ List<EPRole> roles = localSession.createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
+ HashMap<Long, EPRole> rolesMap = new HashMap<Long, EPRole>();
+ for (EPRole role : roles) {
+ rolesMap.put(role.getAppRoleId(), role);
+ }
+ for (EcompRole userRole : newRolesToAdd) {
+ EPUserApp userApp = new EPUserApp();
+ userApp.setUserId(client.getId());
+ userApp.setApp(app);
+ userApp.setRole(rolesMap.get(userRole.getId()));
+ localSession.save(userApp);
+ }
+ }
+ }
+ transaction.commit();
+ result = true;
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ EcompPortalUtils.rollbackTransaction(transaction, "Exception occurred in syncUserRoles, Details: " + EcompPortalUtils.getStackTrace(e));
+ } finally {
+ localSession.close();
+ if (!result) {
+ throw new Exception("Exception occurred in syncUserRoles while closing database session for app: '" + appId + "'.");
+ }
+ }
+ }
+
+ // Called when getting the list of roles for the user
+ private List<RoleInAppForUser> constructRolesInAppForUserGet(EcompRole[] appRoles, EcompRole[] userAppRoles) {
+ List<RoleInAppForUser> rolesInAppForUser = new ArrayList<RoleInAppForUser>();
+
+ Set<Long> userAppRolesMap = new HashSet<Long>();
+ if (userAppRoles!=null) {
+ for (EcompRole ecompRole : userAppRoles) {
+ userAppRolesMap.add(ecompRole.getId());
+ }
+ } else {
+ String message = String.format("UserRolesServiceImpl.constructRolesInAppForUserGet has received userAppRoles list empty.");
+ logger.info(EELFLoggerDelegate.errorLogger, message);
+ }
+
+ if (appRoles!=null) {
+ for (EcompRole ecompRole : appRoles) {
+ RoleInAppForUser roleForUser = new RoleInAppForUser(ecompRole.getId(), ecompRole.getName());
+ roleForUser.isApplied = userAppRolesMap.contains(ecompRole.getId());
+ rolesInAppForUser.add(roleForUser);
+ }
+ } else {
+ String message = String.format("UserRolesServiceImpl.constructRolesInAppForUser has received appRoles list empty.");
+ logger.info(EELFLoggerDelegate.errorLogger, message);
+ }
+ return rolesInAppForUser;
+ }
+ public List<RoleInAppForUser> getAppRolesForUser(Long appId, String orgUserId) {
+ List<RoleInAppForUser> rolesInAppForUser = null;
+ try {
+ EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
+
+ // Test this error case, for generating an internal Ecomp Portal error
+// EcompRole[] appRoles = null;
+ // If there is an exception in the rest client api, then null will be returned.
+ if (appRoles != null) {
+ syncAppRoles(sessionFactory, appId, appRoles);
+ EcompRole[] userAppRoles;
+ try {
+ userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId, String.format("/user/%s/roles", orgUserId));
+ if (userAppRoles == null) {
+ if (EcompPortalUtils.getExternalAppResponseCode() == 400) {
+ EcompPortalUtils.setExternalAppResponseCode(200);
+ logger.error(EELFLoggerDelegate.errorLogger, "400 returned from /user/{userid}/roles, assuming user doesn't exist, app is framework SDK based, and things are ok. Overriding to 200 until framework SDK returns a useful response.");
+ logger.debug(EELFLoggerDelegate.debugLogger, "400 returned from /user/{userid}/roles, assuming user doesn't exist, app is framework SDK based, and things are ok. Overriding to 200 until framework SDK returns a useful response.");
+ }
+ }
+ // If the remote application isn't down we MUST to sync user roles here in case we have this user here!
+ syncUserRoles(sessionFactory, orgUserId, appId, userAppRoles);
+ } catch (Exception e) {
+ // TODO: we may need to check if user exists, maybe remote app is down.
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ logger.error(EELFLoggerDelegate.errorLogger, "LR: user " + orgUserId + " does not exist in remote application: " + appId + ".");
+ userAppRoles = new EcompRole[0];
+ }
+ rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles);
+ // Test this error case, for generating an external app error
+// EcompPortalUtils.setResponseCode(404);
+ }
+ } catch (Exception e) {
+ String message = String.format("Received an exception while performing getAppRolesForUser for the User %s, and for the AppId %s, Details: %s",
+ orgUserId, Long.toString(appId), EcompPortalUtils.getStackTrace(e));
+ logger.error(EELFLoggerDelegate.errorLogger, message);
+ }
+ return rolesInAppForUser;
+
+ }
+
+ // copies of methods in GetAppsWithUserRoleState
+ private void syncAppRoles(SessionFactory sessionFactory, Long appId, EcompRole[] appRoles) throws Exception {
+ logger.debug(EELFLoggerDelegate.debugLogger, "entering syncAppRoles for appId: "+appId);
+ HashMap<Long, EcompRole> newRolesMap = hashMapFromEcompRoles(appRoles);
+ boolean result = false;
+ Session localSession = null;
+ Transaction transaction = null;
+
+ try {
+ localSession = sessionFactory.openSession();
+ transaction = localSession.beginTransaction();
+ // Attention! All roles from remote application supposed to be active!
+ @SuppressWarnings("unchecked")
+ List<EPRole> currentAppRoles = localSession.createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list();
+ List<EPRole> obsoleteRoles = new ArrayList<EPRole>();
+ for (int i = 0; i < currentAppRoles.size(); i++) {
+ EPRole oldAppRole = currentAppRoles.get(i);
+ if (oldAppRole.getAppRoleId() != null) {
+ EcompRole role = null;
+ role = newRolesMap.get(oldAppRole.getAppRoleId());
+ if (role != null) {
+ if (!(role.getName() == null || oldAppRole.getName().equals(role.getName()))) {
+ oldAppRole.setName(role.getName());
+ localSession.update(oldAppRole);
+ }
+ newRolesMap.remove(oldAppRole.getAppRoleId());
+ } else {
+ obsoleteRoles.add(oldAppRole);
+ }
+ } else {
+ obsoleteRoles.add(oldAppRole);
+ }
+ }
+ Collection<EcompRole> newRolesToAdd = newRolesMap.values();
+ for (EcompRole role : newRolesToAdd) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "about to add missing role: "+role.toString());
+ EPRole newRole = new EPRole();
+ // Attention! All roles from remote application supposed to be active!
+ newRole.setActive(true);
+ newRole.setName(role.getName());
+ newRole.setAppId(appId);
+ newRole.setAppRoleId(role.getId());
+ localSession.save(newRole);
+ }
+ if (obsoleteRoles.size() > 0) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "we have obsolete roles to delete");
+ for (EPRole role : obsoleteRoles) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "obsolete role: "+role.toString());
+ Long roleId = role.getId();
+ // delete obsolete roles here
+ // Must delete all records with foreign key constraints on fn_role:
+ // fn_user_role, fn_role_composite, fn_role_function, fn_user_pseudo_role, fn_menu_functional_roles.
+ // And for fn_menu_functional, if no other roles for that menu item, remove the url.
+
+ // Delete from fn_user_role
+ @SuppressWarnings("unchecked")
+ List<EPUserApp> userRoles = localSession
+ .createQuery("from " + EPUserApp.class.getName() + " where app.id=" + appId + " and role_id=" + roleId).list();
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "number of userRoles to delete: "+userRoles.size());
+ for (EPUserApp userRole : userRoles) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "about to delete userRole: "+userRole.toString());
+ localSession.delete(userRole);
+ logger.debug(EELFLoggerDelegate.debugLogger, "finished deleting userRole: "+userRole.toString());
+ }
+
+ // Delete from fn_menu_functional_roles
+ @SuppressWarnings("unchecked")
+ List<FunctionalMenuRole> funcMenuRoles = localSession
+ .createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + roleId).list();
+ int numMenuRoles = funcMenuRoles.size();
+ logger.debug(EELFLoggerDelegate.debugLogger, "number of funcMenuRoles for roleId: "+roleId+": "+numMenuRoles);
+ for (FunctionalMenuRole funcMenuRole : funcMenuRoles) {
+ Long menuId = funcMenuRole.menuId;
+ // If this is the only role for this menu item, then the app and roles will be gone,
+ // so must null out the url too, to be consistent
+ @SuppressWarnings("unchecked")
+ List<FunctionalMenuRole> funcMenuRoles2 = localSession
+ .createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + menuId).list();
+ int numMenuRoles2 = funcMenuRoles2.size();
+ logger.debug(EELFLoggerDelegate.debugLogger, "number of funcMenuRoles for menuId: "+menuId+": "+numMenuRoles2);
+ localSession.delete(funcMenuRole);
+ if (numMenuRoles2 == 1) {
+ // If this is the only role for this menu item, then the app and roles will be gone,
+ // so must null out the url too, to be consistent
+ logger.debug(EELFLoggerDelegate.debugLogger, "There is exactly 1 menu item for this role, so emptying the url");
+ @SuppressWarnings("unchecked")
+ List<FunctionalMenuItem> funcMenuItems = localSession
+ .createQuery("from " + FunctionalMenuItem.class.getName() + " where menuId=" + menuId).list();
+ if (funcMenuItems.size() > 0) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "got the menu item");
+ FunctionalMenuItem funcMenuItem = funcMenuItems.get(0);
+ funcMenuItem.url = "";
+ localSession.update(funcMenuItem);
+ }
+ }
+ }
+
+ // Delete from fn_role_function
+ String sql = "DELETE FROM fn_role_function WHERE role_id="+roleId;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ Query query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+
+ // Delete from fn_role_composite
+ sql = "DELETE FROM fn_role_composite WHERE parent_role_id="+roleId+" OR child_role_id="+roleId;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+
+ // Delete from fn_user_pseudo_role
+ sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id="+roleId;
+ logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+ query = localSession.createSQLQuery(sql);
+ query.executeUpdate();
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "about to delete the role: "+role.toString());
+ localSession.delete(role);
+ logger.debug(EELFLoggerDelegate.debugLogger, "deleted the role");
+ }
+ }
+ logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction");
+ transaction.commit();
+ logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction");
+ result = true;
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ EcompPortalUtils.rollbackTransaction(transaction, "Exception occurred in syncAppRoles, Details: " + EcompPortalUtils.getStackTrace(e));
+ } finally {
+ localSession.close();
+ if (!result) {
+ throw new Exception("Exception occurred in syncAppRoles while closing database session for app: '" + appId + "'.");
+ }
+ }
+ }
+
+ // Called when updating the list of roles for the user
+ private RolesInAppForUser constructRolesInAppForUserUpdate(String orgUserId, Long appId, Set<EcompRole> userRolesInRemoteApp) {
+ RolesInAppForUser result;
+ result = new RolesInAppForUser();
+ result.appId = appId;
+ result.orgUserId = orgUserId;
+ for (EcompRole role : userRolesInRemoteApp) {
+ RoleInAppForUser roleInAppForUser = new RoleInAppForUser();
+ roleInAppForUser.roleId = role.getId();
+ roleInAppForUser.roleName = role.getName();
+ roleInAppForUser.isApplied = new Boolean(true);
+ result.roles.add(roleInAppForUser);
+ }
+ return result;
+ }
+
+ private EPUser getUserFromRemoteApp(String orgUserId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException {
+ EPUser user = applicationsRestClientService.get(EPUser.class, app.getId(), String.format("/user/%s", orgUserId));
+ return user;
+ }
+
+ private boolean remoteUserShouldBeCreated(List<RoleInAppForUser> roleInAppForUserList) {
+ for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
+ if (roleInAppForUser.isApplied.booleanValue()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private Set<EcompRole> postUsersRolesToRemoteApp(List<RoleInAppForUser> roleInAppForUserList, ObjectMapper mapper,
+ ApplicationsRestClientService applicationsRestClientService, Long appId, String orgUserId) throws JsonProcessingException, HTTPException {
+ Set<EcompRole> updatedUserRoles = constructUsersEcompRoles(roleInAppForUserList);
+ String userRolesAsString = mapper.writeValueAsString(updatedUserRoles);
+ applicationsRestClientService.post(EcompRole.class, appId, userRolesAsString, String.format("/user/%s/roles", orgUserId));
+ // TODO: We should add code that verifies that the post operation did succeed. Because the SDK may still return 200 OK with an html page even when it fails!
+ return updatedUserRoles;
+ }
+
+ private Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
+ Set<EcompRole> existingUserRoles = new TreeSet<EcompRole>();
+ for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
+ if (roleInAppForUser.isApplied) {
+ EcompRole ecompRole = new EcompRole();
+ ecompRole.setId(roleInAppForUser.roleId);
+ ecompRole.setName(roleInAppForUser.roleName);
+ existingUserRoles.add(ecompRole);
+ }
+ }
+ return existingUserRoles;
+ }
+
+ private static void createNewUserOnRemoteApp(String orgUserId, EPApp app, ApplicationsRestClientService applicationsRestClientService,
+ SearchService searchService, ObjectMapper mapper) throws Exception {
+ EPUser client = searchService.searchUserByUserId(orgUserId);
+ if (client == null) {
+ String msg = "cannot create user " + orgUserId + ", because he/she cannot be found in phonebook.";
+ logger.error(EELFLoggerDelegate.errorLogger, msg);
+ throw new Exception(msg);
+ }
+ client.setLoginId(orgUserId);
+ client.setActive(true);
+ // The remote doesn't care about other apps, and this has caused serialization problems - infinite recursion.
+ client.getEPUserApps().clear();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ String userAsString = mapper.writeValueAsString(client);
+ logger.debug(EELFLoggerDelegate.debugLogger, "about to post new client to remote application, users json = " + userAsString);
+ applicationsRestClientService.post(EPUser.class, app.getId(), userAsString, String.format("/user", orgUserId));
+ }
+
+ public String updateRemoteUserProfile(String orgUserId, Long appId){
+
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ EPUser client = searchService.searchUserByUserId(orgUserId);
+ EPUser newUser = new EPUser();
+ newUser.setActive(client.getActive());
+ newUser.setFirstName(client.getFirstName());
+ newUser.setLastName(client.getLastName());
+ newUser.setLoginId(client.getLoginId());
+ newUser.setLoginPwd(client.getLoginPwd());
+ newUser.setMiddleInitial(client.getMiddleInitial());
+ newUser.setEmail(client.getEmail());
+ newUser.setOrgUserId(client.getLoginId());
+ try {
+ String userAsString = mapper.writeValueAsString(newUser);
+ List<EPApp> appList = appsService.getUserRemoteApps(client.getId().toString());
+ //applicationsRestClientService.post(EPUser.class, appId, userAsString, String.format("/user", orgUserId));
+ for(EPApp eachApp : appList){
+ try{
+ applicationsRestClientService.post(EPUser.class, eachApp.getId(), userAsString, String.format("/user/%s", orgUserId));
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to update user: " + client.getOrgUserId() + " in remote app. appId = " + eachApp.getId());
+ }
+ }
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ return "failure";
+ }
+
+ return "success";
+
+ }
+
+ private static final Object syncRests = new Object();
+
+ @Override
+ public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) {
+ boolean result = false;
+ String orgUserId = "";
+ if (newAppRolesForUser != null && newAppRolesForUser.orgUserId != null) {
+ orgUserId = newAppRolesForUser.orgUserId.trim();
+ }
+ Long appId = newAppRolesForUser.appId;
+ List<RoleInAppForUser> roleInAppForUserList = newAppRolesForUser.appRoles;
+ if (orgUserId.length() > 0) {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+
+ try {
+ EPApp app = appsService.getApp(appId);
+ EPUser remoteAppUser = getUserFromRemoteApp(orgUserId, app, applicationsRestClientService);
+ if (remoteAppUser == null) {
+ if (remoteUserShouldBeCreated(roleInAppForUserList)) {
+ createNewUserOnRemoteApp(orgUserId, app, applicationsRestClientService, searchService, mapper);
+ // If we succeed, we know that the new user was persisted on remote app.
+ remoteAppUser = getUserFromRemoteApp(orgUserId, app, applicationsRestClientService);
+ if (remoteAppUser == null) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to persist new user: " + orgUserId + " in remote app. appId = " + appId);
+// return null;
+ }
+ }
+ }
+ if (remoteAppUser != null) {
+ Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper, applicationsRestClientService, appId, orgUserId);
+ RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, appId, userRolesInRemoteApp);
+ result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser);
+ }
+ } catch (Exception e) {
+ String message = String.format("Failed to create user or update user roles for the User %s, and for the AppId %s, Details: %s",
+ orgUserId, Long.toString(appId), EcompPortalUtils.getStackTrace(e));
+ logger.error(EELFLoggerDelegate.errorLogger, message);
+ result = false;
+ }
+
+ }
+ return result;
+ }
+
+ // This is for a single app
+ private boolean applyChangesInUserRolesForAppToEcompDB(RolesInAppForUser rolesInAppForUser) {
+ boolean result = false;
+ String orgUserId = rolesInAppForUser.orgUserId;
+ Long appId = rolesInAppForUser.appId;
+ synchronized (syncRests) {
+ if (rolesInAppForUser != null) {
+ createLocalUserIfNecessary(orgUserId);
+ }
+
+ if (rolesInAppForUser != null) {
+ EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.size()];
+ for (int i = 0; i < rolesInAppForUser.roles.size(); i++) {
+ RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i);
+ EcompRole role = new EcompRole();
+ role.setId(roleInAppForUser.roleId);
+ role.setName(roleInAppForUser.roleName);
+ userAppRoles[i] = role;
+ }
+ try {
+ syncUserRoles(sessionFactory, orgUserId, appId, userAppRoles);
+ result = true;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "applyChangesInUserRolesForAppToEcompDB syncUserRoles, orgUserId = " + orgUserId);
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+ }
+ }
+ return result;
+ }
+
+ @Override
+ public List<UserApplicationRoles> getUsersFromAppEndpoint(Long appId) throws HTTPException {
+ RemoteUserWithRoles[] remoteUsers = applicationsRestClientService.get(RemoteUserWithRoles[].class, appId, "/users");
+ ArrayList<UserApplicationRoles> userApplicationRoles = new ArrayList<UserApplicationRoles>();
+ for (RemoteUserWithRoles remoteUser : remoteUsers) {
+ UserApplicationRoles userWithRemoteAppRoles = convertToUserApplicationRoles(appId, remoteUser);
+ if(userWithRemoteAppRoles.roles!=null && userWithRemoteAppRoles.roles.size()>0) {
+ userApplicationRoles.add(userWithRemoteAppRoles);
+ } else {
+ logger.debug(EELFLoggerDelegate.debugLogger, "User " + userWithRemoteAppRoles.orgUserId + " doesn't have any roles assigned to any app.");
+ }
+ }
+
+ return userApplicationRoles;
+ }
+
+ private UserApplicationRoles convertToUserApplicationRoles(Long appId, RemoteUserWithRoles remoteUser) {
+ UserApplicationRoles userWithRemoteAppRoles = new UserApplicationRoles();
+ userWithRemoteAppRoles.appId = appId;
+ userWithRemoteAppRoles.orgUserId = remoteUser.loginId;
+ userWithRemoteAppRoles.firstName = remoteUser.firstName;
+ userWithRemoteAppRoles.lastName = remoteUser.lastName;
+ userWithRemoteAppRoles.roles = remoteUser.roles;
+ return userWithRemoteAppRoles;
+ }
+
+ public static void persistExternalRoleInEcompDb(EPRole externalAppRole, Long appId, EPRoleService roleService) {
+ externalAppRole.setAppId(appId);
+ externalAppRole.setAppRoleId(externalAppRole.getId());
+ externalAppRole.setId(null); // We will persist a new role, with ecomp role id which will be different than external app role id.
+
+ roleService.saveRole(externalAppRole);
+ logger.debug(EELFLoggerDelegate.debugLogger, String.format("ECOMP persists role from app:%d, app roleId: %d, roleName: %s", appId, externalAppRole.getAppRoleId(), externalAppRole.getName()));
+ }
+
+ @Override
+ public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException {
+ EPRole[] appRolesFull = applicationsRestClientService.get(EPRole[].class, appId, "/rolesFull");
+ List<EPRole> rolesList = Arrays.asList(appRolesFull);
+ for (EPRole externalAppRole : rolesList) {
+
+ // Try to find an existing extern role for the app in the local ecomp DB. If so, then use its id to update the existing external application role record.
+ Long externAppId = externalAppRole.getId();
+ EPRole existingAppRole = epRoleService.getRole(appId, externAppId);
+ if (existingAppRole != null) {
+ logger.debug(EELFLoggerDelegate.debugLogger, String.format("ecomp role already exists for app=%s; appRoleId=%s. No need to import this one.", appId, externAppId));
+ continue;
+ }
+ // persistExternalRoleInEcompDb(externalAppRole, appId, roleService);
+ }
+
+ return rolesList;
+ }
+
+ @Override
+ public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) {
+ // Find the records for this user-app combo, if any
+ String filter = " where user_id = " + Long.toString(userId) + " and app_id = " + Long.toString(appId);
+ @SuppressWarnings("unchecked")
+ List<EPUserApp> roleList = dataAccessService.getList(EPUserApp.class, filter, null, null);
+ logger.debug(EELFLoggerDelegate.debugLogger, "getCachedAppRolesForUser: list size is {}",
+ roleList.size());
+ return roleList;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/UserService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/UserService.java
new file mode 100644
index 00000000..8fcd5669
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/UserService.java
@@ -0,0 +1,34 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.List;
+
+import org.openecomp.portalapp.portal.domain.EPUser;
+
+public interface UserService {
+
+ List getUserByUserId(String orgUserId);
+
+ List getUserByFirstLastName(String firstName, String lastName);
+
+ public String saveNewUser(EPUser newUser, String checkDuplicate) throws Exception;
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/UserServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/UserServiceImpl.java
new file mode 100644
index 00000000..0b4a8809
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/UserServiceImpl.java
@@ -0,0 +1,260 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.FusionObject.Utilities;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.service.DataAccessService;
+import org.openecomp.portalsdk.core.util.CipherUtil;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service("userService")
+@Transactional
+public class UserServiceImpl implements UserService {
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserServiceImpl.class);
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public List getUserByUserId(String userId) {
+
+
+ if(SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC")){
+ List<EPUser> users=new ArrayList<EPUser>();
+ List<EPUser> filterdUsers=new ArrayList<EPUser>();
+ BufferedReader in = null;
+ HttpURLConnection con = null;
+ try{
+ String url = EPSystemProperties.getProperty(EPSystemProperties.AUTH_USER_SERVER);
+ URL obj = new URL(url);
+
+ con = (HttpURLConnection) obj.openConnection();
+
+ // optional default is GET
+ con.setRequestMethod("GET");
+ con.setConnectTimeout(3000);
+ con.setReadTimeout(8000);
+
+ StringBuffer response = new StringBuffer();
+
+ in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
+ String inputLine;
+ while ((inputLine = in.readLine()) != null)
+ response.append(inputLine);
+ JSONObject jObject = new JSONObject(response.toString()); // json
+ JSONArray jsonUsers = jObject.getJSONArray("response"); // get data object
+ for (int i = 0; i < jsonUsers.length(); i++) {
+ JSONObject eachObject = jsonUsers.getJSONObject(i);
+ EPUser eachUser = new EPUser();
+ eachUser.setOrgUserId(eachObject.get("id").toString());// getString("id"));
+ eachUser.setFirstName(eachObject.get("givenName").toString());
+ eachUser.setLastName(eachObject.get("familyName").toString());
+ eachUser.setEmail(eachObject.get("email").toString());
+ users.add(eachUser);
+ }
+
+ for(int i = 0 ; i < users.size(); i ++){
+
+ if(Utilities.nvl(userId).length() > 0){
+ if(!userId.equalsIgnoreCase(users.get(i).getOrgUserId())){
+ continue;
+ }
+ }
+ filterdUsers.add(users.get(i));
+
+ }
+
+ }catch (Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }finally{
+ try {
+ in.close();
+ con.disconnect();
+ } catch (IOException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+ }
+
+ return filterdUsers;
+
+ }else{
+
+ List list = null;
+ StringBuffer criteria = new StringBuffer();
+ criteria.append(" where org_user_id = '").append(userId).append("'");
+ list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null);
+ return (list == null || list.size() == 0) ? null : list;
+
+ }
+
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public List getUserByFirstLastName(String firstName, String lastName) {
+
+ if(!SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC")){
+
+ List list = null;
+ StringBuffer criteria = new StringBuffer();
+ if(firstName!=null)
+ criteria.append(" where first_name = '").append(firstName).append("'");
+ if(lastName!=null)
+ criteria.append(" where last_name = '").append(lastName).append("'");
+ list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null);
+ return (list == null || list.size() == 0) ? null : list;
+
+ }else{
+
+ List<EPUser> users=new ArrayList<EPUser>();
+ List<EPUser> filterdUsers=new ArrayList<EPUser>();
+ BufferedReader in = null;
+ HttpURLConnection con = null;
+ try{
+ String url = EPSystemProperties.getProperty(EPSystemProperties.AUTH_USER_SERVER);
+ URL obj = new URL(url);
+
+ con = (HttpURLConnection) obj.openConnection();
+
+ // optional default is GET
+ con.setRequestMethod("GET");
+ con.setConnectTimeout(3000);
+ con.setReadTimeout(8000);
+
+ StringBuffer response = new StringBuffer();
+
+ in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
+ String inputLine;
+ while ((inputLine = in.readLine()) != null)
+ response.append(inputLine);
+ JSONObject jObject = new JSONObject(response.toString()); // json
+ JSONArray jsonUsers = jObject.getJSONArray("response"); // get data object
+ for (int i = 0; i < jsonUsers.length(); i++) {
+ JSONObject eachObject = jsonUsers.getJSONObject(i);
+ EPUser eachUser = new EPUser();
+ eachUser.setOrgUserId(eachObject.get("id").toString());// getString("id"));
+ eachUser.setFirstName(eachObject.get("givenName").toString());
+ eachUser.setLastName(eachObject.get("familyName").toString());
+ eachUser.setEmail(eachObject.get("email").toString());
+ users.add(eachUser);
+ }
+
+ for(int i = 0 ; i < users.size(); i ++){
+
+ if(Utilities.nvl(firstName).length() > 0){
+ if(!firstName.equalsIgnoreCase(users.get(i).getFirstName())){
+ continue;
+ }
+ }
+ if(Utilities.nvl(lastName).length() > 0){
+ if(!lastName.equalsIgnoreCase(users.get(i).getLastName())){
+ continue;
+ }
+ }
+
+
+ filterdUsers.add(users.get(i));
+
+ }
+
+ }catch (Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }finally{
+ try {
+ in.close();
+ con.disconnect();
+ } catch (IOException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+ }
+
+ return filterdUsers;
+ }
+
+ }
+
+ public String saveNewUser(EPUser newUser, String checkDuplicate) throws Exception{
+
+ try{
+
+ List list = null;
+ StringBuffer criteria = new StringBuffer();
+ criteria.append(" where org_user_id = '").append(newUser.getLoginId()).append("'");
+ list = getDataAccessService().getList(EPUser.class, criteria.toString(), null, null);
+ if(list == null || list.size()==0){
+ newUser.setActive(true);
+ newUser.setOrgUserId(newUser.getLoginId());
+ newUser.setLoginPwd(CipherUtil.encrypt(newUser.getLoginPwd()));
+ getDataAccessService().saveDomainObject(newUser, null);
+ }else{
+ if(checkDuplicate.equals("Yes")){
+ // userId already exist in database
+ return "Record already exist";
+ }else{
+
+ EPUser oldUser = (EPUser) list.get(0);
+ oldUser.setFirstName(newUser.getFirstName());
+ oldUser.setLastName(newUser.getLastName());
+ oldUser.setMiddleInitial(newUser.getMiddleInitial());
+ if(!oldUser.getLoginPwd().equals(newUser.getLoginPwd()))
+ oldUser.setLoginPwd(CipherUtil.encrypt(newUser.getLoginPwd()));
+ else
+ oldUser.setLoginPwd(newUser.getLoginPwd());
+ getDataAccessService().saveDomainObject(oldUser, null);
+
+ }
+
+ }
+
+ }catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "", e);
+ throw new Exception(e);
+ }
+ return "success";
+ };
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/WidgetService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/WidgetService.java
new file mode 100644
index 00000000..afec3389
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/WidgetService.java
@@ -0,0 +1,36 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.List;
+
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.transport.FieldsValidator;
+import org.openecomp.portalapp.portal.transport.OnboardingWidget;
+
+public interface WidgetService {
+
+ List<OnboardingWidget> getOnboardingWidgets(EPUser user, boolean managed);
+
+ FieldsValidator setOnboardingWidget(EPUser user, OnboardingWidget onboardingWidget);
+
+ FieldsValidator deleteOnboardingWidget(EPUser user, Long onboardingWidgetId);
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/WidgetServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/WidgetServiceImpl.java
new file mode 100644
index 00000000..62ff9e5f
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/service/WidgetServiceImpl.java
@@ -0,0 +1,275 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.service;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.annotation.PostConstruct;
+import javax.servlet.http.HttpServletResponse;
+
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.Transaction;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.domain.EPUserApp;
+import org.openecomp.portalapp.portal.domain.Widget;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
+import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
+import org.openecomp.portalapp.portal.transport.FieldsValidator;
+import org.openecomp.portalapp.portal.transport.OnboardingWidget;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.service.DataAccessService;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service("widgetService")
+@Transactional
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class WidgetServiceImpl implements WidgetService {
+
+ private static final String baseSqlToken = " widget.WIDGET_ID, widget.WDG_NAME, widget.APP_ID, app.APP_NAME, widget.WDG_WIDTH, widget.WDG_HEIGHT, widget.WDG_URL"
+ + " from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID";
+
+ private String validAppsFilter = "";
+
+ private Long LONG_ECOMP_APP_ID = 1L;
+ private Long ACCOUNT_ADMIN_ROLE_ID = 999L;
+ private static final Long DUBLICATED_FIELD_VALUE_ECOMP_ERROR = new Long(EPSystemProperties.DUBLICATED_FIELD_VALUE_ECOMP_ERROR);
+
+ private static final String urlField = "url";
+
+ private static final String nameField = "name";
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetServiceImpl.class);
+
+ @Autowired
+ AdminRolesService adminRolesService;
+ @Autowired
+ private SessionFactory sessionFactory;
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ @PostConstruct
+ private void init() {
+ try {
+ validAppsFilter = " AND app.ENABLED = 'Y' AND app.APP_ID != " + SystemProperties.getProperty(EPSystemProperties.ECOMP_APP_ID);
+ ACCOUNT_ADMIN_ROLE_ID = Long.valueOf(SystemProperties.getProperty(EPSystemProperties.ACCOUNT_ADMIN_ROLE_ID));
+ LONG_ECOMP_APP_ID = Long.valueOf(SystemProperties.getProperty(EPSystemProperties.ECOMP_APP_ID));
+ } catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+ }
+
+ private String sqlWidgetsForAllApps() {
+ return "SELECT" + baseSqlToken + validAppsFilter;
+ }
+
+ private String sqlWidgetsForAllAppsWhereUserIsAdmin(Long userId) {
+ return "SELECT" + baseSqlToken + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = " + userId
+ + " AND FN_USER_ROLE.ROLE_ID = " + ACCOUNT_ADMIN_ROLE_ID + validAppsFilter;
+ }
+
+ private String sqlWidgetsForAllAppsWhereUserHasAnyRole(Long userId) {
+ return "SELECT DISTINCT" + baseSqlToken + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = "
+ + userId + validAppsFilter;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<OnboardingWidget> getOnboardingWidgets(EPUser user, boolean managed) {
+ List<OnboardingWidget> onboardingWidgets = new ArrayList<OnboardingWidget>();
+ String sql = null;
+ if (adminRolesService.isSuperAdmin(user)) {
+ sql = this.sqlWidgetsForAllApps();
+ } else if (managed) {
+ if (adminRolesService.isAccountAdmin(user)) {
+ sql = this.sqlWidgetsForAllAppsWhereUserIsAdmin(user.getId());
+ }
+ } else if (adminRolesService.isAccountAdmin(user) || adminRolesService.isUser(user)) {
+ sql = this.sqlWidgetsForAllAppsWhereUserHasAnyRole(user.getId());
+ }
+ if (sql != null) {
+ onboardingWidgets = dataAccessService.executeSQLQuery(sql, OnboardingWidget.class, null);
+ }
+ return onboardingWidgets;
+ }
+
+ private static final Object syncRests = new Object();
+
+ private boolean isUserAdminOfAppForWidget(boolean superAdmin, Long userId, Long appId) {
+ if (!superAdmin) {
+ @SuppressWarnings("unchecked")
+ List<EPUserApp> userRoles = dataAccessService.getList(EPUserApp.class,
+ " where id = " + userId + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID + " and app.id = " + appId, null, null);
+ return (userRoles.size() > 0);
+ }
+ return true;
+ }
+
+ private void validateOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) {
+ @SuppressWarnings("unchecked")
+ List<Widget> widgets = dataAccessService.getList(Widget.class,
+ " where url = '" + onboardingWidget.url + "'" + " or name = '" + onboardingWidget.name + "'", null, null);
+ boolean dublicatedUrl = false;
+ boolean dublicatedName = false;
+ for (Widget widget : widgets) {
+ if (onboardingWidget.id != null && onboardingWidget.id.equals(widget.getId())) {
+ // widget should not be compared with itself
+ continue;
+ }
+ if (!dublicatedUrl && widget.getUrl().equals(onboardingWidget.url)) {
+ dublicatedUrl = true;
+ if (dublicatedName) {
+ break;
+ }
+ }
+ if (!dublicatedName && widget.getName().equalsIgnoreCase(onboardingWidget.name) && widget.getAppId().equals(onboardingWidget.appId)) {
+ dublicatedName = true;
+ if (dublicatedUrl) {
+ break;
+ }
+ }
+ }
+ if (dublicatedUrl || dublicatedName) {
+ if (dublicatedUrl) {
+ fieldsValidator.addProblematicFieldName(urlField);
+ }
+ if (dublicatedName) {
+ fieldsValidator.addProblematicFieldName(nameField);
+ }
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_CONFLICT);
+ fieldsValidator.errorCode = DUBLICATED_FIELD_VALUE_ECOMP_ERROR;
+ }
+ }
+
+ private void applyOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) {
+ boolean result = false;
+ Session localSession = null;
+ Transaction transaction = null;
+ try {
+ localSession = sessionFactory.openSession();
+ transaction = localSession.beginTransaction();
+ Widget widget;
+ if (onboardingWidget.id == null) {
+ widget = new Widget();
+ } else {
+ widget = (Widget) localSession.get(Widget.class, onboardingWidget.id);
+ }
+ widget.setAppId(onboardingWidget.appId);
+ widget.setName(onboardingWidget.name);
+ widget.setWidth(onboardingWidget.width);
+ widget.setHeight(onboardingWidget.height);
+ widget.setUrl(onboardingWidget.url);
+ localSession.saveOrUpdate(widget);
+ transaction.commit();
+ result = true;
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ EcompPortalUtils.rollbackTransaction(transaction, "applyOnboardingWidget rollback, exception = " + e);
+ } finally {
+ EcompPortalUtils.closeLocalSession(localSession, "applyOnboardingWidget");
+ }
+ if (!result) {
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+ }
+
+ private FieldsValidator updateOrSaveWidget(boolean superAdmin, Long userId, OnboardingWidget onboardingWidget) {
+ FieldsValidator fieldsValidator = new FieldsValidator();
+ if (!this.isUserAdminOfAppForWidget(superAdmin, userId, onboardingWidget.appId)) {
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
+ return fieldsValidator;
+ }
+ synchronized (syncRests) {
+ // onboardingWidget.id is null for POST and not null for PUT
+ if (onboardingWidget.id == null) {
+ this.validateOnboardingWidget(onboardingWidget, fieldsValidator);
+ } else {
+ Widget widget = (Widget) dataAccessService.getDomainObject(Widget.class, onboardingWidget.id, null);
+ if (widget == null || widget.getId() == null) {
+ // Widget not found
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_NOT_FOUND);
+ return fieldsValidator;
+ }
+ this.validateOnboardingWidget(onboardingWidget, fieldsValidator);
+ }
+ if (fieldsValidator.httpStatusCode.intValue() == HttpServletResponse.SC_OK) {
+ this.applyOnboardingWidget(onboardingWidget, fieldsValidator);
+ }
+ }
+ return fieldsValidator;
+ }
+
+ @Override
+ public FieldsValidator setOnboardingWidget(EPUser user, OnboardingWidget onboardingWidget) {
+ if (onboardingWidget.name.length() == 0 || onboardingWidget.url.length() == 0 || onboardingWidget.appId == null
+ || onboardingWidget.appId.equals(LONG_ECOMP_APP_ID) || onboardingWidget.width.intValue() <= 0 || onboardingWidget.height.intValue() <= 0) {
+ if (onboardingWidget.appId.equals(LONG_ECOMP_APP_ID)) {
+ // logger.error("Alarm!!! Security breach attempt on user " + user.getFullName() + ", userId = " + user.getUserId());
+ }
+ FieldsValidator fieldsValidator = new FieldsValidator();
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_BAD_REQUEST);
+ return fieldsValidator;
+ }
+ return this.updateOrSaveWidget(adminRolesService.isSuperAdmin(user), user.getId(), onboardingWidget);
+ }
+
+ @Override
+ public FieldsValidator deleteOnboardingWidget(EPUser user, Long onboardingWidgetId) {
+ FieldsValidator fieldsValidator = new FieldsValidator();
+ synchronized (syncRests) {
+ Widget widget = (Widget) dataAccessService.getDomainObject(Widget.class, onboardingWidgetId, null);
+ if (widget != null && widget.getId() != null) { // widget exists
+ if (!this.isUserAdminOfAppForWidget(adminRolesService.isSuperAdmin(user), user.getId(), widget.getAppId())) {
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN);
+ } else {
+ boolean result = false;
+ Session localSession = null;
+ Transaction transaction = null;
+ try {
+ localSession = sessionFactory.openSession();
+ transaction = localSession.beginTransaction();
+ localSession.delete(localSession.get(Widget.class, onboardingWidgetId));
+ transaction.commit();
+ result = true;
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+ EcompPortalUtils.rollbackTransaction(transaction, "deleteOnboardingWidget rollback, exception = " + e);
+ } finally {
+ EcompPortalUtils.closeLocalSession(localSession, "deleteOnboardingWidget");
+ }
+ if (!result) {
+ fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ }
+ }
+ }
+ }
+ return fieldsValidator;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/AllAppsWithRolesForUser.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/AllAppsWithRolesForUser.java
new file mode 100644
index 00000000..6939a100
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/AllAppsWithRolesForUser.java
@@ -0,0 +1,40 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+import java.util.List;
+
+public class AllAppsWithRolesForUser {
+
+ public String orgUserId;
+
+ public List<AppWithUserRoles> apps;
+
+ public static class AppWithUserRoles {
+
+ public Long appId;
+
+ public String appName;
+
+ public List<RoleInAppForUser> appRoles;
+
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/AppCatalogPersonalization.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/AppCatalogPersonalization.java
new file mode 100644
index 00000000..4ad2594a
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/AppCatalogPersonalization.java
@@ -0,0 +1,38 @@
+package org.openecomp.portalapp.portal.transport;
+
+
+/**
+ * Model for the object PUT to the controller when the user takes an action on
+ * an application in the catalog.
+ */
+public class AppCatalogPersonalization {
+
+ public Long appId;
+ public Boolean select;
+ public Boolean pending;
+
+ public Long getAppId() {
+ return appId;
+ }
+
+ public void setAppId(Long appId) {
+ this.appId = appId;
+ }
+
+ public Boolean getSelect() {
+ return select;
+ }
+
+ public void setSelect(Boolean select) {
+ this.select = select;
+ }
+
+ public Boolean getPending() {
+ return pending;
+ }
+
+ public void setPending(Boolean pending) {
+ this.pending = pending;
+ }
+
+} \ No newline at end of file
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/AppNameIdIsAdmin.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/AppNameIdIsAdmin.java
new file mode 100644
index 00000000..d04e8406
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/AppNameIdIsAdmin.java
@@ -0,0 +1,31 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+public class AppNameIdIsAdmin {
+
+ public Long id;
+
+ public String appName;
+
+ public Boolean isAdmin;
+
+ public Boolean restrictedApp;
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/AppWithRolesForUser.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/AppWithRolesForUser.java
new file mode 100644
index 00000000..fe996fdd
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/AppWithRolesForUser.java
@@ -0,0 +1,34 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+import java.util.List;
+
+public class AppWithRolesForUser {
+
+ public String orgUserId;
+
+ public Long appId;
+
+ public String appName;
+
+ public List<RoleInAppForUser> appRoles;
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/AppsListWithAdminRole.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/AppsListWithAdminRole.java
new file mode 100644
index 00000000..907bf7e5
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/AppsListWithAdminRole.java
@@ -0,0 +1,34 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+import java.util.ArrayList;
+
+public class AppsListWithAdminRole {
+
+ public String orgUserId;
+
+ public ArrayList<AppNameIdIsAdmin> appsRoles;
+
+ public AppsListWithAdminRole() {
+ appsRoles = new ArrayList<AppNameIdIsAdmin>();
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/CommonWidget.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/CommonWidget.java
new file mode 100644
index 00000000..706d6baf
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/CommonWidget.java
@@ -0,0 +1,140 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+import org.openecomp.portalsdk.core.domain.support.DomainVo;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+
+/**
+ * This is to handle portal admins
+ * @author aw3218
+ */
+@Entity
+@Table(name="fn_common_widget_data")
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class CommonWidget extends DomainVo{
+
+ private static final long serialVersionUID = 7897021982887364557L;
+
+ @Id
+ @GeneratedValue(strategy=GenerationType.AUTO)
+ @Column(name = "id")
+ private Long id;
+
+ @Column(name = "category")
+ public String category;
+
+ @Column(name = "href")
+ public String href;
+
+ @Column(name = "title")
+ public String title;
+
+ @Column(name = "content")
+ public String content;
+
+ @Column(name = "event_date")
+ public String eventDate;
+
+ @Column(name = "sort_order")
+ public Integer sortOrder;
+
+
+ public CommonWidget(){
+
+ }
+
+ public CommonWidget(String category, String href, String title, String content, String eventDate, Integer sortOrder){
+ this.category = category;
+ this.href = href;
+ this.title = title;
+ this.content = content;
+ this.eventDate = eventDate;
+ this.sortOrder = sortOrder;
+ }
+
+ public String getCategory() {
+ return category;
+ }
+
+ public void setCategory(String category) {
+ this.category = category;
+ }
+
+ public String getHref() {
+ return href;
+ }
+
+ public void setHref(String href) {
+ this.href = href;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public Integer getSortOrder() {
+ return sortOrder;
+ }
+
+ public void setSortOrder(Integer sortOrder) {
+ this.sortOrder = sortOrder;
+ }
+
+ public static long getSerialversionuid() {
+ return serialVersionUID;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getContent() {
+ return content;
+ }
+
+ public void setContent(String content) {
+ this.content = content;
+ }
+
+ public String getEventDate() {
+ return eventDate;
+ }
+
+ public void setEventDate(String eventDate) {
+ this.eventDate = eventDate;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/CommonWidgetMeta.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/CommonWidgetMeta.java
new file mode 100644
index 00000000..dba1127c
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/CommonWidgetMeta.java
@@ -0,0 +1,50 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+import java.util.List;
+
+public class CommonWidgetMeta {
+
+ private String category;
+ private List<CommonWidget> items;
+
+ public CommonWidgetMeta(){
+
+ }
+
+ public CommonWidgetMeta(String category, List<CommonWidget> items){
+ this.category = category;
+ this.items = items;
+ }
+
+ public String getCategory() {
+ return category;
+ }
+ public void setCategory(String category) {
+ this.category = category;
+ }
+ public List<CommonWidget> getItems() {
+ return items;
+ }
+ public void setItems(List<CommonWidget> items) {
+ this.items = items;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/EventWidget.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/EventWidget.java
new file mode 100644
index 00000000..26d694fd
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/EventWidget.java
@@ -0,0 +1,139 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+/*package org.openecomp.portalapp.portal.transport;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+import org.openecomp.portalsdk.core.domain.support.DomainVo;
+import com.fasterxml.jackson.annotation.JsonInclude;
+
+*//**
+ * This is to handle portal admins
+ * @author aw3218
+ *//*
+@Entity
+@Table(name="fn_event_widget_data")
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class EventWidget extends DomainVo{
+
+ *//**
+ *
+ *//*
+ private static final long serialVersionUID = -2784849102886421352L;
+
+
+ @Id
+ @GeneratedValue(strategy=GenerationType.AUTO)
+ @Column(name = "id")
+ private Long id;
+
+ @Column(name = "category")
+ private String category;
+
+ @Column(name = "title")
+ private String title;
+
+ @Column(name = "href")
+ private String href;
+
+ @Column(name = "content")
+ private String content;
+
+ @Column(name = "month_val")
+ private String mon;
+
+ @Column(name = "day_val")
+ private Integer day;
+
+ @Column(name = "year_val")
+ private Integer year;
+
+ @Column(name = "sort_order")
+ private Integer sortOrder;
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public String getHref() {
+ return href;
+ }
+
+ public void setHref(String href) {
+ this.href = href;
+ }
+
+ public String getContent() {
+ return content;
+ }
+
+ public void setContent(String content) {
+ this.content = content;
+ }
+
+ public String getMon() {
+ return mon;
+ }
+
+ public void setMonth(String mon) {
+ this.mon = mon;
+ }
+
+ public Integer getDay() {
+ return day;
+ }
+
+ public void setDay(Integer day) {
+ this.day = day;
+ }
+
+ public Integer getYear() {
+ return year;
+ }
+
+ public void setYear(Integer year) {
+ this.year = year;
+ }
+
+ public Integer getSortOrder() {
+ return sortOrder;
+ }
+
+ public String getCategory() {
+ return category;
+ }
+
+ public void setCategory(String category) {
+ this.category = category;
+ }
+
+
+}
+*/
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/EventWidgetMeta.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/EventWidgetMeta.java
new file mode 100644
index 00000000..60e9aa01
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/EventWidgetMeta.java
@@ -0,0 +1,52 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+/*package org.openecomp.portalapp.portal.transport;
+
+import java.util.List;
+
+public class EventWidgetMeta {
+
+ private String category;
+ private List<EventWidget> items;
+
+ public EventWidgetMeta(){
+
+ }
+
+ public EventWidgetMeta(String category, List<EventWidget> items){
+ this.category = category;
+ this.items = items;
+ }
+
+ public String getCategory() {
+ return category;
+ }
+ public void setCategory(String category) {
+ this.category = category;
+ }
+ public List<EventWidget> getItems() {
+ return items;
+ }
+ public void setItems(List<EventWidget> items) {
+ this.items = items;
+ }
+}
+*/
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FavoritesFunctionalMenuItem.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FavoritesFunctionalMenuItem.java
new file mode 100644
index 00000000..1a8691d8
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FavoritesFunctionalMenuItem.java
@@ -0,0 +1,45 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+import java.io.Serializable;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+
+/**
+ * This is to handle functional menu favorites
+ */
+@Entity
+@Table(name="fn_menu_favorites")
+public class FavoritesFunctionalMenuItem implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @Column(name = "user_id")
+ public Long userId;
+
+ @Id
+ @Column(name = "menu_id")
+ public Long menuId;
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FavoritesFunctionalMenuItemJson.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FavoritesFunctionalMenuItemJson.java
new file mode 100644
index 00000000..7d829b6b
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FavoritesFunctionalMenuItemJson.java
@@ -0,0 +1,57 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+import java.io.Serializable;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import javax.persistence.Transient;
+
+
+
+/**
+ * This is to handle functional menu favorites
+ */
+@Entity
+@Table(name="fn_menu_favorites")
+public class FavoritesFunctionalMenuItemJson implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @Column(name = "user_id")
+ public Long userId;
+
+ @Id
+ @Column(name = "menu_id")
+ public Long menuId;
+
+ @Column(name = "text")
+ public String text;
+
+ @Column(name = "url")
+ public String url;
+
+ @Transient
+ public Boolean restrictedApp;
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FieldsValidator.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FieldsValidator.java
new file mode 100644
index 00000000..ca559970
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FieldsValidator.java
@@ -0,0 +1,49 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.servlet.http.HttpServletResponse;
+
+public class FieldsValidator {
+
+ public Long httpStatusCode = new Long(HttpServletResponse.SC_OK);
+
+ public Long errorCode;
+
+ public class FieldName {
+
+ public String name;
+
+ public FieldName(String name) {
+ this.name = name;
+ }
+
+ }
+
+ public List<FieldName> fields = new ArrayList<FieldName>();
+
+ public void addProblematicFieldName(String name) {
+ fields.add(new FieldName(name));
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuItem.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuItem.java
new file mode 100644
index 00000000..022c0af6
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuItem.java
@@ -0,0 +1,90 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+import java.io.Serializable;
+import java.util.List;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import javax.persistence.Transient;
+
+@Entity
+@Table(name="fn_menu_functional")
+public class FunctionalMenuItem implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @GeneratedValue(strategy=GenerationType.IDENTITY)
+ @Column(name = "MENU_ID")
+ public Long menuId;
+
+ @Column(name = "COLUMN_NUM")
+ public Integer column;
+
+ @Column(name = "TEXT")
+ public String text;
+
+ @Column(name = "PARENT_MENU_ID")
+ public Integer parentMenuId;
+
+ @Column(name = "URL")
+ public String url;
+
+ @Column(name="ACTIVE_YN")
+ public String active_yn;
+
+ @Transient
+ public Integer appid;
+
+ @Transient
+ public List<Integer> roles;
+
+ @Transient
+ public Boolean restrictedApp;
+
+ public void normalize() {
+ if (this.column == null)
+ this.column = new Integer(1);
+ this.text = (this.text == null) ? "" : this.text.trim();
+ if (this.parentMenuId == null)
+ this.parentMenuId = new Integer(-1);
+ this.url = (this.url == null) ? "" : this.url.trim();
+ }
+
+ @Override
+ public String toString() {
+ return "FunctionalMenuItem [menuId=" + menuId + ", column=" + column + ", text=" + text + ", parentMenuId="
+ + parentMenuId + ", url=" + url + ", active_yn=" + active_yn + ", appid=" + appid + ", roles=" + roles
+ + ", restrictedApp=" + restrictedApp + "]";
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public void setRestrictedApp(Boolean restrictedApp) {
+ this.restrictedApp = restrictedApp;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuItemJson.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuItemJson.java
new file mode 100644
index 00000000..a985150b
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuItemJson.java
@@ -0,0 +1,52 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+import java.io.Serializable;
+import java.util.List;
+
+// This type is used to read the Json in from the API call from the Front End
+public class FunctionalMenuItemJson implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ public Long menuId;
+
+ public Integer column;
+
+ public String text;
+
+ public Integer parentMenuId;
+
+ public String url;
+
+ public Integer appid;
+
+ public List<Integer> roles;
+
+ public void normalize() {
+ if (this.column == null)
+ this.column = new Integer(1);
+ this.text = (this.text == null) ? "" : this.text.trim();
+ if (this.parentMenuId == null)
+ this.parentMenuId = new Integer(-1);
+ this.url = (this.url == null) ? "" : this.url.trim();
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuRole.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuRole.java
new file mode 100644
index 00000000..1792477d
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/FunctionalMenuRole.java
@@ -0,0 +1,49 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+import java.io.Serializable;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+@Entity
+@Table(name="fn_menu_functional_roles")
+public class FunctionalMenuRole implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @GeneratedValue(strategy=GenerationType.IDENTITY)
+ @Column(name = "ID")
+ public Integer id;
+
+ @Column(name = "MENU_ID")
+ public Long menuId;
+
+ @Column(name = "APP_ID")
+ public Integer appId;
+
+ @Column(name = "ROLE_ID")
+ public Integer roleId;
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/LocalRole.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/LocalRole.java
new file mode 100644
index 00000000..586a3885
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/LocalRole.java
@@ -0,0 +1,42 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+import java.io.Serializable;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+@Entity
+public class LocalRole implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @Column(name = "ROLE_ID")
+ public Integer roleId;
+
+ @Column(name = "ROLE_NAME")
+ public String rolename;
+
+ public void normalize() {
+ this.rolename = (this.rolename == null) ? "" : this.rolename.trim();
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java
new file mode 100644
index 00000000..fa070b9b
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java
@@ -0,0 +1,83 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+public class OnboardingApp {
+
+ public Long id;
+
+ public String name;
+
+ public String imageUrl;
+
+ public String description;
+
+ public String notes;
+
+ public String url;
+
+ public String alternateUrl;
+
+ public String restUrl;
+
+ public Boolean isOpen;
+
+ public Boolean isEnabled;
+
+ public String username;
+
+ public String appPassword;
+
+ public String thumbnail;
+
+ public String uebTopicName;
+
+ public String uebKey;
+
+ public String uebSecret;
+
+ public Boolean restrictedApp;
+
+ public void normalize() {
+ this.name = (this.name == null) ? "" : this.name.trim();
+ this.username = (this.username == null) ? "" : this.username.trim();
+ this.appPassword = (this.appPassword == null) ? "" : this.appPassword.trim();
+ }
+
+ public void setUebTopicName(String topicName) {
+ this.uebTopicName = topicName;
+ }
+
+ public void setUebKey(String key) {
+ this.uebKey = key;
+ }
+
+ public void setUebSecret(String secret) {
+ this.uebSecret = secret;
+ }
+
+ // Hide the implementation of restricted and normal app from the front end.
+ // The json sent and received will include restrictedApp but not appType.
+
+ public void setRestrictedApp(Boolean restrictedApp) {
+ this.restrictedApp = restrictedApp;
+ }
+}
+
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingWidget.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingWidget.java
new file mode 100644
index 00000000..0a23786f
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingWidget.java
@@ -0,0 +1,65 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+import java.io.Serializable;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+@Entity
+public class OnboardingWidget implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @Column(name = "WIDGET_ID")
+ public Long id;
+
+ @Column(name = "WDG_NAME")
+ public String name;
+
+ @Column(name = "APP_ID")
+ public Long appId;
+
+ @Column(name = "APP_NAME")
+ public String appName;
+
+ @Column(name = "WDG_WIDTH")
+ public Integer width;
+
+ @Column(name = "WDG_HEIGHT")
+ public Integer height;
+
+ @Column(name = "WDG_URL")
+ public String url;
+
+ public void normalize() {
+ this.name = (this.name == null) ? "" : this.name.trim();
+ this.appName = (this.appName == null) ? "" : this.appName.trim();
+ if (this.width == null)
+ this.width = new Integer(0);
+ if (this.height == null)
+ this.height = new Integer(0);
+ this.url = (this.url == null) ? "" : this.url.trim();
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/PortalAdmin.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/PortalAdmin.java
new file mode 100644
index 00000000..ebf20447
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/PortalAdmin.java
@@ -0,0 +1,53 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+import java.io.Serializable;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+/**
+ * This is to handle portal admins
+ */
+@Entity
+@Table(name="fn_user")
+public class PortalAdmin implements Serializable{
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @GeneratedValue(strategy=GenerationType.IDENTITY)
+ @Column(name = "user_id")
+ public Long userId;
+
+ @Column(name = "login_id")
+ public String loginId;
+
+ @Column(name = "first_name")
+ public String firstName;
+
+ @Column(name = "last_name")
+ public String lastName;
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/PortalAdminUserRole.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/PortalAdminUserRole.java
new file mode 100644
index 00000000..23134298
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/PortalAdminUserRole.java
@@ -0,0 +1,48 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+import java.io.Serializable;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+/**
+ * This is to handle portal admins
+ */
+@Entity
+@Table(name="fn_user_role")
+public class PortalAdminUserRole implements Serializable{
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @Column(name = "user_id")
+ public Long userId;
+
+ @Id
+ @Column(name = "role_id")
+ public Long roleId;
+
+ @Column(name = "app_id")
+ public Long appId;
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/RemoteRole.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/RemoteRole.java
new file mode 100644
index 00000000..0e6c4ff0
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/RemoteRole.java
@@ -0,0 +1,28 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+public class RemoteRole {
+
+ public Long id;
+
+ public String name;
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/RemoteUserWithRoles.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/RemoteUserWithRoles.java
new file mode 100644
index 00000000..48456747
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/RemoteUserWithRoles.java
@@ -0,0 +1,63 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * User description which we receive in response from request to remote
+ * application: applicationsRestClientService.get(RemoteUserWithRoles[].class,
+ * appId, "/users"). It contains the most important info about remote
+ * application user including his roles in this application.
+ */
+public class RemoteUserWithRoles {
+
+ public Long orgId;
+
+ public Long managerId;
+
+ public String firstName;
+
+ public String middleInitial;
+
+ public String lastName;
+
+ public String phone;
+
+ public String email;
+
+ public String hrid;
+
+ public String orgUserid;
+
+ public String orgCode;
+
+ public String orgManagerUserId;
+
+ public String jobTitle;
+
+ public String loginId;
+
+ public Boolean active;
+
+ public List<RemoteRole> roles = new ArrayList<RemoteRole>();
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/RoleInAppForUser.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/RoleInAppForUser.java
new file mode 100644
index 00000000..a74614ce
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/RoleInAppForUser.java
@@ -0,0 +1,39 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+public class RoleInAppForUser {
+
+
+ public RoleInAppForUser() {
+ }
+
+ public RoleInAppForUser(Long id, String name) {
+ this.roleId = id;
+ this.roleName = name;
+ }
+
+ public Long roleId;
+
+ public String roleName;
+
+ public Boolean isApplied;
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/RolesInAppForUser.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/RolesInAppForUser.java
new file mode 100644
index 00000000..1c3862db
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/RolesInAppForUser.java
@@ -0,0 +1,33 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class RolesInAppForUser {
+
+ public String orgUserId;
+
+ public Long appId;
+
+ public List<RoleInAppForUser> roles = new ArrayList<RoleInAppForUser>();
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/UserApplicationRoles.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/UserApplicationRoles.java
new file mode 100644
index 00000000..f9fd4138
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/UserApplicationRoles.java
@@ -0,0 +1,41 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * A specific application user and his application specific roles.
+ *
+ */
+public class UserApplicationRoles {
+
+ public Long appId;
+
+ public String orgUserId;
+
+ public String firstName;
+
+ public String lastName;
+
+ public List<RemoteRole> roles = new ArrayList<RemoteRole>();
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/UserWithNameSurnameTitle.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/UserWithNameSurnameTitle.java
new file mode 100644
index 00000000..6c6cc415
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/transport/UserWithNameSurnameTitle.java
@@ -0,0 +1,39 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.transport;
+
+public class UserWithNameSurnameTitle {
+
+ public String orgUserId;
+
+ public String firstName;
+
+ public String lastName;
+
+ public String jobTitle;
+
+ public UserWithNameSurnameTitle(String orgUserId, String firstName, String lastName, String jobTitle) {
+ this.orgUserId = orgUserId;
+ this.firstName = firstName;
+ this.lastName = lastName;
+ this.jobTitle = jobTitle;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java
new file mode 100644
index 00000000..25766997
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java
@@ -0,0 +1,218 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.ueb;
+
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.util.LinkedList;
+import java.util.List;
+
+import javax.annotation.PostConstruct;
+
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.openecomp.portalapp.portal.domain.EPApp;
+import org.openecomp.portalapp.portal.domain.EcompApp;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
+import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
+import org.openecomp.portalapp.portal.service.EPAppService;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiConstants;
+import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiProperties;
+import org.openecomp.portalsdk.core.onboarding.ueb.Helper;
+import org.openecomp.portalsdk.core.onboarding.ueb.Publisher;
+import org.openecomp.portalsdk.core.onboarding.ueb.UebException;
+import org.openecomp.portalsdk.core.onboarding.ueb.UebManager;
+import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Transactional;
+
+@Component
+@Transactional
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+public class EPUebHelper {
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUebHelper.class);
+
+ @Autowired
+ EPAppService appsService;
+
+
+ @Autowired
+ private SessionFactory sessionFactory;
+
+ @SuppressWarnings("unused")
+ private Publisher epPublisher;
+
+ public EPUebHelper() {
+
+ }
+ //
+ // This should only be called by the ECOMP Portal App, other Apps have just one publisher and use appPublisher
+ //
+ @SuppressWarnings("unused")
+ @EPMetricsLog
+ public void refreshPublisherList()
+ {
+ Session localSession = null;
+ boolean addedPublisher = false;
+
+ try {
+ localSession = sessionFactory.openSession();
+
+ List<EcompApp> apps = appsService.getEcompAppAppsFullList();
+ for (int i = 0; i < apps.size(); i++)
+ {
+ if ((apps.get(i).isEnabled()) &&
+ (apps.get(i).getUebTopicName() != null) &&
+ !(apps.get(i).getUebTopicName().toUpperCase().contains("ECOMP-PORTAL-INBOX")))
+ {
+ logger.debug(EELFLoggerDelegate.debugLogger, "UEBManager adding publisher for " + apps.get(i).getUebTopicName());
+ UebManager.getInstance().addPublisher(apps.get(i).getUebTopicName());
+ addedPublisher = true;
+ }
+ else if ((apps.get(i).getId() != 1) && // App may have been disabled, remove the publisher
+ !(apps.get(i).isEnabled()))
+ {
+ if(apps.get(i).getUebTopicName()!=null){
+ UebManager.getInstance().removePublisher(apps.get(i).getUebTopicName());
+ }
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeUebSystemError, "add/remove Publisher");
+ String stackTrace = EcompPortalUtils.getStackTrace(e);
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while refreshing the publisher list. Details: " + stackTrace);
+ }
+
+ //publisherList.print();
+
+ if (addedPublisher == true) // Give publishers time to initialize
+ {
+ Helper.sleep(400);
+ }
+ }
+
+ //@PostConstruct
+ //@EPMetricsLog
+ public void initUeb() {
+ try {
+ epPublisher = new Publisher(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY),
+ PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET),
+ PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME));
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeUebConnectionError, e.getMessage());
+ String stackTrace = EcompPortalUtils.getStackTrace(e);
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while initializing the publisher. Details: " + stackTrace);
+ }
+
+ Thread thread = new Thread("EPUebManager: postConstructMethod - refreshPublisherList") {
+ public void run(){
+ refreshPublisherList();
+ }
+ };
+ if (thread != null) {
+ thread.start();
+ }
+ }
+
+ @EPMetricsLog
+ public void addPublisher(EPApp app) {
+ // TODO Auto-generated method stub
+ try {
+ UebManager.getInstance().addPublisher(app.getUebTopicName());
+ } catch (UebException e) {
+ String stackTrace = EcompPortalUtils.getStackTrace(e);
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception while adding a publisher. Details: " + stackTrace);
+ }
+ }
+
+ public boolean checkAvailability() {
+
+ //
+ // Test existence of topic at UEB url
+ //
+ //
+ //
+ boolean available = true;
+ LinkedList<String> urlList = Helper.uebUrlList();
+ if (!urlList.isEmpty()) {
+ String url = "http://" + urlList.getFirst() + ":3904/topics/" + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME);
+ if (!url.isEmpty()) {
+ try {
+ URL siteURL = new URL(url);
+ HttpURLConnection connection = (HttpURLConnection) siteURL.openConnection();
+ connection.setRequestMethod("GET");
+ connection.connect();
+
+ int code = connection.getResponseCode();
+ if (code == 200) {
+ available = true;
+ }
+ else {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeUebConnectionError, url);
+ available = false;
+ logger.warn(EELFLoggerDelegate.errorLogger, "Warning! UEB topic existence check failed, topic = " + url );
+ logger.debug(EELFLoggerDelegate.debugLogger, "Warning! UEB topic existence check failed, topic = " + url );
+ }
+ }
+ catch (Exception e) {
+ available = false;
+ String stackTrace = EcompPortalUtils.getStackTrace(e);
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing the UEB Healthcheck. Details: " + stackTrace);
+ }
+ }
+ }
+ return available;
+ }
+
+ public boolean MessageCanBeSentToTopic() {
+
+ boolean sentMsgSuccessfully = false;
+
+ UebMsg msg = new UebMsg();
+ msg.putSourceTopicName(PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME));
+ msg.putPayload("Pinging topic for health check");
+ msg.putMsgType(EPUebMsgTypes.UEB_MSG_TYPE_HEALTH_CHECK);
+
+ try {
+ // epPublisher.send(msg);
+ sentMsgSuccessfully = true;
+ }
+ catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeHealthCheckUebClusterError);
+ String stackTrace = EcompPortalUtils.getStackTrace(e);
+ sentMsgSuccessfully = false;
+ logger.warn(EELFLoggerDelegate.errorLogger, "Warning! could not successfully publish a UEB msg to "
+ + PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME) + " exception : " + stackTrace);
+ }
+
+ return sentMsgSuccessfully;
+ }
+
+}
+
+
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebMsgTypes.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebMsgTypes.java
new file mode 100644
index 00000000..5dfd822d
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebMsgTypes.java
@@ -0,0 +1,27 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.ueb;
+
+import org.openecomp.portalsdk.core.onboarding.ueb.UebMsgTypes;
+
+public interface EPUebMsgTypes extends UebMsgTypes {
+
+ public static final String UEB_MSG_TYPE_HEALTH_CHECK = "uebHealthCheckPing";
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/CustomLoggingFilter.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/CustomLoggingFilter.java
new file mode 100644
index 00000000..852779a1
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/CustomLoggingFilter.java
@@ -0,0 +1,60 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.utils;
+
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.filter.Filter;
+import ch.qos.logback.core.spi.FilterReply;
+
+/**
+ * Custom Filter class bind with logback.xml
+ * configuration file to strip out certain log messages
+ * coming out of special packages or classes.
+ *
+ */
+public class CustomLoggingFilter extends Filter<ILoggingEvent> {
+
+ /**
+ * Custom Filter is added to strip out the continuous U-EB logging messages
+ * But make sure we log the ERROR & WARNING Level messages.
+ */
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CustomLoggingFilter.class);
+
+ @Override
+ public FilterReply decide(ILoggingEvent event) {
+ try {
+ if ((event.getLevel() != Level.ERROR || event.getLevel() != Level.WARN) &&
+ (event.getThreadName().equalsIgnoreCase("UEBConsumerThread")) &&
+ (event.getLoggerName().contains("com.att.nsa") || event.getLoggerName().contains("org.apache.http"))
+ ) {
+ return FilterReply.DENY;
+ } else {
+ return FilterReply.NEUTRAL;
+ }
+ } catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ return FilterReply.NEUTRAL;
+ }
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/EPSystemProperties.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/EPSystemProperties.java
new file mode 100644
index 00000000..57eb921f
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/EPSystemProperties.java
@@ -0,0 +1,77 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.utils;
+
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+
+@Configuration
+@PropertySources({
+ @PropertySource ("/WEB-INF/conf/system.properties"),
+ @PropertySource ("/WEB-INF/conf/sql.properties"),
+ @PropertySource ("/WEB-INF/fusion/conf/fusion.properties"),
+ @PropertySource (value = "file:${catalina.home}/conf/system.properties", ignoreResourceNotFound = true),
+ @PropertySource (value = "file:${catalina.home}/conf/fusion.properties", ignoreResourceNotFound = true)
+ })
+
+public class EPSystemProperties extends SystemProperties {
+
+ public static final String LOGIN_URL_NO_RET_VAL = "login_url_no_ret_val";
+ public static final String HOME_PAGE_INDEX_HTML = "home_page";
+ public static final String ECOMP_APP_ID = "ecomp_app_id";
+ public static final String SYS_ADMIN_ROLE_ID = "sys_admin_role_id";
+ public static final String DUBLICATED_FIELD_VALUE_ECOMP_ERROR = "1201";
+ public static final String IDLE_CONNECTION_TEST_PERIOD = "hb.idle_connection_test_period";
+ public static final String DB_RECONNECT = "hb.db_reconnect";
+ public static final String ACCOUNT_ADMIN_ROLE_ID = "account_admin_role_id";
+ public static final String RESTRICTED_APP_ROLE_ID = "restricted_app_role_id";
+ public static final String FE_URL = "frontend_url";
+ public static final String HEALTH_POLL_INTERVAL_SECONDS = "health_poll_interval_seconds";
+ public static final String HEALTHFAIL_ALERT_EVERY_X_INTERVALS = "health_fail_alert_every_x_intervals";
+ public static final String CONTACT_US_URL = "contact_us_link";
+ public static final String USER_GUIDE_URL = "user_guide_link";
+
+ public static final String USER_FIRST_NAME = "USER_FIRST_NAME";
+ public static final String USER_LAST_NAME = "USER_LAST_NAME";
+ public static final String USER_EMAIL = "USER_EMAIL";
+ public static final String USER_ORG_USERID = "USER_ORG_USERID";
+ public static final String USER_LAST_LOGIN = "USER_LAST_LOGIN";
+ public static final String ELASTIC_SEARCH_URL = "elastic_search_url";
+
+ public static final String EXTERNAL_API_RESPONSE_CODE = "External_API_ResponseCode";
+ public static final String COOKIE_DOMAIN = "cookie_domain";
+
+
+ public static final String USH_TICKET_URL = "ush_ticket_url";
+ public static final String FEEDBACK_EMAIL_ADDRESS = "feedback_email_address";
+ public static final String PORTAL_INFO_URL = "portal_info_url";
+
+ public static final String ONLINE_USER_UPDATE_RATE = "online_user_update_rate";
+ public static final String ONLINE_USER_UPDATE_DURATION = "online_user_update_duration";
+
+ public static final String WINDOW_WIDTH_THRESHOLD_LEFT_MENU = "window_width_threshold_left_menu";
+ public static final String WINDOW_WIDTH_THRESHOLD_RIGHT_MENU = "window_width_threshold_right_menu";
+
+ public static final String ECOMP_CONTEXT_ROOT = "context_root";
+
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/EcompPortalUtils.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/EcompPortalUtils.java
new file mode 100644
index 00000000..6ec14511
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/EcompPortalUtils.java
@@ -0,0 +1,248 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.utils;
+
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.servlet.http.HttpServletResponse;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
+import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.slf4j.MDC;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+public class EcompPortalUtils {
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EcompPortalUtils.class);
+
+ /**
+ * @param orgUserId
+ * @return true if orgUserId is not empty and contains only alphanumeric, false otherwise
+ */
+ public static boolean legitimateUserId(String orgUserId) {
+ return orgUserId.matches("^[a-zA-Z0-9]+$");
+ }
+
+ public static List<String> parsingByRegularExpression(String source, String regex) {
+ List<String> tokens = new ArrayList<String>();
+ if (source != null && source.length() > 0) {
+ String[] parsed = source.split(regex);
+ for (String token : parsed) {
+ if (token.length() > 0) {
+ tokens.add(token);
+ }
+ }
+ }
+ return tokens;
+ }
+
+ public static String jsonErrorMessageResponse(int errorCode, String errorMessage) {
+ return "{\"error\":{\"code\":" + errorCode + "," + "\"message\":\"" + errorMessage + "\"}}";
+ }
+
+ public static String jsonMessageResponse(String message) {
+ return String.format("{\"message\":\"%s\"}", message);
+ }
+
+ public static void logAndSerializeObject(String source, String msg, Object obj) {
+ try {
+ String objectAsJson = new ObjectMapper().writeValueAsString(obj);
+ logger.debug(EELFLoggerDelegate.debugLogger, String.format("source= [%s]; %s [%s];", source, msg, objectAsJson));
+ } catch (JsonProcessingException e) {
+ logger.warn(EELFLoggerDelegate.errorLogger, "JsonProcessingException occurred while parsing the response, Details:" + EcompPortalUtils.getStackTrace(e));
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput);
+ } catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while parsing the response, Details:" + EcompPortalUtils.getStackTrace(e));
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput);
+ }
+ }
+
+ public static void rollbackTransaction(Transaction transaction, String errorMessage) {
+ logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
+ try {
+ if(transaction != null) {
+ transaction.rollback();
+ }
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeExecuteRollbackError);
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing a rollback transaction, Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+ }
+
+ public static void closeLocalSession(Session localSession, String errorMessage) {
+ logger.error(EELFLoggerDelegate.errorLogger, errorMessage);
+ try {
+ if(localSession != null) {
+ localSession.close();
+ }
+ } catch (Exception e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoCloseSessionError);
+ logger.error(EELFLoggerDelegate.errorLogger, errorMessage + ", closeLocalSession exception: " + EcompPortalUtils.getStackTrace(e));
+ }
+ }
+
+ // TODO: GLOBAL_LOGIN_URL is the same as in SessionTimeoutInterceptor.
+ // It should be defined in SystemProperties.
+ private static final String GLOBAL_LOGIN_URL = "global-login-url";
+
+ /**
+ * Set response status to Unauthorized if user == null and to Forbidden in all (!) other cases.
+ * Logging is not performed if invocator == null
+ * @param user
+ * @param response
+ * @param invocator - may be null
+ */
+ public static void setBadPermissions(EPUser user, HttpServletResponse response, String invocator) {
+ if (user == null) {
+ String loginUrl = SystemProperties.getProperty(EPSystemProperties.LOGIN_URL_NO_RET_VAL);
+ response.setHeader(GLOBAL_LOGIN_URL, loginUrl);
+ response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+ MDC.put(EPSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_UNAUTHORIZED));
+ } else {
+ response.setStatus(HttpServletResponse.SC_FORBIDDEN);
+ MDC.put(EPSystemProperties.RESPONSE_CODE, Integer.toString(HttpServletResponse.SC_FORBIDDEN));
+ }
+ if (invocator != null) {
+ logger.warn(EELFLoggerDelegate.errorLogger, invocator + ", permissions problem, response status = " + response.getStatus());
+ }
+ }
+
+ public static int getExternalAppResponseCode() {
+ String responseCode = MDC.get(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE);
+ int responseCodeInt = 0;
+ try {
+ if (responseCode != null && responseCode != "") {
+ responseCodeInt = Integer.valueOf(responseCode);
+ }
+ } catch (Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in getResponseCode(). Details: "+EcompPortalUtils.getStackTrace(e));
+ }
+ return responseCodeInt;
+ }
+
+ // This method might be just for testing purposes.
+ public static void setExternalAppResponseCode(int responseCode) {
+ try {
+ String responseCodeString = String.valueOf(responseCode);
+ MDC.put(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE, responseCodeString);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in setResponseCode(). Details: "+EcompPortalUtils.getStackTrace(e));
+ }
+ }
+
+ public static String getHTTPStatusString(int httpStatusCode) {
+ String httpStatusString = "unknown_error";
+ try {
+ httpStatusString = org.springframework.http.HttpStatus.valueOf(httpStatusCode).name();
+ if (httpStatusString != null) {
+ httpStatusString = httpStatusString.toLowerCase();
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in getHTTPStatusString(). Details: "+EcompPortalUtils.getStackTrace(e));
+ }
+ return httpStatusString;
+ }
+
+ public static String getFEErrorString(Boolean internal, int responseCode) {
+ // Return a String like the following:
+ // "Internal Ecomp Error: 500 internal_server_error" or
+ // "External App Error: 404 not_found"
+ // TODO: create our own Ecomp error codes, starting with 1000 and up.
+ String responseString = "";
+ String internalExternalString = internal ? "Ecomp Error: " : "App Error: ";
+ String httpStatusString = "unknown_error";
+ try {
+ if (responseCode < 1000) {
+ httpStatusString = getHTTPStatusString(responseCode);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in getFEErrorString(). Details: "+EcompPortalUtils.getStackTrace(e));
+ }
+ responseString = internalExternalString + responseCode + " " + httpStatusString;
+ return responseString;
+ }
+
+ public static boolean isProductionBuild()
+ {
+ boolean productionBuild = true;
+ String epVersion = EcompVersion.buildNumber;
+ if (epVersion != null)
+ {
+ int buildNum = epVersion.lastIndexOf('.');
+ if (buildNum > 0)
+ {
+ int buildNumber = Integer.parseInt(epVersion.substring(buildNum+1));
+ if (buildNumber < 3000) // Production versions are 3000+, (ie 1.0.3003)
+ {
+ productionBuild = false;
+ }
+ }
+ }
+ return productionBuild;
+ }
+
+ private static final Object stackTraceLock = new Object();
+ public static String getStackTrace(Throwable t) {
+ synchronized(stackTraceLock) {
+ StringWriter sw = new StringWriter ();
+ PrintWriter pw = new PrintWriter (sw);
+ t.printStackTrace (pw);
+ return sw.toString ();
+ }
+ }
+
+ public static String getMyIpAdddress() {
+ InetAddress ip;
+ String localIp;
+ try {
+ ip = InetAddress.getLocalHost();
+ localIp = ip.getHostAddress();
+ } catch (UnknownHostException e) {
+ localIp = "unknown";
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+ return localIp;
+ }
+
+ public static String getMyHostName() {
+ InetAddress ip;
+ String hostName;
+ try {
+ ip = InetAddress.getLocalHost();
+ hostName = ip.getHostName();
+ } catch (UnknownHostException e) {
+ hostName = "unknown";
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+ return hostName;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/EcompVersion.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/EcompVersion.java
new file mode 100644
index 00000000..595ae24f
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/EcompVersion.java
@@ -0,0 +1,33 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.utils;
+
+//
+// Hardcoded for now, wanted to use maven and resource file. Possibly just read
+// pom.properties file with version added, but spent several hours already running
+// into issues with that and other ideas not working. So, for 1604 deadlines I
+// am just putting the version in the code here... for now.
+//
+public final class EcompVersion {
+
+ // TODO - not used - manifest service reads from manifest
+ public static final String buildNumber="1610.1.999";
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/HashMapFromList.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/HashMapFromList.java
new file mode 100644
index 00000000..c9a55328
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/HashMapFromList.java
@@ -0,0 +1,100 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.utils;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.List;
+
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+/**
+ *
+ * @author Vladimir Turovets This class is used to create HashMap<String, T>
+ * from the list of T objects. We suppose that
+ * 1) T object contains field 'parmName' or getter 'getParmName()'.
+ * The value of object.parmName or object.getParmName() is used as
+ * a key in created hashMap.
+ * 2) for all objects in the list 'parmName' or getter
+ * 'getParmName().toString' has to be unique and not null.
+ * This class has one function only:
+ * HashMap<String, T> hashMap(List<T> list, String name) and returns
+ * hash map created from list.
+ *
+ * @param <T>
+ */
+public class HashMapFromList<T> {
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HashMapFromList.class);
+
+ public HashMap<String, T> hashMap(List<T> list, String name) {
+ HashMap<String, T> result = new HashMap<String, T>();
+ if (list == null || list.size() == 0 || name == null) {
+ return result;
+ }
+ name = name.trim();
+ if (name.length() > 0) {
+ T object = list.get(0);
+ try {
+ String parmName = name;
+ Field field = object.getClass().getField(parmName);
+ for (T obj : list) {
+ try {
+ Object o = field.get(obj);
+ if (o != null)
+ result.put(o.toString(), obj);
+ } catch (Exception e1) {
+ String stackTrace = EcompPortalUtils.getStackTrace(e1);
+ logger.error(EELFLoggerDelegate.errorLogger, "Object of class " + object.getClass().getName() + ", field " + parmName + ". Details: ", stackTrace);
+ return new HashMap<String, T>();
+ }
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ String getterName = "get" + (name.length() == 1 ? name.toUpperCase() : (name.substring(0, 1).toUpperCase() + name.substring(1)));
+ try {
+ Class<?>[] parmClasses = null;
+ Method method = object.getClass().getMethod(getterName, parmClasses);
+ Object[] parmValues = new Object[0];
+ for (T obj : list) {
+ try {
+ Object o = method.invoke(obj, parmValues);
+ if (o != null)
+ result.put(o.toString(), obj);
+ } catch (Exception e2) {
+ String stackTrace = EcompPortalUtils.getStackTrace(e2);
+ logger.error(EELFLoggerDelegate.errorLogger, "Object of class " + object.getClass().getName() + ", method " + getterName + ". Details: ", stackTrace);
+ return new HashMap<String, T>();
+ }
+ }
+ } catch (Exception e3) {
+ String stackTrace = EcompPortalUtils.getStackTrace(e3);
+ logger.error(EELFLoggerDelegate.errorLogger, "Object of class " + object.getClass().getName() + ", bad field '" + name + "' or method '" + getterName + "()'. Details: " + stackTrace);
+ return new HashMap<String, T>();
+ }
+ }
+ }
+ if (list.size() != result.size()) {
+ logger.warn(EELFLoggerDelegate.errorLogger, "Duplicated or empty keys were found!!!");
+ }
+ return result;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/ParallelExecutor.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/ParallelExecutor.java
new file mode 100644
index 00000000..19b3fc8c
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/portal/utils/ParallelExecutor.java
@@ -0,0 +1,83 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.portal.utils;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+
+public abstract class ParallelExecutor<T> {
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ParallelExecutor.class);
+
+ protected static abstract class ThreadOperation<T> {
+ public abstract T execute(List<Object> parms);
+ }
+
+ protected abstract ThreadOperation<T> getThreadOperation();
+
+ private static class CallableOperationThread<T> implements Callable<T> {
+
+ List<Object> parms;
+
+ private ThreadOperation<T> operation;
+
+ public CallableOperationThread(ThreadOperation<T> operation, List<Object> parms) {
+ this.parms = parms;
+ this.operation = operation;
+ }
+
+ @Override
+ public T call() throws Exception {
+ return this.operation.execute(this.parms);
+ }
+
+ }
+
+ public List<T> performAllOperations(int ThreadPoolSize, List<List<Object>> listOfParms) {
+ List<T> result = new ArrayList<T>();
+ if (ThreadPoolSize > 0 && listOfParms != null) {
+ ExecutorService executor = Executors.newFixedThreadPool(ThreadPoolSize);
+ List<Future<T>> list = new ArrayList<Future<T>>();
+ for (List<Object> parms : listOfParms) {
+ CallableOperationThread<T> getter = new CallableOperationThread<T>(this.getThreadOperation(), parms);
+ Future<T> submit = executor.submit(getter);
+ list.add(submit);
+ }
+ for (Future<T> future : list) {
+ try {
+ if (future != null) {
+ result.add(future.get());
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ }
+ }
+ executor.shutdown();
+ }
+ return result;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/scheduler/LogJob.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/scheduler/LogJob.java
new file mode 100644
index 00000000..7e1ad889
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/scheduler/LogJob.java
@@ -0,0 +1,45 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.scheduler;
+
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.quartz.DisallowConcurrentExecution;
+import org.quartz.JobExecutionContext;
+import org.quartz.JobExecutionException;
+import org.quartz.PersistJobDataAfterExecution;
+import org.springframework.scheduling.quartz.QuartzJobBean;
+
+@PersistJobDataAfterExecution
+@DisallowConcurrentExecution
+public class LogJob extends QuartzJobBean {
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LogJob.class);
+
+ @Override
+ protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException {
+ // JobDataMap dataMap = ctx.getJobDetail().getJobDataMap();
+ // int cnt = dataMap.getInt("");
+ // JobKey jobKey = ctx.getJobDetail().getKey();
+ logger.info(EELFLoggerDelegate.debugLogger,
+ (Runtime.getRuntime().maxMemory() + " " + Runtime.getRuntime().maxMemory()));
+
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/scheduler/LogRegistry.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/scheduler/LogRegistry.java
new file mode 100644
index 00000000..9b34c87a
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/scheduler/LogRegistry.java
@@ -0,0 +1,57 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.scheduler;
+
+import java.text.ParseException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.portalsdk.core.scheduler.CronRegistry;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.context.annotation.DependsOn;
+import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
+import org.springframework.scheduling.quartz.JobDetailFactoryBean;
+import org.springframework.stereotype.Component;
+
+@Component
+@DependsOn({ "systemProperties" })
+public class LogRegistry extends CronRegistry {
+
+ private static final String groupName = "AppGroup";
+ private static final String jobName = "LogJob";
+ private static final String triggerName = "LogTrigger";
+
+ // @Autowired
+ // private SystemProperties systemProperties;
+
+ // @Bean
+ public JobDetailFactoryBean jobDetailFactoryBean() {
+ Map<String, Object> map = new HashMap<String, Object>();
+ map.put("units", "bytes");
+ return jobDetailFactoryBean(groupName, jobName, LogJob.class, map);
+ }
+
+ // @Bean
+ public CronTriggerFactoryBean cronTriggerFactoryBean() throws ParseException {
+ // "0 * * * * ? *
+ return cronTriggerFactoryBean(groupName, triggerName, SystemProperties.getProperty(SystemProperties.LOG_CRON));
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/scheduler/Register.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/scheduler/Register.java
new file mode 100644
index 00000000..c09721c6
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/scheduler/Register.java
@@ -0,0 +1,86 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.scheduler;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.scheduler.Registerable;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.quartz.Trigger;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.DependsOn;
+import org.springframework.stereotype.Component;
+
+@Component
+@DependsOn({"logRegistry", "sessionMgtRegistry", "systemProperties"})
+public class Register implements Registerable {
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(Register.class);
+
+ private List<Trigger> scheduleTriggers = new ArrayList<Trigger>();
+ Trigger trigger[] = new Trigger[0];
+
+ @Autowired
+ private LogRegistry logRegistry;
+
+ @Autowired
+ private SessionMgtRegistry sessionMgtRegistry;
+
+ @Override
+ public Trigger[] getTriggers() {
+ return getScheduleTriggers().toArray(trigger);
+ }
+
+ @Override
+ public void registerTriggers() {
+ // if the property value is not available; the cron will not be added
+ // and can be ignored. its safe to ignore the exceptions
+ try {
+ if (SystemProperties.getProperty(SystemProperties.LOG_CRON) != null)
+ getScheduleTriggers().add(logRegistry.getTrigger());
+
+ } catch (IllegalStateException ies) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(ies));
+ logger.info(EELFLoggerDelegate.debugLogger, ("Log Cron not available"));
+ }
+
+ try {
+ if(SystemProperties.getProperty(SystemProperties.SESSIONTIMEOUT_FEED_CRON) != null)
+ getScheduleTriggers().add(sessionMgtRegistry.getTrigger());
+
+ } catch(IllegalStateException ies) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(ies));
+ logger.info(EELFLoggerDelegate.debugLogger, ("Session Cron not available"));
+ }
+
+ }
+
+ public List<Trigger> getScheduleTriggers() {
+ return scheduleTriggers;
+ }
+
+ public void setScheduleTriggers(List<Trigger> scheduleTriggers) {
+ this.scheduleTriggers = scheduleTriggers;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/scheduler/RegistryAdapter.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/scheduler/RegistryAdapter.java
new file mode 100644
index 00000000..b26df58b
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/scheduler/RegistryAdapter.java
@@ -0,0 +1,100 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.scheduler;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.openecomp.portalsdk.core.scheduler.Registerable;
+import org.openecomp.portalsdk.workflow.services.WorkflowScheduleService;
+import org.quartz.Trigger;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.scheduling.quartz.SchedulerFactoryBean;
+import org.springframework.stereotype.Component;
+
+/**
+ * TODO REFACTOR moved from org.openecomp.portalsdk.core.scheduler to
+ * org.openecomp.portalapp.scheduler
+ *
+ */
+@Component
+public class RegistryAdapter {
+
+ @Autowired
+ private Registerable registry;
+
+ @Autowired
+ private WorkflowScheduleService workflowScheduleService;
+
+ private SchedulerFactoryBean schedulerBean;
+
+ Trigger trigger[] = new Trigger[0];
+
+ public Trigger[] getTriggers() {
+
+ registry.registerTriggers();
+
+ List<Trigger> allTriggers = new ArrayList<Trigger>();
+
+ List<Trigger> coreTriggers = addCoreTriggers();
+ final Trigger[] extTriggerArray = registry.getTriggers();
+
+ allTriggers.addAll(Arrays.asList(extTriggerArray));
+ allTriggers.addAll(coreTriggers);
+
+ return allTriggers.toArray(trigger);
+
+ }
+
+ public List<Trigger> addCoreTriggers() {
+ // On startup of the application after crash recovery, invoke workflow
+ // schedule trigger
+ List<Trigger> triggers = getWorkflowScheduleService().triggerWorkflowScheduling();
+ return triggers;
+ }
+
+ public void setSchedulerBean(SchedulerFactoryBean _schedulerBean) {
+ schedulerBean = _schedulerBean;
+
+ }
+
+ public SchedulerFactoryBean getSchedulerBean() {
+ return schedulerBean;
+
+ }
+
+ public Registerable getRegistry() {
+ return registry;
+ }
+
+ public void setRegistry(Registerable registry) {
+ this.registry = registry;
+ }
+
+ public WorkflowScheduleService getWorkflowScheduleService() {
+ return workflowScheduleService;
+ }
+
+ public void setWorkflowScheduleService(WorkflowScheduleService workflowScheduleService) {
+ this.workflowScheduleService = workflowScheduleService;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/scheduler/SessionMgtRegistry.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/scheduler/SessionMgtRegistry.java
new file mode 100644
index 00000000..177b4299
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/scheduler/SessionMgtRegistry.java
@@ -0,0 +1,89 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.scheduler;
+
+import java.text.ParseException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.portalapp.portal.listener.UserSessionListener;
+import org.openecomp.portalapp.service.sessionmgt.TimeoutHandler;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.scheduler.CronRegistry;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
+import org.springframework.context.annotation.DependsOn;
+import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
+import org.springframework.scheduling.quartz.JobDetailFactoryBean;
+import org.springframework.stereotype.Component;
+
+/**
+ * Extra depends-on annotation tells Spring that the system properties object
+ * will be used in the constructor.
+ */
+@Component
+// @DependsOn({ "manageService", "epAppService", "systemProperties" })
+@DependsOn({ "systemProperties" })
+public class SessionMgtRegistry extends CronRegistry implements ApplicationContextAware {
+
+ EELFLoggerDelegate logger = null;
+
+ private static final String groupName = "AppGroup";
+ private static final String jobName = "PortalSessionTimeoutFeedJob";
+ private static final String triggerName = "PortalSessionTimeoutFeedTrigger";
+
+ // Not strictly necessary, but preparing for the day
+ // when the getProperty method is not static.
+ @Autowired
+ private SystemProperties systemProperties;
+
+ private ApplicationContext applicationContext;
+
+ public JobDetailFactoryBean jobDetailFactoryBean() {
+ logger = EELFLoggerDelegate.getLogger(SessionMgtRegistry.class);
+ Map<String, Object> map = new HashMap<String, Object>();
+ return jobDetailFactoryBean(groupName, jobName, TimeoutHandler.class, map);
+ }
+
+ @SuppressWarnings("static-access")
+ public CronTriggerFactoryBean cronTriggerFactoryBean() throws ParseException {
+ logger = EELFLoggerDelegate.getLogger(SessionMgtRegistry.class);
+ String property = "* * * * * ? 2099";
+ try {
+ property = systemProperties.getProperty(SystemProperties.SESSIONTIMEOUT_FEED_CRON);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "Failed to retrieve " + SystemProperties.SESSIONTIMEOUT_FEED_CRON + ", defaulting to " + property,
+ e);
+ }
+ return cronTriggerFactoryBean(groupName, triggerName, property);
+ }
+
+ @Override
+ public void setApplicationContext(ApplicationContext _applicationContext) throws BeansException {
+ applicationContext = _applicationContext;
+ TimeoutHandler.setApplicationContext(applicationContext);
+ UserSessionListener.setApplicationContext(_applicationContext);
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/AdminAuthExtension.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/AdminAuthExtension.java
new file mode 100644
index 00000000..2432061e
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/AdminAuthExtension.java
@@ -0,0 +1,35 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.service;
+
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+
+@Service("adminAuthExtension")
+@Transactional
+public class AdminAuthExtension {
+
+ public void saveUserExtension(EPUser user){
+ //app's developer implement their own logic here, like updating app's related tables
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/EPProfileService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/EPProfileService.java
new file mode 100644
index 00000000..98415662
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/EPProfileService.java
@@ -0,0 +1,36 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.service;
+
+import java.util.List;
+
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalsdk.core.domain.Profile;
+
+
+public interface EPProfileService {
+ List<Profile> findAll();
+
+ Profile getProfile(int id);
+
+ EPUser getUser(String id);
+
+ void saveUser(EPUser user);
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/EPProfileServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/EPProfileServiceImpl.java
new file mode 100644
index 00000000..9dcc8dc9
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/EPProfileServiceImpl.java
@@ -0,0 +1,76 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.service;
+
+import java.util.List;
+
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalsdk.core.dao.ProfileDao;
+import org.openecomp.portalsdk.core.domain.Profile;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.service.DataAccessService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service("epProfileService")
+@Transactional
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class EPProfileServiceImpl implements EPProfileService {
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPProfileServiceImpl.class);
+
+ @Autowired
+ private ProfileDao profileDao;
+
+ @Autowired
+ private DataAccessService dataAccessService;
+
+ @SuppressWarnings("unchecked")
+ public List<Profile> findAll() {
+ // List msgDB = getDataAccessService().getList(Profile.class, null);
+ return getDataAccessService().getList(Profile.class, null);
+ }
+
+ public EPUser getUser(String userId) {
+ return (EPUser) getDataAccessService().getDomainObject(EPUser.class, Long.parseLong(userId), null);
+ }
+
+ public void saveUser(EPUser user) {
+
+ getDataAccessService().saveDomainObject(user, null);
+ }
+
+ public Profile getProfile(int id) {
+ return profileDao.getProfile(id);
+ }
+
+ public DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ this.dataAccessService = dataAccessService;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/CoreTimeoutHandler.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/CoreTimeoutHandler.java
new file mode 100644
index 00000000..dace543c
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/CoreTimeoutHandler.java
@@ -0,0 +1,166 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.service.sessionmgt;
+
+import java.util.Calendar;
+import java.util.Hashtable;
+import java.util.Map;
+
+import javax.servlet.http.HttpSession;
+
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.domain.sessionmgt.TimeoutVO;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiConstants;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+
+@Service
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class CoreTimeoutHandler{
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CoreTimeoutHandler.class);
+
+ public static final Map<String, HttpSession> sessionMap = new Hashtable<String,HttpSession>();
+ public static final Integer repeatInterval = 15 * 60; // 15 minutes
+ ObjectMapper mapper = new ObjectMapper();
+
+
+ public static void sessionCreated(String portalJSessionId, String jSessionId, HttpSession session) {
+
+ storeMaxInactiveTime(session);
+
+ // this key is a combination of portal jsession id and app session id
+ session.setAttribute(PortalApiConstants.PORTAL_JSESSION_ID,jSessionKey(jSessionId, portalJSessionId));
+ sessionMap.put((String)session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID), session);
+
+ }
+
+ protected static void storeMaxInactiveTime(HttpSession session) {
+
+ if(session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME) == null)
+ session.setAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME,session.getMaxInactiveInterval());
+ }
+
+ public static void sessionDestroyed(HttpSession session) {
+
+ try{
+ sessionMap.remove((String)session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID));
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "************************ Session Management: Error while destroying session for " + session.getId() + " Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+
+ }
+
+ public String gatherSessionExtenstions() {
+
+ Map<String,TimeoutVO> sessionTimeoutMap = new Hashtable<String,TimeoutVO>();
+ String jsonMap = "";
+
+
+ for(String jSessionKey: sessionMap.keySet()) {
+
+ try{
+ // get the expirytime in seconds
+ HttpSession session = sessionMap.get(jSessionKey);
+
+ Long lastAccessedTimeMilliSec = session.getLastAccessedTime();
+ Long maxIntervalMilliSec = session.getMaxInactiveInterval() * 1000L;
+ //Long currentTimeMilliSec = Calendar.getInstance().getTimeInMillis() ;
+ //(maxIntervalMilliSec - (currentTimeMilliSec - lastAccessedTimeMilliSec) + ;
+ Calendar instance = Calendar.getInstance();
+ instance.setTimeInMillis(session.getLastAccessedTime());
+ logger.info(EELFLoggerDelegate.errorLogger, "************************ Session Management: Last Accessed time for "+ jSessionKey + ": " + instance.getTime());
+
+ Long sessionTimOutMilliSec = maxIntervalMilliSec + lastAccessedTimeMilliSec;
+
+ sessionTimeoutMap.put( portalJSessionId(jSessionKey), new TimeoutVO(jSessionId(jSessionKey),sessionTimOutMilliSec));
+
+
+ jsonMap = mapper.writeValueAsString(sessionTimeoutMap);
+ } catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "************************ Session Management: Error during JsonSessionTimout conversion. Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+ }
+
+ return jsonMap;
+
+ }
+
+
+ public void updateSessionExtensions(String sessionTimeoutMapStr) throws Exception {
+
+ //Map<String,Object> sessionTimeoutMap = mapper.readValue(sessionTimeoutMapStr, Map.class);
+ Map<String,TimeoutVO> sessionTimeoutMap;
+ try{
+ TypeReference<Hashtable<String,TimeoutVO>> typeRef
+ = new TypeReference<Hashtable<String,TimeoutVO>>() {};
+
+ sessionTimeoutMap = mapper.readValue(sessionTimeoutMapStr, typeRef);
+ }catch(Exception e){
+ logger.error(EELFLoggerDelegate.errorLogger, "************************ Session Management: Error while to parse update session extension in portal", e);
+ return;
+ }
+ for(String jPortalSessionId: sessionTimeoutMap.keySet()) {
+ try {
+
+ TimeoutVO extendedTimeoutVO = mapper.readValue(mapper.writeValueAsString(sessionTimeoutMap.get(jPortalSessionId)),TimeoutVO.class);
+ HttpSession session = sessionMap.get(jSessionKey(extendedTimeoutVO.getjSessionId(), jPortalSessionId));
+
+ if(session == null) {
+ continue;
+ }
+
+ Long lastAccessedTimeMilliSec = session.getLastAccessedTime();
+ Long maxIntervalMilliSec = session.getMaxInactiveInterval() * 1000L;
+ Long sessionTimOutMilliSec = maxIntervalMilliSec + lastAccessedTimeMilliSec;
+
+ Long maxTimeoutTimeMilliSec = extendedTimeoutVO.getSessionTimOutMilliSec();
+ if(maxTimeoutTimeMilliSec>sessionTimOutMilliSec) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "************************ Session Management: " + " updated session max idle time");
+ session.setMaxInactiveInterval((int)(maxTimeoutTimeMilliSec-lastAccessedTimeMilliSec)/1000);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "************************ Session Management: " + EcompPortalUtils.getStackTrace(e));
+ }
+
+ }
+
+ }
+
+ protected static String jSessionKey(String jSessionId, String portalJSessionId) {
+ return portalJSessionId + "-" + jSessionId;
+ }
+
+ protected String portalJSessionId(String jSessionKey) {
+ return jSessionKey.split("-")[0];
+ }
+
+ protected String jSessionId(String jSessionKey) {
+ return jSessionKey.split("-")[1];
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/ManageService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/ManageService.java
new file mode 100644
index 00000000..a485176f
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/ManageService.java
@@ -0,0 +1,101 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.service.sessionmgt;
+
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.service.EPAppService;
+import org.openecomp.portalapp.portal.transport.OnboardingApp;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.onboarding.crossapi.PortalTimeoutHandler;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.quartz.CronExpression;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+import org.springframework.util.StringUtils;
+
+@Service("manageService")
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class ManageService implements PortalTimeoutHandler.SessionCommInf {
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ManageService.class);
+
+ @Autowired
+ EPAppService appService;
+
+ @Autowired
+ SessionCommunication sessionCommunication;
+
+ public Integer fetchSessionSlotCheckInterval(String... params) throws Exception {
+
+ String defaultCronExpressionStr = "0 0/5 * * * ? *";
+ String cronExpressionStr = SystemProperties.getProperty(SystemProperties.SESSIONTIMEOUT_FEED_CRON);
+
+ if (cronExpressionStr == null) {
+ cronExpressionStr = defaultCronExpressionStr;
+ }
+
+ CronExpression cal = new CronExpression(cronExpressionStr);
+ final Date nowTime = Calendar.getInstance().getTime();
+ Date nextTime = cal.getNextValidTimeAfter(nowTime);
+ Date nextNextTime = cal.getNextValidTimeAfter(nextTime);
+
+ final int timeDiff = (int)(nextNextTime.getTime()-nextTime.getTime());
+ logger.debug(EELFLoggerDelegate.debugLogger, "Time interval between subsequent session checks " + timeDiff);
+
+ return timeDiff;
+ }
+
+ public void extendSessionTimeOuts(String... params) throws Exception {
+ try {
+ String sessionMap = params[3];
+
+ logger.debug(EELFLoggerDelegate.debugLogger, "Extending the App sessions for last minute request: " + sessionMap);
+
+ if (StringUtils.isEmpty(sessionMap)) {
+ logger.error(EELFLoggerDelegate.errorLogger, "extendSessionTimeOuts: Skipping session updates since the portal session value is empty.");
+ } else {
+ List<OnboardingApp> appList = appService.getEnabledNonOpenOnboardingApps();
+ for (OnboardingApp onApp : appList) {
+ sessionCommunication.pingSession(onApp, sessionMap);
+ }
+ updateSessionExtensions(sessionMap);
+ sessionCommunication.clear(false);
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred in extendSessionTimeOuts(). Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+ }
+
+ public String gatherSessionExtenstions() {
+ return PortalTimeoutHandler.gatherSessionExtensions();
+ }
+
+ public void updateSessionExtensions(String sessionTimeoutMapStr) throws Exception {
+ PortalTimeoutHandler.updateSessionExtensions(sessionTimeoutMapStr);
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/RemoteWebServiceCallService.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/RemoteWebServiceCallService.java
new file mode 100644
index 00000000..15693a60
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/RemoteWebServiceCallService.java
@@ -0,0 +1,44 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.service.sessionmgt;
+
+public interface RemoteWebServiceCallService {
+
+ /**
+ * Answers whether the specified credentials match application information
+ * in the database.
+ *
+ * @param secretKey
+ * Key used to decrypt passwords; ignored if null.
+ * @param requestUebKey
+ * UEB key that identifies the application
+ * @param requesUserName
+ * User name for the application
+ * @param requestPassword
+ * Password for the application
+ * @return True if the UEB key and the credentials match the database
+ * entries; else false.
+ * @throws Exception
+ * If decryption fails.
+ */
+ public boolean verifyRESTCredential(String secretKey, String requestUebKey, String requestUserName,
+ String requestPassword) throws Exception;
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/RemoteWebServiceCallServiceImpl.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/RemoteWebServiceCallServiceImpl.java
new file mode 100644
index 00000000..e2b2dd5d
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/RemoteWebServiceCallServiceImpl.java
@@ -0,0 +1,83 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.service.sessionmgt;
+
+import java.util.List;
+
+import org.openecomp.portalapp.portal.domain.EPApp;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.service.WebServiceCallServiceImpl;
+import org.openecomp.portalsdk.core.util.CipherUtil;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service("remoteWebServiceCallService")
+@Transactional
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class RemoteWebServiceCallServiceImpl extends WebServiceCallServiceImpl implements RemoteWebServiceCallService {
+
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RemoteWebServiceCallServiceImpl.class);
+
+ /*
+ * (non-Javadoc)
+ * @see org.openecomp.portalapp.service.sessionmgt.RemoteWebServiceCallService#verifyRESTCredential(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
+ */
+ public boolean verifyRESTCredential(String secretKey, String requestUebKey, String requestAppName,
+ String requestPassword) throws Exception {
+ EPApp appRecord = findEpApp(requestUebKey);
+ if (appRecord == null) {
+ logger.warn(EELFLoggerDelegate.errorLogger, "Failed to find application with UEB key " + requestUebKey);
+ return false;
+ }
+
+ String encryptedPwdDB = appRecord.getAppPassword();
+ String appUserName = appRecord.getUsername();
+ String decryptedPwd = CipherUtil.decrypt(encryptedPwdDB,
+ secretKey == null ? SystemProperties.getProperty(SystemProperties.Decryption_Key) : secretKey);
+ if (decryptedPwd.equals(requestPassword) && appUserName.equals(requestAppName))
+ return true;
+ else
+ return false;
+ }
+
+ /**
+ * Searches the FN_APP table for the specified UEB key.
+ *
+ * @return EPApp object if the key is found; else null.
+ */
+ public EPApp findEpApp(String uebKey) {
+ List<?> list = null;
+ StringBuffer criteria = new StringBuffer();
+ criteria.append(" where ueb_key = '" + uebKey + "'");
+ list = getDataAccessService().getList(EPApp.class, criteria.toString(), null, null);
+ return (list == null || list.size() == 0) ? null : (EPApp) list.get(0);
+ }
+
+ public static void main(String args[]) throws Exception {
+ String decryptedPwd = CipherUtil.decrypt("okYTaDrhzibcbGVq5mjkVQ==", "AGLDdG4D04BKm2IxIWEr8o==");
+ System.out.print(decryptedPwd);
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/SessionCommunication.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/SessionCommunication.java
new file mode 100644
index 00000000..57fdd8a0
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/SessionCommunication.java
@@ -0,0 +1,274 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.service.sessionmgt;
+
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.util.UUID;
+
+import javax.servlet.http.HttpServletResponse;
+
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
+import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
+import org.openecomp.portalapp.portal.transport.OnboardingApp;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.exception.UrlAccessRestrictedException;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.slf4j.MDC;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.stereotype.Service;
+import org.springframework.util.StringUtils;
+
+import com.att.eelf.configuration.Configuration;
+
+@Service("sessionCommunication")
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+public class SessionCommunication {
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SessionCommunication.class);
+
+ @EPAuditLog
+ public String sendGet(OnboardingApp app) throws Exception {
+ String appResponse = "";
+ String appName = "Unknwon";
+ int responseCode = 0;
+
+ try {
+ if (app != null && app.name != null && app.name != "") {
+ appName = app.name;
+ }
+ String url = app.restUrl + "/sessionTimeOuts";
+ String encriptedPwdDB = app.appPassword;
+ String appUserName = app.username;
+
+ setLocalMDCContext(app, "/sessionTimeOuts", url);
+
+ URL obj = new URL(url);
+
+ HttpURLConnection con = (HttpURLConnection) obj.openConnection();
+
+ // optional default is GET
+ con.setRequestMethod("GET");
+ con.setConnectTimeout(3000);
+ con.setReadTimeout(8000);
+ // add request header
+ con.setRequestProperty("username", appUserName);
+ con.setRequestProperty("password", encriptedPwdDB);
+
+ // con.set
+ responseCode = con.getResponseCode();
+ logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
+
+ BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
+ String inputLine;
+ StringBuffer response = new StringBuffer();
+
+ while ((inputLine = in.readLine()) != null) {
+ response.append(inputLine);
+ }
+
+ in.close();
+ appResponse = response.toString();
+ } catch (UrlAccessRestrictedException e) {
+ responseCode = HttpServletResponse.SC_UNAUTHORIZED;
+ logger.error(EELFLoggerDelegate.errorLogger, String.format("SessionCommunication.sendGet received an un-authorized exception. AppName: %s", appName));
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeRestApiAuthenticationError);
+ } catch (Exception e) {
+ responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
+ String message = String.format(
+ "SessionCommunication.sendGet encountered an Exception. AppName: %s, Details: %s", appName,
+ EcompPortalUtils.getStackTrace(e));
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeHttpConnectionError, e.getMessage());
+ logger.error(EELFLoggerDelegate.errorLogger, message);
+ } finally {
+ EcompPortalUtils.setExternalAppResponseCode(responseCode);
+ }
+ return appResponse;
+ }
+
+ @EPAuditLog
+ public Boolean pingSession(OnboardingApp app, String sessionTimeoutMap) throws Exception {
+ String appName = "Unknwon";
+ int responseCode = 0;
+ try {
+ if (app != null && app.name != null && app.name != "") {
+ appName = app.name;
+ }
+
+ String url = app.restUrl + "/updateSessionTimeOuts";
+ String encriptedPwdDB = app.appPassword;
+ String appUserName = app.username;
+ // String decreptedPwd = CipherUtil.decrypt(encriptedPwdDB,
+ // SystemProperties.getProperty(SystemProperties.Decryption_Key));
+
+ setLocalMDCContext(app, "/updateSessionTimeOuts", url);
+
+ URL obj = new URL(url);
+
+ HttpURLConnection con = (HttpURLConnection) obj.openConnection();
+
+ // optional default is GET
+ con.setRequestMethod("POST");
+ con.setConnectTimeout(3000);
+ con.setReadTimeout(15000);
+
+ // add request header
+ con.setRequestProperty("username", appUserName);
+ con.setRequestProperty("password", encriptedPwdDB);
+
+ con.setRequestProperty("sessionMap", sessionTimeoutMap);
+ con.setDoInput(true);
+ con.setDoOutput(true);
+ con.getOutputStream().write(sessionTimeoutMap.getBytes());
+ con.getOutputStream().flush();
+ con.getOutputStream().close();
+
+ responseCode = con.getResponseCode();
+ logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
+ } catch (UrlAccessRestrictedException e) {
+ responseCode = HttpServletResponse.SC_UNAUTHORIZED;
+ String message = String.format(
+ "SessionCommunication.pingSession received an un-authorized exception. AppName: %s", appName);
+ logger.error(EELFLoggerDelegate.errorLogger, message);
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeRestApiAuthenticationError);
+ } catch (Exception e) {
+ responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
+ String message = String.format(
+ "SessionCommunication.pingSession encountered an Exception. AppName: %s, Details: %s", appName,
+ EcompPortalUtils.getStackTrace(e));
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeHttpConnectionError, e.getMessage());
+ logger.error(EELFLoggerDelegate.errorLogger, message);
+ } finally {
+ EcompPortalUtils.setExternalAppResponseCode(responseCode);
+ }
+
+ return true;
+ }
+
+ @EPAuditLog
+ public Boolean timeoutSession(OnboardingApp app, String portalJSessionId) throws Exception {
+ String appName = "Unknwon";
+ int responseCode = 0;
+ try {
+ if (app != null && app.name != null && app.name != "") {
+ appName = app.name;
+ }
+
+ String url = app.restUrl + "/timeoutSession" + "?portalJSessionId=" + portalJSessionId;
+
+ String encriptedPwdDB = app.appPassword;
+ String appUserName = app.username;
+ // String decreptedPwd = CipherUtil.decrypt(encriptedPwdDB,
+ // SystemProperties.getProperty(SystemProperties.Decryption_Key));
+
+ setLocalMDCContext(app, "/timeoutSession", url);
+
+ URL obj = new URL(url);
+ HttpURLConnection con = (HttpURLConnection) obj.openConnection();
+
+ // optional default is GET
+ con.setRequestMethod("POST");
+ con.setConnectTimeout(3000);
+ con.setReadTimeout(15000);
+
+ // add request header
+ con.setRequestProperty("username", appUserName);
+ con.setRequestProperty("password", encriptedPwdDB);
+
+ // con.setRequestProperty("portalJSessionId", portalJSessionId);
+ con.setDoInput(true);
+ con.setDoOutput(true);
+ con.getOutputStream().flush();
+ con.getOutputStream().close();
+
+ responseCode = con.getResponseCode();
+ logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode);
+ } catch (UrlAccessRestrictedException e) {
+ responseCode = HttpServletResponse.SC_UNAUTHORIZED;
+ String message = String.format(
+ "SessionCommunication.timeoutSession received an un-authorized exception. AppName: %s", appName);
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ logger.error(EELFLoggerDelegate.errorLogger, message);
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeRestApiAuthenticationError);
+ } catch (Exception e) {
+ responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
+ String message = String.format(
+ "SessionCommunication.timeoutSession encountered an Exception. AppName: %s, Details: %s", appName,
+ EcompPortalUtils.getStackTrace(e));
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeHttpConnectionError, e.getMessage());
+ logger.error(EELFLoggerDelegate.errorLogger, message);
+ } finally {
+ EcompPortalUtils.setExternalAppResponseCode(responseCode);
+ }
+ return true;
+ }
+
+ @EPMetricsLog
+ private void setLocalMDCContext(OnboardingApp app, String restPath, String url) {
+ setRequestId();
+ MDC.put(EPSystemProperties.PROTOCOL, EPSystemProperties.HTTP);
+ if (url!=null && url.contains("https")) {
+ MDC.put(EPSystemProperties.PROTOCOL, EPSystemProperties.HTTPS);
+ }
+ MDC.put(EPSystemProperties.FULL_URL, url);
+ MDC.put(EPSystemProperties.TARGET_ENTITY, app.name);
+ MDC.put(EPSystemProperties.TARGET_SERVICE_NAME, restPath);
+ }
+
+ /**
+ * Generates request id, service name fields and loads them
+ * into MDC, as these values could be empty as these
+ * session timeout requests are generated at
+ * scheduled intervals using quartz scheduler.
+ */
+ @EPMetricsLog
+ public void setRequestId() {
+ String requestId = MDC.get(Configuration.MDC_KEY_REQUEST_ID);
+ if (StringUtils.isEmpty(requestId)) {
+ MDC.put(Configuration.MDC_KEY_REQUEST_ID, UUID.randomUUID().toString());
+ }
+
+ MDC.put(Configuration.MDC_SERVICE_NAME, "/quartz/keepSessionAlive");
+ MDC.put(EPSystemProperties.PARTNER_NAME, EPSystemProperties.ECOMP_PORTAL_BE);
+ }
+
+ /**
+ * Remove the values from MDC as these requests are
+ * executed at regular intervals based on quartz rather
+ * incoming REST API requests.
+ * @param bAll
+ */
+ @EPMetricsLog
+ public void clear(Boolean bAll) {
+ MDC.remove(EPSystemProperties.EXTERNAL_API_RESPONSE_CODE);
+ if (bAll) {
+ MDC.remove(Configuration.MDC_KEY_REQUEST_ID);
+ MDC.remove(Configuration.MDC_SERVICE_NAME);
+ MDC.remove(EPSystemProperties.PARTNER_NAME);
+ }
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/TimeoutHandler.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/TimeoutHandler.java
new file mode 100644
index 00000000..84dcf3fa
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/service/sessionmgt/TimeoutHandler.java
@@ -0,0 +1,252 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.service.sessionmgt;
+
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpSession;
+
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
+import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
+import org.openecomp.portalapp.portal.service.EPAppService;
+import org.openecomp.portalapp.portal.transport.OnboardingApp;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.domain.sessionmgt.TimeoutVO;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiConstants;
+import org.quartz.DisallowConcurrentExecution;
+import org.quartz.JobExecutionContext;
+import org.quartz.JobExecutionException;
+import org.quartz.PersistJobDataAfterExecution;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.scheduling.quartz.QuartzJobBean;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+/**
+ * Executed periodically by Quartz to discover remote application sessions and
+ * update timeouts suitably.
+ */
+@PersistJobDataAfterExecution
+@DisallowConcurrentExecution
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class TimeoutHandler extends QuartzJobBean {
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(TimeoutHandler.class);
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ /**
+ * Supports static call {@link #timeoutSessions(HttpSession)}
+ */
+ private static List<OnboardingApp> onboardedAppList = null;
+
+ @Autowired
+ SessionCommunication sessionCommunication;
+
+ @Override
+ protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
+ try {
+ //Create a request id if there is none available,
+ //and which will internally be used when making
+ //session extended timeout calls to the partner applications.
+ if (getSessionCommunication()!=null) {
+ getSessionCommunication().setRequestId();
+ }
+ logger.info(EELFLoggerDelegate.debugLogger, "Quartz Cronjob for Session Management begins");
+
+ ManageService manageService = (ManageService) applicationContext.getBean("manageService");
+ EPAppService appService = (EPAppService) applicationContext.getBean("epAppService");
+
+ List<OnboardingApp> appList = appService.getEnabledNonOpenOnboardingApps();
+ onboardedAppList = appList;
+ TypeReference<Hashtable<String, TimeoutVO>> typeRef = new TypeReference<Hashtable<String, TimeoutVO>>() {
+ };
+ String portalJsonSessionStr;
+ Map<String, TimeoutVO> portalSessionTimeoutMap = null;
+
+ portalJsonSessionStr = manageService.gatherSessionExtenstions();
+ if (portalJsonSessionStr == null || portalJsonSessionStr == "") {
+ logger.error(EELFLoggerDelegate.errorLogger, "Session Management: Portal session information is empty.");
+ return;
+ }
+
+ try {
+ portalSessionTimeoutMap = mapper.readValue(portalJsonSessionStr, typeRef);
+ } catch (JsonMappingException | JsonParseException je) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput);
+ logger.error(EELFLoggerDelegate.errorLogger, "Session Management: JSON Mapping Exception occurred while gathering the Session", je);
+ return;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Session Management: Error while gather Session from portal", e);
+ return;
+ }
+
+ Map<Long, Map<String, TimeoutVO>> appSessionTimeOutMap = new Hashtable<Long, Map<String, TimeoutVO>>();
+ // determine the Max TimeOut Time for each of the managed sessions
+ for (OnboardingApp app : appList) {
+ if (app.restUrl == null) {
+ logger.info(EELFLoggerDelegate.debugLogger, "Session Management: null restUrl, not fetching from app " + app.name);
+ continue;
+ }
+ logger.info(EELFLoggerDelegate.debugLogger, "Session Management: Calling App " + app.name + " at URL " + app.restUrl);
+ String jsonSessionStr = fetchAppSessions(app);
+ logger.info(EELFLoggerDelegate.debugLogger, "Session Management: App " + app.name + " returned " + jsonSessionStr);
+ if (jsonSessionStr == null || jsonSessionStr.isEmpty())
+ continue;
+
+ try {
+ Map<String, TimeoutVO> sessionTimeoutMap = mapper.readValue(jsonSessionStr, typeRef);
+ appSessionTimeOutMap.put(app.id, sessionTimeoutMap);
+ for (String portalJSessionId : sessionTimeoutMap.keySet()) {
+ final TimeoutVO maxTimeoutVO = portalSessionTimeoutMap.get(portalJSessionId);
+ final TimeoutVO compareTimeoutVO = sessionTimeoutMap.get(portalJSessionId);
+ if (maxTimeoutVO != null && compareTimeoutVO != null) {
+ if (maxTimeoutVO.compareTo(compareTimeoutVO) < 0)
+ portalSessionTimeoutMap.get(portalJSessionId)
+ .setSessionTimOutMilliSec(compareTimeoutVO.getSessionTimOutMilliSec());
+ }
+ }
+ } catch (JsonParseException | JsonMappingException e) {
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput);
+ logger.error(EELFLoggerDelegate.errorLogger,
+ "JSON Mapping/Processing Exception occurred while mapping/parsing the jsonSessionStr", e);
+ continue;
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while mapping/parsing the jsonSessionStr", e);
+ continue;
+ }
+
+ }
+
+ // post the updated session timeouts back to the Apps
+ for (OnboardingApp app : appList) {
+ if (app.restUrl == null) {
+ logger.warn(EELFLoggerDelegate.errorLogger, "Session Management: null restUrl, not posting back to app " + app.name);
+ continue;
+ }
+
+ Map<String, TimeoutVO> sessionTimeoutMap = appSessionTimeOutMap.get(app.id);
+ if (sessionTimeoutMap == null || sessionTimeoutMap.isEmpty())
+ continue;
+
+ for (String portalJSessionId : sessionTimeoutMap.keySet()) {
+ try {
+ final TimeoutVO maxTimeoutVO = portalSessionTimeoutMap.get(portalJSessionId);
+ final TimeoutVO setTimeoutVO = sessionTimeoutMap.get(portalJSessionId);
+ if (maxTimeoutVO == null || setTimeoutVO == null) {
+ String message = String.format(
+ "Session Management: Failed to update the session timeouts for the app: %s and the sessionId: %s.",
+ app.name, portalJSessionId);
+ logger.warn(EELFLoggerDelegate.errorLogger, message);
+ continue;
+ }
+ setTimeoutVO.setSessionTimOutMilliSec(maxTimeoutVO.getSessionTimOutMilliSec());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Session Management: error while updating the session timeout map", e);
+ continue;
+ }
+ }
+ logger.info(EELFLoggerDelegate.debugLogger, "Session Management: Updating App " + app.restUrl);
+ String sessionTimeoutMapStr = "";
+ try {
+ sessionTimeoutMapStr = mapper.writeValueAsString(sessionTimeoutMap);
+ } catch (JsonProcessingException je) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while processing sessionTimeOutMap object to a String. Details: "
+ + EcompPortalUtils.getStackTrace(je));
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput);
+ }
+ pingAppSessions(app, sessionTimeoutMapStr);
+ }
+ String portalSessionTimeoutMapStr = "";
+ try {
+ portalSessionTimeoutMapStr = mapper.writeValueAsString(portalSessionTimeoutMap);
+ } catch (JsonProcessingException je) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while processing portalSessionTimeOutMap object to a String", je);
+ EPLogUtil.logEcompError(EPAppMessagesEnum.BeInvalidJsonInput);
+ }
+ manageService.updateSessionExtensions(portalSessionTimeoutMapStr);
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "************************ Session Management: error in managing session timeouts", e);
+ } finally {
+ getSessionCommunication().clear(true);
+ }
+ }
+
+ private String fetchAppSessions(OnboardingApp app) throws Exception {
+ String jsonSessionValue = getSessionCommunication().sendGet(app);
+ getSessionCommunication().clear(false);
+ return jsonSessionValue;
+ }
+
+ private void pingAppSessions(OnboardingApp app, String sessionTimeoutMapStr) throws Exception {
+ getSessionCommunication().pingSession(app, sessionTimeoutMapStr);
+ getSessionCommunication().clear(false);
+ }
+
+ public void timeoutSessions(HttpSession session) throws Exception {
+ String portalJSessionId = portalJSessionId(session);
+ if (onboardedAppList == null)
+ return;
+
+ for (OnboardingApp app : onboardedAppList) {
+ getSessionCommunication().timeoutSession(app, portalJSessionId);
+ getSessionCommunication().clear(false);
+ }
+ }
+
+ protected static String portalJSessionId(HttpSession session) {
+ final Object attribute = session.getAttribute(PortalApiConstants.PORTAL_JSESSION_ID);
+ if (attribute == null)
+ return "";
+ String jSessionKey = (String) attribute;
+ return jSessionKey.split("-")[0];
+ }
+
+ private static ApplicationContext applicationContext;
+
+ public static void setApplicationContext(ApplicationContext _applicationContext) {
+ applicationContext = _applicationContext;
+ }
+
+ public SessionCommunication getSessionCommunication() {
+ if(sessionCommunication == null){
+ if (applicationContext != null)
+ sessionCommunication = (SessionCommunication)applicationContext.getBean("sessionCommunication");
+ }
+
+ return sessionCommunication;
+ }
+
+ public void setSessionCommunication(SessionCommunication sessionCommunication) {
+ this.sessionCommunication = sessionCommunication;
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/uebhandler/FunctionalMenuHandler.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/uebhandler/FunctionalMenuHandler.java
new file mode 100644
index 00000000..a726674c
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/uebhandler/FunctionalMenuHandler.java
@@ -0,0 +1,126 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.uebhandler;
+
+import java.util.List;
+
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
+import org.openecomp.portalapp.portal.service.AdminRolesService;
+import org.openecomp.portalapp.portal.service.FunctionalMenuService;
+import org.openecomp.portalapp.portal.service.SearchService;
+import org.openecomp.portalapp.portal.transport.FunctionalMenuItem;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.onboarding.ueb.UebException;
+import org.openecomp.portalsdk.core.onboarding.ueb.UebManager;
+import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg;
+import org.openecomp.portalsdk.core.service.DataAccessService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.scheduling.annotation.Async;
+import org.springframework.stereotype.Component;
+
+import com.google.gson.Gson;
+
+@Component
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class FunctionalMenuHandler {
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FunctionalMenuHandler.class);
+
+ @Autowired
+ AdminRolesService adminRolesService;
+
+ @Autowired
+ FunctionalMenuService functionalMenuService;
+
+ @Autowired
+ SearchService searchSvc;
+
+ @Autowired
+ DataAccessService dataAccessService;
+
+ @Async
+ public Boolean getFunctionalMenu(UebMsg requestMsg)
+ {
+ UebMsg returnMsg = new UebMsg();
+
+ if (requestMsg == null)
+ {
+ logger.error(EELFLoggerDelegate.errorLogger, "handleMenuRequest received null message");
+ return false;
+ }
+ else if (requestMsg.getSourceTopicName() == null)
+ {
+ logger.error(EELFLoggerDelegate.errorLogger, "A source topic name is required and not found in this msg:" + requestMsg.toString());
+ return false;
+ }
+ else if (requestMsg.getUserId() == null)
+ {
+ logger.debug(EELFLoggerDelegate.debugLogger, "Error getting functional menu. A userId is required and not found in this msg: " + requestMsg.toString());
+ returnMsg.putMsgId(requestMsg.getMsgId()); // echo tells requester this is a response
+ returnMsg.putPayload("Error: A userId is required. Call msg.putUserId() with an userId");
+ }
+ else
+ {
+ logger.debug(EELFLoggerDelegate.debugLogger, "Getting functional menu for user = " + requestMsg.getUserId());
+ EPUser user = searchSvc.searchUserByUserId(requestMsg.getUserId());
+
+ List<FunctionalMenuItem> menuItems = null;
+ if (user == null)
+ {
+ logger.debug(EELFLoggerDelegate.debugLogger, "Error getting functional menu. userId not found in directory or is guest: " + requestMsg.toString());
+ }
+ else if (adminRolesService.isSuperAdmin(user))
+ {
+ logger.debug(EELFLoggerDelegate.debugLogger, "FunctionalMenuHandler: SuperUser, about to call getFunctionalMenuItems()");
+ menuItems = functionalMenuService.getFunctionalMenuItems();
+ }
+ else
+ {
+ logger.debug(EELFLoggerDelegate.debugLogger, "getMenuItemsForAuthUser: about to call getFunctionalMenuItemsForUser()");
+ menuItems = functionalMenuService.getFunctionalMenuItemsForUser(requestMsg.getUserId());
+ }
+
+ if ( menuItems != null )
+ {
+ String functionalMenuJsonString = new Gson().toJson(menuItems);
+ logger.debug(EELFLoggerDelegate.debugLogger, "returning functional menu : " + functionalMenuJsonString);
+ returnMsg.putMsgId(requestMsg.getMsgId()); // echo tells requester this is a response
+ returnMsg.putPayload(functionalMenuJsonString);
+ } else {
+ returnMsg.putMsgId(requestMsg.getMsgId()); // echo tells requester this is a response
+ returnMsg.putPayload("Error: Not found for userId = " + requestMsg.getUserId());
+ }
+ }
+
+ try {
+ UebManager.getInstance().publishReplyEP(returnMsg, requestMsg.getSourceTopicName());
+ } catch (UebException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "UebException occurred while responding to the Ueb message, Details:" + EcompPortalUtils.getStackTrace(e));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while responding to the Ueb message, Details:" + EcompPortalUtils.getStackTrace(e));
+ }
+
+ return true;
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/uebhandler/InitUebHandler.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/uebhandler/InitUebHandler.java
new file mode 100644
index 00000000..b8289538
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/uebhandler/InitUebHandler.java
@@ -0,0 +1,75 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.uebhandler;
+
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+import javax.annotation.PostConstruct;
+
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiConstants;
+import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiProperties;
+import org.openecomp.portalsdk.core.onboarding.ueb.UebManager;
+import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+
+//
+// Adding this class for the sole purpose of insuring that the MainUebHandler really
+// honors @Async and kicks off a thread. For more info google @Async and read about
+// @Async only working if called from different class.
+//
+//@Configuration
+//@EnableAspectJAutoProxy
+//@EPMetricsLog
+public class InitUebHandler {
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(InitUebHandler.class);
+
+ //@Autowired
+ MainUebHandler mainUebHandler;
+
+ public InitUebHandler() {
+
+ }
+
+ //@PostConstruct
+ public void initUeb() {
+
+ try {
+ String enableListenerThread = PortalApiProperties.getProperty(PortalApiConstants.UEB_LISTENERS_ENABLE);
+ if (enableListenerThread.equalsIgnoreCase("true")) {
+ ConcurrentLinkedQueue<UebMsg> inboxQueue = new ConcurrentLinkedQueue<UebMsg>();
+ UebManager.getInstance().initListener(inboxQueue);
+ mainUebHandler.runHandler(inboxQueue);
+ logger.info(EELFLoggerDelegate.errorLogger, "Returned from initiating mainUebHandler...");
+ }
+ else {
+ logger.info(EELFLoggerDelegate.errorLogger, "Not starting UEB listening thread because ueb_listeners_enable is not set to true in the properties file.");
+ }
+ }
+ catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e));
+ logger.info(EELFLoggerDelegate.errorLogger, "Not starting UEB listening thread because property could not be read " + PortalApiConstants.UEB_LISTENERS_ENABLE + e.getMessage());
+ }
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/uebhandler/MainUebHandler.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/uebhandler/MainUebHandler.java
new file mode 100644
index 00000000..de085419
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/uebhandler/MainUebHandler.java
@@ -0,0 +1,115 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.uebhandler;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+import org.openecomp.portalapp.portal.ueb.EPUebMsgTypes;
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg;
+import org.openecomp.portalsdk.core.onboarding.ueb.UebMsgTypes;
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.scheduling.annotation.Async;
+import org.springframework.stereotype.Component;
+
+import com.att.eelf.configuration.Configuration;
+
+
+//-------------------------------------------------------------------------
+// Listens for received UEB messages and handles the messages
+//
+// Note: To implement a synchronous reply call getMsgId on the request
+// and putMsgId on the reply (echoing the request MsgId).
+//
+//-------------------------------------------------------------------------
+@Component("MainUebHandler")
+public class MainUebHandler
+{
+ final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MainUebHandler.class);
+
+ ConcurrentLinkedQueue<UebMsg> inboxQueue = null;
+
+ @Autowired
+ FunctionalMenuHandler funcMenuHandler;
+
+ @Autowired
+ WidgetNotificationHandler widgetNotificationHandler;
+
+ @Async
+ public void runHandler(ConcurrentLinkedQueue<UebMsg> queue)
+ {
+ inboxQueue = queue;
+ logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "==> MainUebHandler started");
+ while (true)
+ {
+ UebMsg msg = null;
+ while ((msg = inboxQueue.poll()) != null)
+ {
+ if ((msg.getMsgType() != null) && (!msg.getMsgType().equalsIgnoreCase(EPUebMsgTypes.UEB_MSG_TYPE_HEALTH_CHECK)))
+ {
+ // TODO: switch this back to debug
+ logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== Received UEB message : " + msg.toString());
+ logger.info(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== Received UEB message : " + msg.toString());
+ MDC.put(EPSystemProperties.PARTNER_NAME, msg.getSourceTopicName());
+ MDC.put(Configuration.MDC_SERVICE_NAME, msg.getMsgType().toString());
+ switch(msg.getMsgType())
+ {
+ case UebMsgTypes.UEB_MSG_TYPE_GET_FUNC_MENU:
+ {
+ funcMenuHandler.getFunctionalMenu(msg);
+ break;
+ }
+ case UebMsgTypes.UEB_MSG_TYPE_WIDGET_NOTIFICATION:
+ {
+ widgetNotificationHandler.handleWidgetNotification(msg);
+ break;
+ }
+ default:
+ {
+ logger.info(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "Unknown UEB message type " + msg.toString());
+ break;
+ }
+ }
+ }
+ }
+
+ if (Thread.interrupted())
+ {
+ logger.info(EELFLoggerDelegate.errorLogger, "==> UebMainHandler exiting");
+ break;
+ }
+
+ try {
+ Thread.sleep(10);
+ } catch (InterruptedException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "UebMainHandler interrupted during sleep" + EcompPortalUtils.getStackTrace(e));
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred during sleep" + EcompPortalUtils.getStackTrace(e));
+ }
+ }
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/uebhandler/WidgetNotificationHandler.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/uebhandler/WidgetNotificationHandler.java
new file mode 100644
index 00000000..a066b124
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/uebhandler/WidgetNotificationHandler.java
@@ -0,0 +1,93 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.uebhandler;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+
+import org.openecomp.portalapp.portal.domain.EPApp;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
+import org.openecomp.portalapp.portal.service.EPAppService;
+import org.openecomp.portalapp.portal.service.SearchService;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.onboarding.ueb.UebException;
+import org.openecomp.portalsdk.core.onboarding.ueb.UebManager;
+import org.openecomp.portalsdk.core.onboarding.ueb.UebMsg;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.scheduling.annotation.Async;
+import org.springframework.stereotype.Component;
+
+@Component
+@org.springframework.context.annotation.Configuration
+@EnableAspectJAutoProxy
+@EPMetricsLog
+public class WidgetNotificationHandler {
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetNotificationHandler.class);
+
+ final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
+
+ @Autowired
+ EPAppService appSvc;
+
+ @Autowired
+ SearchService searchSvc;
+
+
+ public WidgetNotificationHandler()
+ {
+ }
+
+ @Async
+ public void handleWidgetNotification(UebMsg requestMsg)
+ {
+ if (requestMsg.getUserId() != null) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "handleWidgetNotification: getting widgets/apps for user = " + requestMsg.getUserId());
+ EPUser user = searchSvc.searchUserByUserId(requestMsg.getUserId());
+ if (user != null && (appSvc != null)) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "Debug mytag: " + appSvc);
+ List<EPApp> apps = appSvc.getUserApps(user);
+ for (EPApp app : apps) {
+ if (app.getUebTopicName() != null) {
+ UebMsg widgetMsg = new UebMsg();
+ widgetMsg.putSourceTopicName(app.getUebTopicName());
+ logger.debug(EELFLoggerDelegate.debugLogger, "app.getUebTopicName was invoked");
+ widgetMsg.putPayload(requestMsg.getPayload());
+ try {
+ logger.debug(EELFLoggerDelegate.debugLogger, "Sending widget notification from " + requestMsg.getSourceTopicName() + " to " + app.getUebTopicName());
+ UebManager.getInstance().publishEP(widgetMsg, app.getUebTopicName());
+ } catch (UebException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "handleWidgetNotification publishEP exception" + EcompPortalUtils.getStackTrace(e));
+ }
+ }
+ }
+ } else {
+ logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "handleWidgetNotification: user " +
+ requestMsg.getUserId() + " not found" + " source = " + requestMsg.getSourceTopicName() +
+ ". This widget notification cannot be posted to other widgets");
+ }
+ }
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/util/EPUserUtils.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/util/EPUserUtils.java
new file mode 100644
index 00000000..0b79a2b4
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/util/EPUserUtils.java
@@ -0,0 +1,308 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.util;
+
+import java.io.Serializable;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+
+import org.openecomp.portalapp.portal.domain.EPRole;
+import org.openecomp.portalapp.portal.domain.EPUser;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.FusionObject;
+import org.openecomp.portalsdk.core.domain.RoleFunction;
+import org.openecomp.portalsdk.core.domain.UrlsAccessible;
+import org.openecomp.portalsdk.core.exception.SessionExpiredException;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.menu.MenuBuilder;
+import org.openecomp.portalsdk.core.service.DataAccessService;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.openecomp.portalsdk.core.web.support.AppUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+
+public class EPUserUtils implements Serializable, FusionObject {
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUserUtils.class);
+
+ public static final String KEY_USER_ROLES_CACHE = "userRoles";
+
+ public static final String WJ_HEADER_USER_NAME = "iv-user";
+ public static final String WJ_HEADER_USER_GROUP = "iv-groups";
+
+ private static DataAccessService dataAccessService;
+
+ private static final long serialVersionUID = 1L;
+
+ public static EPUser getUserSession(HttpServletRequest request) {
+ HttpSession session = AppUtils.getSession(request);
+
+ if (session == null) {
+ throw new SessionExpiredException();
+ }
+
+ return (EPUser) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
+ }
+
+ @SuppressWarnings("rawtypes")
+ public static void setUserSession(HttpServletRequest request, EPUser user, Set applicationMenuData,
+ Set businessDirectMenuData, String loginMethod) {
+ HttpSession session = request.getSession(true);
+
+ EPUserUtils.clearUserSession(request); // let's clear the current user
+ // session to avoid any
+ // conflicts during the set
+
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user);
+
+ getRoleFunctions(request);
+
+ // truncate the role (and therefore the role function) data to save
+ // memory in the session
+ user.setEPRoles(null);
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME), user.getFullName());
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME), "My Portal");
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME),
+ MenuBuilder.filterMenu(applicationMenuData, request));
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME),
+ MenuBuilder.filterMenu(businessDirectMenuData, request));
+ }
+
+ public static void clearUserSession(HttpServletRequest request) {
+ HttpSession session = AppUtils.getSession(request);
+
+ if (session == null) {
+ throw new SessionExpiredException();
+ }
+
+ // removes all stored attributes from the current user's session
+ session.removeAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
+ session.removeAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME));
+ session.removeAttribute(SystemProperties.getProperty(SystemProperties.BUSINESS_DIRECT_MENU_ATTRIBUTE_NAME));
+ session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
+ session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ public static Set getRoleFunctions(HttpServletRequest request) {
+ HashSet roleFunctions = null;
+
+ HttpSession session = request.getSession();
+ roleFunctions = (HashSet) session
+ .getAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
+
+ if (roleFunctions == null) {
+ HashMap roles = getRoles(request);
+ roleFunctions = new HashSet();
+
+ Iterator i = roles.keySet().iterator();
+
+ while (i.hasNext()) {
+ Long roleKey = (Long) i.next();
+ EPRole role = (EPRole) roles.get(roleKey);
+
+ Iterator j = role.getRoleFunctions().iterator();
+
+ while (j.hasNext()) {
+ RoleFunction function = (RoleFunction) j.next();
+ roleFunctions.add(function.getCode());
+ }
+ }
+
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME),
+ roleFunctions);
+ }
+
+ return roleFunctions;
+ }
+
+ @SuppressWarnings("rawtypes")
+ public static HashMap getRoles(HttpServletRequest request) {
+ HashMap roles = null;
+
+ // HttpSession session = request.getSession();
+ HttpSession session = AppUtils.getSession(request);
+ roles = (HashMap) session.getAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME));
+
+ // if roles are not already cached, let's grab them from the user
+ // session
+ if (roles == null) {
+ EPUser user = getUserSession(request);
+
+ // get all user roles (including the tree of child roles)
+ roles = getAllUserRoles(user);
+
+ session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME),
+ getAllUserRoles(user));
+ }
+
+ return roles;
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ public static HashMap getAllUserRoles(EPUser user) {
+ HashMap roles = new HashMap();
+ Iterator i = user.getEPRoles().iterator();
+
+ while (i.hasNext()) {
+ EPRole role = (EPRole) i.next();
+
+ if (role.getActive()) {
+ roles.put(role.getId(), role);
+
+ // let's take a recursive trip down the tree to add all child
+ // roles
+ addChildRoles(role, roles);
+ }
+ }
+
+ return roles;
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ private static void addChildRoles(EPRole role, HashMap roles) {
+ Set childRoles = role.getChildRoles();
+
+ if (childRoles != null && childRoles.size() > 0) {
+ Iterator j = childRoles.iterator();
+ while (j.hasNext()) {
+ EPRole childRole = (EPRole) j.next();
+
+ if (childRole.getActive()) {
+ roles.put(childRole.getId(), childRole);
+
+ addChildRoles(childRole, roles);
+ }
+ }
+ }
+
+ }
+
+ @SuppressWarnings({ "unchecked", "rawtypes", "unused" })
+ public static boolean isUrlAccessible(HttpServletRequest request, String currentUrl) {
+ boolean isAccessible = false;
+
+ Map params = new HashMap();
+ params.put("current_url", currentUrl);
+
+ List list = getDataAccessService().executeNamedQuery("restrictedUrls", params, null);
+
+ // loop through the list of restricted URL's
+ if (list != null && list.size() > 0) {
+ for (int i = 0; i < list.size(); i++) {
+ /*
+ * Object[] restrictedUrl = (Object[])list.get(i);
+ *
+ * String url = (String)restrictedUrl[0]; String functionCd =
+ * (String)restrictedUrl[1];
+ */
+ UrlsAccessible urlFunctions = (UrlsAccessible) list.get(i);
+
+ String url = (String) urlFunctions.getUrl();
+ String functionCd = (String) urlFunctions.getFunctionCd();
+
+ if (EPUserUtils.isAccessible(request, functionCd)) {
+ isAccessible = true;
+ }
+ }
+ return isAccessible;
+ }
+
+ return true;
+ }
+
+ public static boolean hasRole(HttpServletRequest request, String roleKey) {
+ return getRoles(request).keySet().contains(new Long(roleKey));
+ }
+
+ public static boolean hasRole(EPUser user, String roleKey) {
+ return getAllUserRoles(user).keySet().contains(new Long(roleKey));
+ }
+
+ public static boolean isAccessible(HttpServletRequest request, String functionKey) {
+ return getRoleFunctions(request).contains(functionKey);
+ }
+
+ public static DataAccessService getDataAccessService() {
+ return dataAccessService;
+ }
+
+ @Autowired
+ public void setDataAccessService(DataAccessService dataAccessService) {
+ EPUserUtils.dataAccessService = dataAccessService;
+ }
+
+ public static int getUserId(HttpServletRequest request) {
+ return getUserIdAsLong(request).intValue();
+ }
+
+ public static Long getUserIdAsLong(HttpServletRequest request) {
+ Long userId = new Long(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID));
+
+ if (request != null) {
+ if (getUserSession(request) != null) {
+ userId = getUserSession(request).getId();
+ }
+ }
+
+ return userId;
+ }
+
+ public static String getRequestId(HttpServletRequest request) {
+ Enumeration<String> headerNames = request.getHeaderNames();
+
+ String requestId = "";
+ try {
+ while (headerNames.hasMoreElements()) {
+ String headerName = (String) headerNames.nextElement();
+ logger.debug(EELFLoggerDelegate.debugLogger, "One header is " + headerName + " : " + request.getHeader(headerName));
+ if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) {
+ requestId = request.getHeader(headerName);
+ break;
+ }
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "HEADER!!!! Exception : " + EcompPortalUtils.getStackTrace(e));
+ }
+
+ return (requestId.isEmpty() ? UUID.randomUUID().toString() : requestId);
+ }
+
+ public static String getFullURL(HttpServletRequest request) {
+ if (request != null) {
+ StringBuffer requestURL = request.getRequestURL();
+ String queryString = request.getQueryString();
+
+ if (queryString == null) {
+ return requestURL.toString();
+ } else {
+ return requestURL.append('?').append(queryString).toString();
+ }
+ }
+ return "";
+ }
+}
diff --git a/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/util/SessionCookieUtil.java b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/util/SessionCookieUtil.java
new file mode 100644
index 00000000..69fc9b21
--- /dev/null
+++ b/ecomp-portal-BE/src/main/java/org/openecomp/portalapp/util/SessionCookieUtil.java
@@ -0,0 +1,129 @@
+/*-
+ * ================================================================================
+ * eCOMP Portal
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ================================================================================
+ */
+package org.openecomp.portalapp.util;
+
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.openecomp.portalapp.portal.utils.EPSystemProperties;
+import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
+import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.openecomp.portalsdk.core.onboarding.crossapi.PortalApiConstants;
+import org.openecomp.portalsdk.core.onboarding.crossapi.PortalTimeoutHandler;
+import org.openecomp.portalsdk.core.util.CipherUtil;
+import org.openecomp.portalsdk.core.util.SystemProperties;
+import org.openecomp.portalsdk.core.web.support.AppUtils;
+
+public class SessionCookieUtil {
+
+ //private static final String JSESSIONID = "JSESSIONID";
+ private static final String EP_SERVICE = "EPService";
+ private static final String USER_ID = "UserId";
+ private static Integer cookieMaxAge = -1;
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SessionCookieUtil.class);
+
+ public static void preSetUp(HttpServletRequest request,
+ HttpServletResponse response) {
+ initateSessionMgtHandler(request);
+ //set up EPService cookie
+ setUpEPServiceCookie(request, response);
+ }
+
+ public static void setUpEPServiceCookie(HttpServletRequest request,
+ HttpServletResponse response) {
+ String jSessionId = getJessionId(request);
+ Cookie cookie1 = new Cookie(EP_SERVICE, jSessionId);
+ cookie1.setMaxAge(cookieMaxAge);
+ cookie1.setDomain(EPSystemProperties.getProperty(EPSystemProperties.COOKIE_DOMAIN));
+ cookie1.setPath("/");
+ response.addCookie(cookie1);
+ }
+
+ public static void setUpUserIdCookie(HttpServletRequest request,
+ HttpServletResponse response,String userId) throws Exception {
+ logger.info("************** session cookie util set up UserId cookie begins");
+ userId = CipherUtil.encrypt(userId,
+ SystemProperties.getProperty(SystemProperties.Decryption_Key));
+ Cookie cookie1 = new Cookie(USER_ID, userId);
+ cookie1.setMaxAge(cookieMaxAge);
+ cookie1.setDomain(EPSystemProperties.getProperty(EPSystemProperties.COOKIE_DOMAIN));
+ cookie1.setPath("/");
+ response.addCookie(cookie1);
+ logger.info("************** session cookie util set up EP cookie completed");
+ }
+
+ public static String getUserIdFromCookie(HttpServletRequest request,
+ HttpServletResponse response) throws Exception {
+ String userId = "";
+ Cookie[] cookies = request.getCookies();
+ Cookie userIdcookie = null;
+ if (cookies != null)
+ for (Cookie cookie : cookies)
+ if (cookie.getName().equals(USER_ID))
+ userIdcookie = cookie;
+ if(userIdcookie!=null){
+ userId = CipherUtil.decrypt(userIdcookie.getValue(),
+ SystemProperties.getProperty(SystemProperties.Decryption_Key));
+ }
+
+ logger.info("************** session cookie util set up EP cookie completed");
+ return userId;
+ }
+
+ public static String getJessionId(HttpServletRequest request){
+
+ return request.getSession().getId();
+ /*
+ Cookie ep = WebUtils.getCookie(request, JSESSIONID);
+ if(ep==null){
+ return request.getSession().getId();
+ }
+ return ep.getValue();
+ */
+ }
+
+ protected static void initateSessionMgtHandler(HttpServletRequest request) {
+ String jSessionId = getJessionId(request);
+ storeMaxInactiveTime(request);
+ PortalTimeoutHandler.sessionCreated(jSessionId, jSessionId, AppUtils.getSession(request));
+ }
+
+ protected static void storeMaxInactiveTime(HttpServletRequest request) {
+ HttpSession session = AppUtils.getSession(request);
+ if(session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME) == null)
+ session.setAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME,session.getMaxInactiveInterval());
+ }
+
+ public static void resetSessionMaxIdleTimeOut(HttpServletRequest request) {
+ try {
+ HttpSession session = AppUtils.getSession(request);
+ final Object maxIdleAttribute = session.getAttribute(PortalApiConstants.GLOBAL_SESSION_MAX_IDLE_TIME);
+ if(session != null && maxIdleAttribute != null) {
+ session.setMaxInactiveInterval(Integer.parseInt(maxIdleAttribute.toString()));
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Could not reset the session timeout. Details: " + EcompPortalUtils.getStackTrace(e));
+ }
+
+ }
+
+}
diff --git a/ecomp-portal-BE/src/main/resources/cache.ccf b/ecomp-portal-BE/src/main/resources/cache.ccf
new file mode 100644
index 00000000..6f5c6f92
--- /dev/null
+++ b/ecomp-portal-BE/src/main/resources/cache.ccf
@@ -0,0 +1,30 @@
+# DEFAULT CACHE REGION
+jcs.default=DC
+jcs.default.cacheattributes=org.apache.jcs.engine.CompositeCacheAttributes
+jcs.default.cacheattributes.MaxObjects=1000
+jcs.default.cacheattributes.MemoryCacheName=org.apache.jcs.engine.memory.lru.LRUMemoryCache
+jcs.default.elementattributes=org.apache.jcs.engine.ElementAttributes
+jcs.default.elementattributes.IsEternal=true
+jcs.default.elementattributes.IsSpool=true
+
+
+# MEMORY SHRINKING CONFIGURATION (Commented)
+#jcs.default.cacheattributes.UseMemoryShrinker=true
+#jcs.default.cacheattributes.MaxMemoryIdleTimeSeconds=3600
+#jcs.default.cacheattributes.ShrinkerIntervalSeconds=60
+#jcs.default.cacheattributes.MaxSpoolPerRun=500
+#jcs.default.elementattributes=org.apache.jcs.engine.ElementAttributes
+#jcs.default.elementattributes.IsEternal=false
+
+
+# AUXILLARY CACHE CONFIGURATION
+jcs.auxiliary.DC=org.apache.jcs.auxiliary.disk.indexed.IndexedDiskCacheFactory
+jcs.auxiliary.DC.attributes=org.apache.jcs.auxiliary.disk.indexed.IndexedDiskCacheAttributes
+jcs.auxiliary.DC.attributes.DiskPath=c:/projects/fusion/war/WEB-INF/cache
+
+
+# PRE-DEFINED REGION FOR LOOKUP DATA
+jcs.region.lookUpObjectCache=DC
+jcs.region.lookUpObjectCache.cacheattributes=org.apache.jcs.engine.CompositeCacheAttributes
+jcs.region.lookUpObjectCache.cacheattributes.MaxObjects=4000
+jcs.region.lookUpObjectCache.cacheattributes.MemoryCacheName=org.apache.jcs.engine.memory.lru.LRUMemoryCache
diff --git a/ecomp-portal-BE/src/main/resources/logback.xml b/ecomp-portal-BE/src/main/resources/logback.xml
new file mode 100644
index 00000000..0c0d7647
--- /dev/null
+++ b/ecomp-portal-BE/src/main/resources/logback.xml
@@ -0,0 +1,285 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ================================================================================
+ eCOMP Portal
+ ================================================================================
+ Copyright (C) 2017 AT&T Intellectual Property
+ ================================================================================
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ ================================================================================
+ -->
+
+<!DOCTYPE xml>
+<configuration scan="true" scanPeriod="3 seconds" debug="true">
+ <!-- Log-back files for the ECOMP Portal "ecompportal" are created in directory
+ ${catalina.base}/logs/ecompportal; e.g., apache-tomcat-8.0.35/logs/ecompportal/application.log -->
+ <!--<jmxConfigurator /> -->
+
+ <!-- specify the component name -->
+ <property name="componentName" value="ecompportal"></property>
+
+ <!-- specify the base path of the log directory -->
+ <property name="logDirPrefix" value="${catalina.base}/logs"></property>
+
+ <!-- The directories where logs are written -->
+ <property name="logDirectory" value="${logDirPrefix}/${componentName}" />
+ <!-- Can easily relocate debug logs by modifying this path. -->
+ <property name="debugLogDirectory" value="${logDirPrefix}/${componentName}" />
+
+ <!-- log file names -->
+ <property name="generalLogName" value="application" />
+ <property name="errorLogName" value="error" />
+ <property name="metricsLogName" value="metrics" />
+ <property name="auditLogName" value="audit" />
+ <property name="debugLogName" value="debug" />
+ <!-- These loggers are not used in code (yet). <property name="securityLogName"
+ value="security" /> <property name="policyLogName" value="policy" /> <property
+ name="performanceLogName" value="performance" /> <property name="serverLogName"
+ value="server" /> -->
+
+ <!-- ServerFQDN=Server, -->
+ <property name="auditLoggerPattern"
+ value="%X{AuditLogBeginTimestamp}|%X{AuditLogEndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{Timer}|%X{ServerFQDN}|%X{ClientIPAddress}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| %msg%n" />
+
+ <property name="metricsLoggerPattern"
+ value="%X{MetricsLogBeginTimestamp}|%X{MetricsLogEndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{Timer}|%X{ServerFQDN}|%X{ClientIPAddress}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{TargetVisualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| %msg%n" />
+
+ <property name="errorLoggerPattern"
+ value="%date{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{RequestId}|%thread|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ClassName}|%X{AlertSeverity}|%X{ErrorCode}|%X{ErrorDescription}| %msg%n" />
+
+ <property name="defaultLoggerPattern"
+ value="%date{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{RequestId}|%thread|%X{ClassName}| %msg%n" />
+
+ <!-- use %class so library logging calls yield their class name -->
+ <property name="applicationLoggerPattern"
+ value="%date{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{RequestId}|%thread|%class{36}| %msg%n" />
+
+ <!--
+ <property name="defaultPattern"
+ value="%date{ISO8601}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}| %msg%n" />
+ <property name="debugLoggerPattern"
+ value="%date{ISO8601}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}| %msg%n" />
+ -->
+ <!-- <property name="debugLoggerPattern" value="%date{ISO8601}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%caller{3}]|%msg%n"
+ /> -->
+ <!-- Example evaluator filter applied against console appender -->
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <encoder>
+ <pattern>${applicationLoggerPattern}</pattern>
+ </encoder>
+ </appender>
+
+ <!-- ============================================================================ -->
+ <!-- EELF Appenders -->
+ <!-- ============================================================================ -->
+
+ <!-- The EELFAppender is used to record events to the general application
+ log -->
+
+
+ <appender name="EELF"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${generalLogName}.log</file>
+ <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
+ <!-- daily rollover -->
+ <fileNamePattern>${logDirectory}/${generalLogName}.log.%d{yyyy-MM-dd}.zip
+ </fileNamePattern>
+ <maxHistory>30</maxHistory>
+ </rollingPolicy>
+ <encoder>
+ <pattern>${applicationLoggerPattern}</pattern>
+ </encoder>
+ <filter class="org.openecomp.portalapp.portal.utils.CustomLoggingFilter" />
+ </appender>
+
+ <appender name="asyncEELF" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <!-- Class name is part of caller data -->
+ <includeCallerData>true</includeCallerData>
+ <appender-ref ref="EELF" />
+ </appender>
+
+ <!-- EELF Security Appender. This appender is used to record security events
+ to the security log file. Security events are separate from other loggers
+ in EELF so that security log records can be captured and managed in a secure
+ way separate from the other logs. This appender is set to never discard any
+ events. -->
+ <!-- <appender name="EELFSecurity" class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${securityLogName}.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/${securityLogName}.%i.log.zip </fileNamePattern>
+ <minIndex>1</minIndex> <maxIndex>9</maxIndex> </rollingPolicy> <triggeringPolicy
+ class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy> <encoder> <pattern>${defaultPattern}</pattern> </encoder>
+ </appender> <appender name="asyncEELFSecurity" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize> <discardingThreshold>0</discardingThreshold> <appender-ref
+ ref="EELFSecurity" /> </appender> -->
+
+ <!-- EELF Performance Appender. This appender is used to record performance
+ records. -->
+ <!-- <appender name="EELFPerformance" class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${performanceLogName}.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/${performanceLogName}.%i.log.zip </fileNamePattern>
+ <minIndex>1</minIndex> <maxIndex>9</maxIndex> </rollingPolicy> <triggeringPolicy
+ class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy> <encoder> <outputPatternAsHeader>true</outputPatternAsHeader>
+ <pattern>${defaultPattern}</pattern> </encoder> </appender> <appender name="asyncEELFPerformance"
+ class="ch.qos.logback.classic.AsyncAppender"> <queueSize>256</queueSize>
+ <appender-ref ref="EELFPerformance" /> </appender> -->
+
+ <!-- EELF Server Appender. This appender is used to record Server related
+ logging events. The Server logger and appender are specializations of the
+ EELF application root logger and appender. This can be used to segregate
+ Server events from other components, or it can be eliminated to record these
+ events as part of the application root log. -->
+ <!-- <appender name="EELFServer" class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${serverLogName}.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/${serverLogName}.%i.log.zip </fileNamePattern>
+ <minIndex>1</minIndex> <maxIndex>9</maxIndex> </rollingPolicy> <triggeringPolicy
+ class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy> <encoder> <pattern>${defaultPattern}</pattern> </encoder>
+ </appender> <appender name="asyncEELFServer" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize> <appender-ref ref="EELFServer" /> </appender> -->
+
+ <!-- EELF Policy Appender. This appender is used to record Policy engine
+ related logging events. The Policy logger and appender are specializations
+ of the EELF application root logger and appender. This can be used to segregate
+ Policy engine events from other components, or it can be eliminated to record
+ these events as part of the application root log. -->
+ <!-- <appender name="EELFPolicy" class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${policyLogName}.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/${policyLogName}.%i.log.zip </fileNamePattern>
+ <minIndex>1</minIndex> <maxIndex>9</maxIndex> </rollingPolicy> <triggeringPolicy
+ class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy> <encoder> <pattern>${defaultPattern}</pattern> </encoder>
+ </appender> <appender name="asyncEELFPolicy" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize> <appender-ref ref="EELFPolicy" /> </appender> -->
+
+ <!-- EELF Audit Appender. This appender is used to record audit engine related
+ logging events. The audit logger and appender are specializations of the
+ EELF application root logger and appender. This can be used to segregate
+ Policy engine events from other components, or it can be eliminated to record
+ these events as part of the application root log. -->
+
+ <appender name="EELFAudit"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${auditLogName}.log</file>
+ <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
+ <!-- daily roll over -->
+ <fileNamePattern>${logDirectory}/${auditLogName}.log.%d{yyyy-MM-dd}.zip
+ </fileNamePattern>
+ <maxHistory>30</maxHistory>
+ </rollingPolicy>
+ <encoder>
+ <pattern>${auditLoggerPattern}</pattern>
+ </encoder>
+ </appender>
+ <appender name="asyncEELFAudit" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <appender-ref ref="EELFAudit" />
+ </appender>
+
+ <appender name="EELFMetrics"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${metricsLogName}.log</file>
+ <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
+ <!-- daily roll over -->
+ <fileNamePattern>${logDirectory}/${metricsLogName}.log.%d{yyyy-MM-dd}.zip
+ </fileNamePattern>
+ <maxHistory>30</maxHistory>
+ </rollingPolicy>
+ <encoder>
+ <pattern>${metricsLoggerPattern}</pattern>
+ </encoder>
+ </appender>
+
+
+ <appender name="asyncEELFMetrics" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <appender-ref ref="EELFMetrics" />
+ </appender>
+
+ <appender name="EELFError"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${errorLogName}.log</file>
+ <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
+ <!-- daily roll over -->
+ <fileNamePattern>${logDirectory}/${errorLogName}.log.%d{yyyy-MM-dd}.zip
+ </fileNamePattern>
+ <maxHistory>30</maxHistory>
+ </rollingPolicy>
+ <encoder>
+ <pattern>${errorLoggerPattern}</pattern>
+ </encoder>
+ </appender>
+
+ <appender name="asyncEELFError" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <appender-ref ref="EELFError" />
+ </appender>
+
+ <appender name="EELFDebug"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${debugLogDirectory}/${debugLogName}.log</file>
+ <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
+ <!-- daily roll over -->
+ <fileNamePattern>${logDirectory}/${debugLogName}.log.%d{yyyy-MM-dd}.zip
+ </fileNamePattern>
+ <maxHistory>30</maxHistory>
+ </rollingPolicy>
+ <encoder>
+ <pattern>${defaultLoggerPattern}</pattern>
+ </encoder>
+ </appender>
+
+ <appender name="asyncEELFDebug" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <appender-ref ref="EELFDebug" />
+ <includeCallerData>true</includeCallerData>
+ </appender>
+
+
+ <!-- ============================================================================ -->
+ <!-- EELF loggers -->
+ <!-- ============================================================================ -->
+ <logger name="com.att.eelf" level="info" additivity="false">
+ <appender-ref ref="asyncEELF" />
+ </logger>
+
+ <!-- <logger name="com.att.eelf.security" level="info" additivity="false">
+ <appender-ref ref="asyncEELFSecurity" /> </logger> <logger name="com.att.eelf.perf"
+ level="info" additivity="false"> <appender-ref ref="asyncEELFPerformance"
+ /> </logger> <logger name="com.att.eelf.server" level="info" additivity="false">
+ <appender-ref ref="asyncEELFServer" /> </logger> <logger name="com.att.eelf.policy"
+ level="info" additivity="false"> <appender-ref ref="asyncEELFPolicy" /> </logger> -->
+
+ <logger name="com.att.eelf.audit" level="info" additivity="false">
+ <appender-ref ref="asyncEELFAudit" />
+ </logger>
+
+ <logger name="com.att.eelf.metrics" level="info" additivity="false">
+ <appender-ref ref="asyncEELFMetrics" />
+ </logger>
+
+ <logger name="com.att.eelf.error" level="info" additivity="false">
+ <appender-ref ref="asyncEELFError" />
+ </logger>
+
+ <logger name="com.att.eelf.debug" level="debug" additivity="false">
+ <appender-ref ref="asyncEELFDebug" />
+ </logger>
+
+ <root level="INFO">
+ <appender-ref ref="asyncEELF" />
+ </root>
+
+</configuration>
diff --git a/ecomp-portal-BE/src/main/resources/openid-connect.properties b/ecomp-portal-BE/src/main/resources/openid-connect.properties
new file mode 100644
index 00000000..79d3b9b4
--- /dev/null
+++ b/ecomp-portal-BE/src/main/resources/openid-connect.properties
@@ -0,0 +1,22 @@
+###
+# ================================================================================
+# eCOMP Portal
+# ================================================================================
+# Copyright (C) 2017 AT&T Intellectual Property
+# ================================================================================
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ================================================================================
+###
+authentication_server_url = http://localhost:8383/openid-connect-server-webapp/
+ecomp_openid_connect_client = http://localhost:8080/ecompportal/openid_connect_login
+ecomp_redirect_uri = http://localhost:8080/ecompportal/welcome.htm
diff --git a/ecomp-portal-BE/src/main/resources/openid-keystore.jwks b/ecomp-portal-BE/src/main/resources/openid-keystore.jwks
new file mode 100644
index 00000000..caad4aaa
--- /dev/null
+++ b/ecomp-portal-BE/src/main/resources/openid-keystore.jwks
@@ -0,0 +1,12 @@
+{
+ "keys": [
+ {
+ "alg": "RSA256",
+ "d": "GIW2b3-ig8rk-Pm3cD5VqRSxtKBJfNhuBCSNe1N6-_kGrk3M5MWgqEbJCzdoZz8M8fclE8sV11b9_-iQx2iVjaw77gHsGe-IUucSNEeW2VtvbpvgCklw-B3CathBMOuHzqCbafj-J6zJ9uxGUFhgUKkLWZJ1iSuIw7WfKoBx_jU",
+ "e": "AQAB",
+ "n": "qYJqXTXsDroPYyQBBmSolK3bJtrSerEm-nrmbSpfn8Rz3y3oXLydvUqj8869PkcEzoJIY5Xf7xDN1Co_qyT9qge-3C6DEwGVHXOwRoXRGQ_h50Vsh60MB5MIuDN188EeZnQ30dtCTBB9KDTSEA2DunplhwLCq4xphnMNUaeHdEk",
+ "kty": "RSA",
+ "kid": "rsa1"
+ }
+ ]
+}
diff --git a/ecomp-portal-BE/src/main/resources/portal.properties b/ecomp-portal-BE/src/main/resources/portal.properties
new file mode 100644
index 00000000..a1982632
--- /dev/null
+++ b/ecomp-portal-BE/src/main/resources/portal.properties
@@ -0,0 +1,44 @@
+###
+# ================================================================================
+# eCOMP Portal
+# ================================================================================
+# Copyright (C) 2017 AT&T Intellectual Property
+# ================================================================================
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ================================================================================
+###
+portal.api.impl.class = org.openecomp.portalsdk.core.onboarding.client.OnBoardingApiServiceImpl
+portal.api.prefix = /api
+max.idle.time = 5
+user.attribute.name = user_attribute
+
+# Global Log On for single sign on
+ecomp_redirect_url = https://localhost:8080/ecompportal/login.htm
+
+testing=testing
+
+# URL of the ECOMP Portal REST API
+ecomp_rest_url = http://localhost:8080/ecompportal/auxapi
+
+ueb_listeners_enable = true
+
+ueb_app_key = EkrqsjQqZt4ZrPh6
+ueb_app_secret = KDwJDKdiVVkaz6gIBlRbyxbk
+ueb_app_mailbox_name = ECOMP-PORTAL-INBOX-DEV-LOCAL
+
+ueb_url_list = todo_ueb_url
+ecomp_portal_inbox_name = ECOMP-PORTAL-INBOX-DEV-LOCAL
+
+# Consumer group name for UEB topic.
+# Use the special tag to generate a unique one for each sdk-app server.
+ueb_app_consumer_group_name = {UUID}