diff options
Diffstat (limited to 'portal-BE/src/main/java/org')
49 files changed, 1953 insertions, 310 deletions
diff --git a/portal-BE/src/main/java/org/onap/portal/annotation/ApiVersion.java b/portal-BE/src/main/java/org/onap/portal/annotation/ApiVersion.java new file mode 100644 index 00000000..1c4fafc3 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/annotation/ApiVersion.java @@ -0,0 +1,57 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface ApiVersion { + + String service() default ""; + String max() default ""; + int min() default 0; + String method() default ""; + +} diff --git a/portal-BE/src/main/java/org/onap/portal/aop/service/FnUserServiceAOP.java b/portal-BE/src/main/java/org/onap/portal/aop/service/FnUserServiceAOP.java index b96575c6..65fc88d9 100644 --- a/portal-BE/src/main/java/org/onap/portal/aop/service/FnUserServiceAOP.java +++ b/portal-BE/src/main/java/org/onap/portal/aop/service/FnUserServiceAOP.java @@ -62,14 +62,11 @@ public class FnUserServiceAOP { private final DataValidator dataValidator; private final FnUserMapper fnUserMapper; - private final FnUserService fnUserService; @Autowired - public FnUserServiceAOP(final DataValidator dataValidator, final FnUserMapper fnUserMapper, - final FnUserService fnUserService) { + public FnUserServiceAOP(final DataValidator dataValidator, final FnUserMapper fnUserMapper) { this.dataValidator = dataValidator; this.fnUserMapper = fnUserMapper; - this.fnUserService = fnUserService; } @Before("execution(* org.onap.portal.service.fn.FnUserService.saveFnUser(..)) && args(principal, fnUser)") @@ -93,7 +90,7 @@ public class FnUserServiceAOP { LOGGER.error("User " + principal.getName() + " try to save not valid fnUser: " + violations); throw new IllegalArgumentException("FnUser is not valid, " + violations); } else { - LOGGER.error("User " + principal.getName() + " send valid fnUser"); + LOGGER.info("User " + principal.getName() + " send valid fnUser"); } } } diff --git a/portal-BE/src/main/java/org/onap/portal/aop/service/PersUserWidgetServiceAOP.java b/portal-BE/src/main/java/org/onap/portal/aop/service/PersUserWidgetServiceAOP.java new file mode 100644 index 00000000..79326618 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/aop/service/PersUserWidgetServiceAOP.java @@ -0,0 +1,72 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.aop.service; + +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.onap.portal.domain.db.fn.FnUser; +import org.onap.portal.domain.dto.transport.WidgetCatalogPersonalization; +import org.onap.portal.validation.DataValidator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Aspect +@Component +public class PersUserWidgetServiceAOP { + + private static final Logger LOGGER = LoggerFactory.getLogger(PersUserWidgetServiceAOP.class); + + private final DataValidator dataValidator; + + @Autowired + public PersUserWidgetServiceAOP(DataValidator dataValidator) { + this.dataValidator = dataValidator; + } + + @Before("execution(* org.onap.portal.service.PersUserWidgetService.setPersUserAppValue(..)) && args(user, personalization)") + public void setOnboardingWidget(FnUser user, WidgetCatalogPersonalization personalization) { + if (!dataValidator.isValid(personalization)) { + throw new IllegalArgumentException(dataValidator.getConstraintViolationsString(personalization)); + } + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/aop/service/WidgetServiceAOP.java b/portal-BE/src/main/java/org/onap/portal/aop/service/WidgetServiceAOP.java new file mode 100644 index 00000000..14172937 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/aop/service/WidgetServiceAOP.java @@ -0,0 +1,32 @@ +package org.onap.portal.aop.service; + +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.onap.portal.domain.dto.transport.OnboardingWidget; +import org.onap.portal.validation.DataValidator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Aspect +@Component +public class WidgetServiceAOP { + private final Long LONG_ECOMP_APP_ID = 1L; + + private static final Logger LOGGER = LoggerFactory.getLogger(WidgetServiceAOP.class); + + private final DataValidator dataValidator; + + @Autowired + public WidgetServiceAOP(DataValidator dataValidator) { + this.dataValidator = dataValidator; + } + + @Before("execution(* org.onap.portal.service.WidgetService.setOnboardingWidget(..)) && args(userId, onboardingWidget)") + public void setOnboardingWidget(final Long userId, OnboardingWidget onboardingWidget) { + if (!dataValidator.isValid(onboardingWidget)) { + throw new IllegalArgumentException(dataValidator.getConstraintViolationsString(onboardingWidget)); + } + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/controller/UserRolesController.java b/portal-BE/src/main/java/org/onap/portal/controller/UserRolesController.java new file mode 100644 index 00000000..fdd1de24 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/controller/UserRolesController.java @@ -0,0 +1,536 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.controller; + +import java.security.Principal; +import org.onap.portal.domain.db.fn.FnUser; +import org.onap.portal.service.AdminRolesService; +import org.onap.portal.service.fn.FnUserService; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@Configuration +public class UserRolesController { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesController.class); + + private final FnUserService fnUserService; + private final AdminRolesService adminRolesService; + + +/* + private final UserRolesService userRolesService; + private final ApplicationsRestClientService applicationsRestClientService; + private final SearchService searchService;*/ + + + private static final String FAILURE = "failure"; + + @Autowired + public UserRolesController(final FnUserService fnUserService, + final AdminRolesService adminRolesService) { + this.fnUserService = fnUserService; + this.adminRolesService = adminRolesService; + } + +/* + + @RequestMapping(value = {"/portalApi/queryUsers"}, method = RequestMethod.GET, produces = "application/json") + @PreAuthorize("hasRole('System_Administrator') and hasRole('Account_Administrator')") + public String getPhoneBookSearchResult(Principal principal, @RequestParam("search") String searchString, + HttpServletResponse response) { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + + String searchResult = null; + if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdmin(user) + && !adminRolesService.isRoleAdmin(user)) { + EcompPortalUtils.setBadPermissions(user, response, "getPhoneBookSearchResult"); + } else { + searchString = searchString.trim(); + if (searchString.length() > 2) { + searchResult = searchService.searchUsersInPhoneBook(searchString); + } else { + logger.info(EELFLoggerDelegate.errorLogger, + "getPhoneBookSearchResult - too short search string: " + searchString); + } + } + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/queryUsers", "result =", searchResult); + + return searchResult; + } + + @RequestMapping(value = {"/portalApi/adminAppsRoles"}, method = { + RequestMethod.GET}, produces = "application/json") + public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(Principal principal, + @RequestParam("user") String orgUserId, HttpServletResponse response) { + + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + + 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 Organization User ID"); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + } + + StringBuilder adminAppRoles = new StringBuilder(); + if (result != null) { + if (!result.appsRoles.isEmpty()) { + 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."); + } + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "putAppWithUserRoleStateForUser: getAppsWithAdminRoleStateForUser result is null"); + } + + logger.info(EELFLoggerDelegate.errorLogger, adminAppRoles.toString()); + + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "get result =", result); + + return result; + } + + @RequestMapping(value = {"/portalApi/adminAppsRoles"}, method = { + RequestMethod.PUT}, produces = "application/json") + public FieldsValidator putAppsWithAdminRoleStateForUser(Principal principal, + @RequestBody AppsListWithAdminRole newAppsListWithAdminRoles, HttpServletResponse response) { + + // newAppsListWithAdminRoles.appsRoles + FieldsValidator fieldsValidator = new FieldsValidator(); + StringBuilder newAppRoles = new StringBuilder(); + if (newAppsListWithAdminRoles != null) { + if (!newAppsListWithAdminRoles.appsRoles.isEmpty()) { + newAppRoles + .append("User '" + newAppsListWithAdminRoles.orgUserId + + "' has admin role to the apps = { "); + for (AppNameIdIsAdmin adminAppRole : newAppsListWithAdminRoles.appsRoles) { + if (adminAppRole.isAdmin) { + newAppRoles.append(adminAppRole.appName + " ,"); + } + } + newAppRoles.deleteCharAt(newAppRoles.length() - 1); + newAppRoles.append("}."); + } else { + newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + + "' has no Apps with Admin Role."); + } + } else { + logger.error(EELFLoggerDelegate.errorLogger, + "putAppWithUserRoleStateForUser: putAppsWithAdminRoleStateForUser result is null"); + fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + + logger.info(EELFLoggerDelegate.errorLogger, newAppRoles.toString()); + + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + + boolean changesApplied = false; + + if (!adminRolesService.isSuperAdmin(user)) { + EcompPortalUtils.setBadPermissions(user, response, "putAppsWithAdminRoleStateForUser"); + } else { + changesApplied = adminRolesService.setAppsWithAdminRoleStateForUser(newAppsListWithAdminRoles); + AuditLog auditLog = new AuditLog(); + auditLog.setUserId(user.getId()); + auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN); + if (newAppsListWithAdminRoles != null) { + auditLog.setAffectedRecordId(newAppsListWithAdminRoles.orgUserId); + } + auditLog.setComments( + EcompPortalUtils + .truncateString(newAppRoles.toString(), PortalConstants.AUDIT_LOG_COMMENT_SIZE)); + auditService.logActivity(auditLog, null); + + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, + EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, + EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + EcompPortalUtils.calculateDateTimeDifferenceForLog( + MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + if (newAppsListWithAdminRoles != null) { + logger.info(EELFLoggerDelegate.auditLogger, + EPLogUtil.formatAuditLogMessage( + "UserRolesController.putAppsWithAdminRoleStateForUser", + EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN, user.getOrgUserId(), + newAppsListWithAdminRoles.orgUserId, newAppRoles.toString())); + } + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + } + EcompPortalUtils + .logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "put result =", changesApplied); + + return fieldsValidator; + } + + + @RequestMapping(value = {"/portalApi/userAppRoles"}, method = { + RequestMethod.GET}, produces = "application/json") + public List<RoleInAppForUser> getAppRolesForUser(Principal principal, + @RequestParam("user") String orgUserId, + @RequestParam("app") Long appid, @RequestParam("externalRequest") Boolean extRequestValue, + @RequestParam("isSystemUser") Boolean isSystemUser, + HttpServletResponse response) { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + List<RoleInAppForUser> result = null; + String feErrorString = ""; + if (!adminRolesService.isAccountAdmin(user) && !adminRolesService.isRoleAdmin(user)) { + logger.debug(EELFLoggerDelegate.debugLogger, + "getAppRolesForUser: Accountadminpermissioncheck {}, RoleAdmincheck {}", + adminRolesService.isAccountAdmin(user), adminRolesService.isRoleAdmin(user)); + EcompPortalUtils.setBadPermissions(user, response, "getAppRolesForUser"); + feErrorString = EcompPortalUtils.getFEErrorString(true, response.getStatus()); + } else { + if ((!isSystemUser && EcompPortalUtils.legitimateUserId(orgUserId)) || isSystemUser) { + result = userRolesService.getAppRolesForUser(appid, orgUserId, extRequestValue, user); + logger.debug(EELFLoggerDelegate.debugLogger, "getAppRolesForUser: result {}, appId {}", + result, appid); + 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 onap 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 Organization User ID"); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + feErrorString = EcompPortalUtils.getFEErrorString(true, HttpServletResponse.SC_BAD_REQUEST); + } + } + + StringBuilder sbUserApps = new StringBuilder(); + if (result != null && !result.isEmpty()) { + 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 { + // Not sure creating an empty object will make any difference + // but would like to give it a shot for defect #DE221057 + if (result == null) { + result = new ArrayList<>(); + } + sbUserApps.append("User '" + orgUserId + "' and appid " + appid + " has no roles"); + } + logger.info(EELFLoggerDelegate.errorLogger, sbUserApps.toString()); + + EcompPortalUtils.logAndSerializeObject(logger, "/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 PortalRestResponse<String> putAppWithUserRoleStateForUser(Principal principal, + @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) { + // FieldsValidator fieldsValidator = new FieldsValidator(); + PortalRestResponse<String> portalResponse = new PortalRestResponse<>(); + StringBuilder sbUserApps = new StringBuilder(); + if (newAppRolesForUser != null) { + sbUserApps.append("User '" + newAppRolesForUser.getOrgUserId()); + if (newAppRolesForUser.getAppId() != null && !newAppRolesForUser.getAppRoles().isEmpty()) { + sbUserApps.append("' has roles = { "); + for (RoleInAppForUser appRole : newAppRolesForUser.getAppRoles()) { + if (appRole.isApplied) { + sbUserApps.append(appRole.roleName + " ,"); + } + } + sbUserApps.deleteCharAt(sbUserApps.length() - 1); + sbUserApps.append("} assigned for the app " + newAppRolesForUser.getAppId()); + } else { + sbUserApps.append("' has no roles assigned for app " + newAppRolesForUser.getAppId()); + } + } + logger.info(EELFLoggerDelegate.applicationLogger, "putAppWithUserRoleStateForUser: {}", + sbUserApps.toString()); + + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + // boolean changesApplied = false; + ExternalRequestFieldsValidator changesApplied = null; + + if (!adminRolesService.isAccountAdmin(user) && !adminRolesService.isRoleAdmin(user)) { + EcompPortalUtils.setBadPermissions(user, response, "putAppWithUserRoleStateForUser"); + } else if (newAppRolesForUser == null) { + logger.error(EELFLoggerDelegate.errorLogger, + "putAppWithUserRoleStateForUser: newAppRolesForUser is null"); + } else { + changesApplied = userRolesService.setAppWithUserRoleStateForUser(user, newAppRolesForUser); + try { + if (changesApplied.isResult()) { + logger.info(EELFLoggerDelegate.applicationLogger, + "putAppWithUserRoleStateForUser: succeeded for app {}, user {}", + newAppRolesForUser.getAppId(), + newAppRolesForUser.getAppId()); + + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, + EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + AuditLog auditLog = new AuditLog(); + auditLog.setUserId(user.getId()); + auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_USER); + auditLog.setAffectedRecordId(newAppRolesForUser.getOrgUserId()); + auditLog.setComments(EcompPortalUtils.truncateString(sbUserApps.toString(), + PortalConstants.AUDIT_LOG_COMMENT_SIZE)); + auditService.logActivity(auditLog, null); + + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, + EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + EcompPortalUtils.calculateDateTimeDifferenceForLog( + MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + logger.info(EELFLoggerDelegate.auditLogger, + EPLogUtil.formatAuditLogMessage( + "UserRolesController.putAppWithUserRoleStateForUser", + EcompAuditLog.CD_ACTIVITY_UPDATE_USER, user.getOrgUserId(), + newAppRolesForUser.getOrgUserId(), sbUserApps.toString())); + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", null); + + } + if (!changesApplied.isResult()) { + throw new Exception(changesApplied.getDetailMessage()); + } + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "putAppWithUserRoleStateForUser: failed for app {}, user {}", + newAppRolesForUser.getAppId(), + newAppRolesForUser.getOrgUserId(), e); + portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), null); + } + } + + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "put result =", changesApplied); + return portalResponse; + } + + @RequestMapping(value = {"/portalApi/updateRemoteUserProfile"}, method = { + RequestMethod.GET}, produces = "application/json") + public PortalRestResponse<String> updateRemoteUserProfile(HttpServletRequest request) { + + 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) { + logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, updateRemoteUserFlag, e.getMessage()); + } + return new PortalRestResponse<>(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 { + logger.debug(EELFLoggerDelegate.debugLogger, "/portalApi/app/{}/users was invoked", appId); + return userRolesService.getUsersFromAppEndpoint(appId); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getUsersFromAppEndpoint failed", e); + return new ArrayList<>(); + } + } + + @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(logger, "/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<FnRole> importRolesFromRemoteApplication(HttpServletRequest request, + @PathVariable("appId") Long appId) + throws HTTPException { + List<FnRole> rolesList = userRolesService.importRolesFromRemoteApplication(appId); + EcompPortalUtils.logAndSerializeObject(logger, "/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(logger, "/portalApi/app/{appId}/user/{orgUserId}/roles", + "response for appId='" + appId + "' and orgUserId='" + orgUserId + "'", roles[0]); + return roles[0]; + } + + @RequestMapping(value = {"/portalApi/saveUserAppRoles"}, method = { + RequestMethod.PUT}, produces = "application/json") + public FieldsValidator putAppWithUserRoleRequest(Principal principal, + @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) { + FieldsValidator fieldsValidator = null; + try { + + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + fieldsValidator = userRolesService.putUserAppRolesRequest(newAppRolesForUser, user); + response.setStatus(fieldsValidator.httpStatusCode.intValue()); + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleRequest failed", e); + + } + // return fieldsValidator; + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/saveUserAppRoles", "PUT result =", + response.getStatus()); + return fieldsValidator; + } + + @RequestMapping(value = {"/portalApi/appCatalogRoles"}, method = { + RequestMethod.GET}, produces = "application/json") + public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(Principal principal, + @RequestParam("appName") String appName) { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + List<EPUserAppCatalogRoles> userAppRoleList = null; + try { + userAppRoleList = userRolesService.getUserAppCatalogRoles(user, appName); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "putUserWidgetsSortPref failed", e); + + } + Collections.sort(userAppRoleList, getUserAppCatalogRolesComparator); + EcompPortalUtils + .logAndSerializeObject(logger, "/portalApi/userApplicationRoles", "result =", userAppRoleList); + + return userAppRoleList; + + } + + private Comparator<EPUserAppCatalogRoles> getUserAppCatalogRolesComparator = + Comparator.comparing(EPUserAppCatalogRoles::getRolename); + + @RequestMapping(value = "/portalApi/externalRequestAccessSystem", method = RequestMethod.GET, + produces = "application/json") + public ExternalSystemAccess readExternalRequestAccess(HttpServletRequest request) { + ExternalSystemAccess result = null; + try { + result = userRolesService.getExternalRequestAccess(); + EcompPortalUtils + .logAndSerializeObject(logger, "/portalApi/externalRequestAccessSystem", "GET result =", + result); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "readExternalRequestAccess failed: " + e.getMessage()); + } + return result; + } +*/ + + + @RequestMapping(value = {"/portalApi/checkIfUserIsSuperAdmin"}, method = RequestMethod.GET, + produces = "application/json") + public boolean checkIfUserIsSuperAdmin(Principal principal) { + FnUser user = fnUserService.loadUserByUsername(principal.getName()); + + boolean isSuperAdmin = false; + try { + isSuperAdmin = adminRolesService.isSuperAdmin(user.getOrgUserId()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "checkIfUserIsSuperAdmin failed: " + e.getMessage()); + } + return isSuperAdmin; + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/controller/WebAnalyticsExtAppController.java b/portal-BE/src/main/java/org/onap/portal/controller/WebAnalyticsExtAppController.java new file mode 100644 index 00000000..849b2620 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/controller/WebAnalyticsExtAppController.java @@ -0,0 +1,256 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.controller; + +import io.swagger.annotations.ApiOperation; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import javax.servlet.http.HttpServletRequest; +import lombok.NoArgsConstructor; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; +import org.onap.portal.domain.db.fn.FnApp; +import org.onap.portal.domain.dto.ecomp.EcompAuditLog; +import org.onap.portal.domain.dto.transport.Analytics; +import org.onap.portal.logging.aop.EPAuditLog; +import org.onap.portal.logging.aop.EPEELFLoggerAdvice; +import org.onap.portal.logging.logic.EPLogUtil; +import org.onap.portal.service.WidgetMService; +import org.onap.portal.service.fn.old.AppsCacheService; +import org.onap.portal.utils.EPCommonSystemProperties; +import org.onap.portal.utils.EcompPortalUtils; +import org.onap.portal.utils.PortalConstants; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse; +import org.onap.portalsdk.core.util.SystemProperties; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.util.concurrent.FailureCallback; +import org.springframework.util.concurrent.ListenableFuture; +import org.springframework.util.concurrent.SuccessCallback; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.AsyncRestTemplate; + +@RestController +@RequestMapping(PortalConstants.REST_AUX_API) +@Configuration +@EnableAspectJAutoProxy +@EPAuditLog +@NoArgsConstructor +public class WebAnalyticsExtAppController { + + private static final String MACHINE_LEARNING_SERVICE_CTX = "/ml_api"; + private static final String REGISTER_ACTION = MACHINE_LEARNING_SERVICE_CTX + "/" + "registerAction"; + private static final String CONSUL_ML_SERVICE_ID = "machine-learning"; + private static final String APP_KEY = "uebkey"; + private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WebAnalyticsExtAppController.class); + private final AsyncRestTemplate restTemplate = new AsyncRestTemplate(); + private final SuccessCallback<ResponseEntity<String>> successCallback = arg -> logger.info(EELFLoggerDelegate.debugLogger, arg.getBody()); + private final FailureCallback failureCallback = arg -> logger.error(EELFLoggerDelegate.errorLogger, "storeAuxAnalytics failed", arg); + + private WidgetMService widgetMService; + private AppsCacheService appCacheService; + + @Autowired + public WebAnalyticsExtAppController(final WidgetMService widgetMService, + final AppsCacheService appCacheService) { + this.widgetMService = widgetMService; + this.appCacheService = appCacheService; + } + + /** + * Answers requests from partner applications for a file that is expected to + * contain javascript to support web analytics. + * + * @param request + * HttpServletRequest + * @return String + */ + @ApiOperation(value = "Gets javascript with functions that support gathering and reporting web analytics.", response = String.class) + @RequestMapping(value = { "/analytics" }, method = RequestMethod.GET, produces = "application/javascript") + public String getAnalyticsScript(HttpServletRequest request) { + String responseText = ""; + FnApp app = null; + String version = ""; + try { + app = getApp(request); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + " Error retrieving Application to capture app name for analytics; Proceeding with empty app name"); + } + if (app != null) { + String restEndPoint = app.getAppRestEndpoint(); + if(restEndPoint.indexOf("/api")!=-1) { + version = restEndPoint.substring(restEndPoint.indexOf("api")); + } + } + String endPoint = "/storeAnalytics"; + if(StringUtils.isNotBlank(version)) { + endPoint = version + "/storeAnalytics"; + } + + final String fileName = "analytics.txt"; + try (InputStream analyticsFileStream = this.getClass().getClassLoader().getResourceAsStream(fileName)) { + responseText = IOUtils.toString(Objects.requireNonNull(analyticsFileStream), StandardCharsets.UTF_8.name()); + } catch (IOException e) { + logger.error(EELFLoggerDelegate.errorLogger, "Error reading contents of the file " + fileName, e); + } + + String feURLContext = SystemProperties.getProperty("frontend_url"); + String feURL = feURLContext.substring(0, feURLContext.lastIndexOf('/')); + responseText = responseText.replace("PORTAL_ENV_URL", feURL); + responseText = responseText.replace("$END_POINT", endPoint); + return responseText; + } + + /** + * Accepts data from partner applications with web analytics data. + * + * @param request + * HttpServletRequest + * @param analyticsMap + * Analytics + * @return PortalAPIResponse + */ + @RequestMapping(value = { "/storeAnalytics" }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + @ApiOperation(value = "Accepts data from partner applications with web analytics data.", response = PortalAPIResponse.class) + public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, @RequestBody Analytics analyticsMap) { + try { + MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + String appName = ""; + try { + appName = getAppName(request, appName); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + " Error retrieving Application to capture app name for analytics; Proceeding with empty app name"); + } + + try { + storeAuxAnalytics(analyticsMap, appName); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + " Error retrieving Application to capture app name for analytics; Proceeding with empty app name"); + } + + MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC()); + + EcompPortalUtils.calculateDateTimeDifferenceForLog( + MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), + MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); + logger.info(EELFLoggerDelegate.auditLogger, + EPLogUtil.formatStoreAnalyticsAuditLogMessage(analyticsMap.getUserid(), appName, + "WebAnalyticsExtAppController.postWebAnalyticsData", + EcompAuditLog.CD_ACTIVITY_STORE_ANALYTICS, analyticsMap.getAction(), analyticsMap.getPage(), + analyticsMap.getFunction(), analyticsMap.getType())); + + MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); + MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); + MDC.remove(SystemProperties.MDC_TIMER); + + return new PortalAPIResponse(true, "success"); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "storeAnalytics failed", e); + return new PortalAPIResponse(true, "error"); + } + } + + private String getAppName(HttpServletRequest request, String appName) { + + FnApp appRecord = getApp(request); + if (appRecord != null) { + appName = appRecord.getAppName(); + } + return appName; + } + + private FnApp getApp(HttpServletRequest request) { + String appKeyValue = request.getHeader(APP_KEY); + FnApp appRecord = null; + if (appKeyValue == null || appKeyValue.equals("")) { + logger.error(EELFLoggerDelegate.errorLogger, " App Key unavailable; Proceeding with null app name"); + } else { + appRecord = appCacheService.getAppFromUeb(appKeyValue); + } + return appRecord; + } + + private void storeAuxAnalytics(Analytics analyticsMap, String appName) { + logger.info(EELFLoggerDelegate.debugLogger, + " Registering an action for recommendation: AppName/Function/UserId " + appName + "/" + + analyticsMap.getFunction() + "/" + analyticsMap.getUserid()); + + Map<String, String> requestMapping = new HashMap<>(); + requestMapping.put("id", analyticsMap.getUserid()); + requestMapping.put("action", appName + "|" + analyticsMap.getFunction()); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + + // set your entity to send + HttpEntity<Map<String, String>> entity = new HttpEntity<>(requestMapping, headers); + + // send it! + ListenableFuture<ResponseEntity<String>> out = restTemplate.exchange( + EcompPortalUtils.widgetMsProtocol() + "://" + + widgetMService.getServiceLocation(CONSUL_ML_SERVICE_ID, + SystemProperties.getProperty("microservices.m-learn.local.port")) + + REGISTER_ACTION, + HttpMethod.POST, entity, String.class); + out.addCallback(successCallback, failureCallback); + } + +} diff --git a/portal-BE/src/main/java/org/onap/portal/controller/WebAnalyticsExtAppVersionController.java b/portal-BE/src/main/java/org/onap/portal/controller/WebAnalyticsExtAppVersionController.java new file mode 100644 index 00000000..87be5439 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/controller/WebAnalyticsExtAppVersionController.java @@ -0,0 +1,77 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.onap.portal.annotation.ApiVersion; +import org.onap.portal.domain.dto.transport.Analytics; +import org.onap.portal.logging.aop.EPAuditLog; +import org.onap.portalsdk.core.onboarding.crossapi.PortalAPIResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; + +@Configuration +@EnableAspectJAutoProxy +@EPAuditLog +@ApiVersion +public class WebAnalyticsExtAppVersionController { + + private final WebAnalyticsExtAppController webAnalyticsExtAppController; + + @Autowired + public WebAnalyticsExtAppVersionController(final + WebAnalyticsExtAppController webAnalyticsExtAppController) { + this.webAnalyticsExtAppController = webAnalyticsExtAppController; + } + + @ApiVersion(max = "v3", service = "/v3/analytics", min = 0,method = "GET") + public String getAnalyticsScript(HttpServletRequest request, HttpServletResponse response) throws Exception { + return webAnalyticsExtAppController.getAnalyticsScript(request); + } + + @ApiVersion(max = "v3", service = "/v3/storeAnalytics", min = 0,method = "POST") + public PortalAPIResponse storeAnalyticsScript(HttpServletRequest request, HttpServletResponse response, Analytics analyticsMap) throws Exception { + return webAnalyticsExtAppController.storeAnalyticsScript(request, analyticsMap); + } + +} diff --git a/portal-BE/src/main/java/org/onap/portal/controller/WidgetMSController.java b/portal-BE/src/main/java/org/onap/portal/controller/WidgetMSController.java new file mode 100644 index 00000000..b9434820 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/controller/WidgetMSController.java @@ -0,0 +1,84 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.onap.portal.domain.dto.ecomp.PortalRestResponse; +import org.onap.portal.domain.dto.ecomp.PortalRestStatusEnum; +import org.onap.portal.service.WidgetMService; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/portalApi/consul") +public class WidgetMSController { + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetMSController.class); + + private final WidgetMService widgetMService; + + @Autowired + public WidgetMSController(final WidgetMService widgetMService) { + this.widgetMService = widgetMService; + } + + // Get location of a healthy node running our service + @RequestMapping(value = { "/service/{service}" }, method = RequestMethod.GET, produces = "application/json") + public PortalRestResponse<String> getServiceLocation(HttpServletRequest request, HttpServletResponse response, + @PathVariable("service") String service) { + + try { + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Success!", + widgetMService.getServiceLocation(service, null)); + } + catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Couldn't get the service location"); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Error!", + "Couldn't get the service location"); + + } + } + +} diff --git a/portal-BE/src/main/java/org/onap/portal/controller/WidgetsCatalogController.java b/portal-BE/src/main/java/org/onap/portal/controller/WidgetsCatalogController.java index decf625d..07695aeb 100644 --- a/portal-BE/src/main/java/org/onap/portal/controller/WidgetsCatalogController.java +++ b/portal-BE/src/main/java/org/onap/portal/controller/WidgetsCatalogController.java @@ -49,12 +49,12 @@ import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; +import org.onap.portal.domain.db.ep.EpWidgetCatalogParameter; import org.onap.portal.domain.db.fn.FnUser; import org.onap.portal.domain.dto.PortalRestResponse; import org.onap.portal.domain.dto.PortalRestStatusEnum; import org.onap.portal.domain.dto.ecomp.MicroserviceParameter; import org.onap.portal.domain.dto.ecomp.WidgetCatalog; -import org.onap.portal.domain.dto.ecomp.WidgetCatalogParameter; import org.onap.portal.domain.dto.ecomp.WidgetParameterResult; import org.onap.portal.domain.dto.ecomp.WidgetServiceHeaders; import org.onap.portal.logging.aop.EPAuditLog; @@ -301,7 +301,8 @@ public class WidgetsCatalogController { } @GetMapping(value = {"/portalApi/microservices/parameters/{widgetId}"}) - public PortalRestResponse<List<WidgetParameterResult>> getWidgetParameterResult(Principal principal, HttpServletRequest request, + public PortalRestResponse<List<WidgetParameterResult>> getWidgetParameterResult(Principal principal, + HttpServletRequest request, @PathVariable("widgetId") long widgetId) throws Exception { FnUser user = fnUserService.loadUserByUsername(principal.getName()); @@ -317,14 +318,15 @@ public class WidgetsCatalogController { return new PortalRestResponse<>(PortalRestStatusEnum.WARN, "No service parameters for this widget", list); } else { - List<MicroserviceParameter> defaultParam = epMicroserviceParameterService.getParametersById(serviceId); + List<MicroserviceParameter> defaultParam = epMicroserviceParameterService + .getParametersById(serviceId); for (MicroserviceParameter param : defaultParam) { WidgetParameterResult userResult = new WidgetParameterResult(); userResult.setParamId(param.getId()); userResult.setDefaultValue(param.getPara_value()); userResult.setParamKey(param.getPara_key()); - WidgetCatalogParameter userValue = epWidgetCatalogParameterService - .getUserParamById(widgetId, user.getId(), + EpWidgetCatalogParameter userValue = epWidgetCatalogParameterService + .getUserParamById(widgetId, user.getUserId(), param.getId()); if (userValue == null) { userResult.setUserValue(param.getPara_value()); @@ -334,17 +336,23 @@ public class WidgetsCatalogController { list.add(userResult); } } - return new PortalRestResponse<List<WidgetParameterResult>>(PortalRestStatusEnum.OK, "SUCCESS", list); + return new PortalRestResponse<>(PortalRestStatusEnum.OK, "SUCCESS", list); } @GetMapping(value = {"/portalApi/microservices/services/{paramId}"}) - public List<WidgetCatalogParameter> getUserParameterById(@PathVariable("paramId") long paramId) { + public List<EpWidgetCatalogParameter> getUserParameterById(@PathVariable("paramId") long paramId) { return epWidgetCatalogParameterService.getUserParameterById(paramId); } @DeleteMapping(value = {"/portalApi/microservices/services/{paramId}"}) - public void deleteUserParameterById(@PathVariable("paramId") long paramId) { - epWidgetCatalogParameterService.deleteUserParameterById(paramId); + public boolean deleteUserParameterById(@PathVariable("paramId") long paramId) { + try { + epWidgetCatalogParameterService.deleteUserParameterById(paramId); + return true; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + return false; + } } @GetMapping(value = {"/portalApi/microservices/download/{widgetId}"}) @@ -395,29 +403,34 @@ public class WidgetsCatalogController { } @PostMapping(value = {"/portalApi/microservices/parameters"}) - public PortalRestResponse<String> saveWidgetParameter(Principal principal, HttpServletRequest request, - @RequestBody WidgetCatalogParameter widgetParameters) { + public PortalRestResponse<String> saveWidgetParameter(Principal principal, + @RequestBody EpWidgetCatalogParameter widgetParameters) { FnUser user = fnUserService.loadUserByUsername(principal.getName()); - widgetParameters.setUserId(user.getId()); + widgetParameters.setUserId(user); try { - WidgetCatalogParameter oldParam = epWidgetCatalogParameterService - .getUserParamById(widgetParameters.getWidgetId(), - widgetParameters.getUserId(), widgetParameters.getParamId()); + EpWidgetCatalogParameter oldParam = epWidgetCatalogParameterService + .getUserParamById(widgetParameters.getWidgetId().getWidgetId(), + widgetParameters.getUserId().getUserId(), widgetParameters.getParamId().getId()); if (oldParam != null) { - widgetParameters.setId(oldParam.getId()); + oldParam.setParamId(widgetParameters.getParamId()); + oldParam.setUserId(widgetParameters.getUserId()); + oldParam.setUserValue(widgetParameters.getUserValue()); + oldParam.setWidgetId(widgetParameters.getWidgetId()); + epWidgetCatalogParameterService.saveUserParameter(oldParam); + } else { + epWidgetCatalogParameterService.saveUserParameter(widgetParameters); } - epWidgetCatalogParameterService.saveUserParameter(widgetParameters); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "saveWidgetParameter failed", e); - return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage()); + return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage()); } return new PortalRestResponse<>(PortalRestStatusEnum.OK, "SUCCESS", ""); } @GetMapping(value = {"/portalApi/microservices/uploadFlag"}) public String getUploadFlag() { - String uplaodFlag = ""; + String uplaodFlag; try { uplaodFlag = SystemProperties.getProperty(EPCommonSystemProperties.MS_WIDGET_UPLOAD_FLAG); } catch (Exception e) { diff --git a/portal-BE/src/main/java/org/onap/portal/controller/WidgetsCatalogMarkupController.java b/portal-BE/src/main/java/org/onap/portal/controller/WidgetsCatalogMarkupController.java index 06dd62da..e63de2e8 100644 --- a/portal-BE/src/main/java/org/onap/portal/controller/WidgetsCatalogMarkupController.java +++ b/portal-BE/src/main/java/org/onap/portal/controller/WidgetsCatalogMarkupController.java @@ -77,14 +77,8 @@ public class WidgetsCatalogMarkupController { static { // for localhost testing only - javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() { - - public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) { - if (hostname.equals("localhost")) { - return true; - } - return false; - } + javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier((hostname, sslSession) -> { + return hostname.equals("localhost"); }); } diff --git a/portal-BE/src/main/java/org/onap/portal/controller/WidgetsController.java b/portal-BE/src/main/java/org/onap/portal/controller/WidgetsController.java index c2915275..556c7ef3 100644 --- a/portal-BE/src/main/java/org/onap/portal/controller/WidgetsController.java +++ b/portal-BE/src/main/java/org/onap/portal/controller/WidgetsController.java @@ -43,7 +43,6 @@ package org.onap.portal.controller; import java.io.IOException; import java.security.Principal; import java.util.List; -import java.util.Optional; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.onap.portal.domain.db.fn.FnUser; @@ -59,9 +58,9 @@ import org.onap.portal.utils.EcompPortalUtils; import org.onap.portal.validation.DataValidator; import org.onap.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.http.MediaType; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -99,7 +98,6 @@ public class WidgetsController { HttpServletResponse response) { FnUser user = fnUserService.loadUserByUsername(principal.getName()); List<OnboardingWidget> onboardingWidgets = null; - if (user.getGuest()) { EcompPortalUtils.setBadPermissions(user, response, "getOnboardingWidgets"); } else { @@ -119,60 +117,50 @@ public class WidgetsController { } @PutMapping(value = {"/portalApi/widgets/{widgetId}"}, produces = MediaType.APPLICATION_JSON_VALUE) - public FieldsValidator putOnboardingWidget(Principal principal, HttpServletRequest request, - @PathVariable("widgetId") Long widgetId, + @PreAuthorize("hasRole('System_Administrator')") + public FieldsValidator putOnboardingWidget(Principal principal, @PathVariable("widgetId") Long widgetId, @RequestBody OnboardingWidget onboardingWidget, HttpServletResponse response) { FnUser user = fnUserService.loadUserByUsername(principal.getName()); FieldsValidator fieldsValidator = null; - if (onboardingWidget != null) { - if (!dataValidator.isValid(onboardingWidget)) { - fieldsValidator = new FieldsValidator(); - fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_NOT_ACCEPTABLE); - return fieldsValidator; - } - } - if (userHasPermissions(user, response, "putOnboardingWidget")) { - assert onboardingWidget != null; - onboardingWidget.setId(widgetId); - onboardingWidget.normalize(); - fieldsValidator = widgetService.setOnboardingWidget(user, onboardingWidget); + assert onboardingWidget != null; + onboardingWidget.setId(widgetId); + onboardingWidget.normalize(); + try { + fieldsValidator = widgetService.setOnboardingWidget(user.getUserId(), onboardingWidget); response.setStatus(fieldsValidator.getHttpStatusCode().intValue()); + } catch (IllegalArgumentException e) { + fieldsValidator = new FieldsValidator(); + fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_NOT_ACCEPTABLE); + fieldsValidator.addProblematicFieldName(e.getMessage()); + return fieldsValidator; } + EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/widgets/" + widgetId, "GET result =", response.getStatus()); return fieldsValidator; } - private boolean userHasPermissions(FnUser user, HttpServletResponse response, String invocator) { - if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdmin(user)) { - EcompPortalUtils.setBadPermissions(user, response, invocator); - return false; - } - return true; - } - @PostMapping(value = {"/portalApi/widgets"}, produces = MediaType.APPLICATION_JSON_VALUE) - public FieldsValidator postOnboardingWidget(Principal principal, HttpServletRequest request, - @RequestBody OnboardingWidget onboardingWidget, HttpServletResponse response) { + @PreAuthorize("hasRole('System_Administrator') and hasRole('Account_Administrator')") + public FieldsValidator postOnboardingWidget(Principal principal, HttpServletResponse response, + @RequestBody OnboardingWidget onboardingWidget) { FnUser user = fnUserService.loadUserByUsername(principal.getName()); - FieldsValidator fieldsValidator = null; + FieldsValidator fieldsValidator; - if (onboardingWidget != null) { - if (!dataValidator.isValid(onboardingWidget)) { - fieldsValidator = new FieldsValidator(); - fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_NOT_ACCEPTABLE); - return fieldsValidator; - } - } + onboardingWidget.setId(null); + onboardingWidget.normalize(); - if (userHasPermissions(user, response, "postOnboardingWidget")) { - onboardingWidget.setId(null); - onboardingWidget.normalize(); - fieldsValidator = widgetService.setOnboardingWidget(user, onboardingWidget); - response.setStatus(fieldsValidator.getHttpStatusCode().intValue()); + try { + fieldsValidator = widgetService.setOnboardingWidget(user.getUserId(), onboardingWidget); + } catch (IllegalArgumentException e) { + fieldsValidator = new FieldsValidator(); + fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_NOT_ACCEPTABLE); + fieldsValidator.addProblematicFieldName(e.getMessage()); + return fieldsValidator; } + response.setStatus(fieldsValidator.getHttpStatusCode().intValue()); EcompPortalUtils .logAndSerializeObject(logger, "/portalApi/widgets", "POST result =", response.getStatus()); @@ -180,15 +168,14 @@ public class WidgetsController { } @DeleteMapping(value = {"/portalApi/widgets/{widgetId}"}, produces = MediaType.APPLICATION_JSON_VALUE) - public FieldsValidator deleteOnboardingWidget(Principal principal, HttpServletRequest request, - @PathVariable("widgetId") Long widgetId, HttpServletResponse response) { + @PreAuthorize("hasRole('System_Administrator') and hasRole('Account_Administrator')") + public FieldsValidator deleteOnboardingWidget(Principal principal, HttpServletResponse response, + @PathVariable("widgetId") Long widgetId) { FnUser user = fnUserService.loadUserByUsername(principal.getName()); - FieldsValidator fieldsValidator = null; + FieldsValidator fieldsValidator; - if (userHasPermissions(user, response, "deleteOnboardingWidget")) { - fieldsValidator = widgetService.deleteOnboardingWidget(user, widgetId); - response.setStatus(fieldsValidator.getHttpStatusCode().intValue()); - } + fieldsValidator = widgetService.deleteOnboardingWidget(user, widgetId); + response.setStatus(fieldsValidator.getHttpStatusCode().intValue()); EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/widgets/" + widgetId, "DELETE result =", response.getStatus()); @@ -196,27 +183,21 @@ public class WidgetsController { } @PutMapping(value = {"portalApi/widgetCatalogSelection"}, produces = MediaType.APPLICATION_JSON_VALUE) - public FieldsValidator putWidgetCatalogSelection(Principal principal, HttpServletRequest request, + public FieldsValidator putWidgetCatalogSelection(Principal principal, @RequestBody WidgetCatalogPersonalization persRequest, HttpServletResponse response) throws IOException { FieldsValidator result = new FieldsValidator(); FnUser user = fnUserService.loadUserByUsername(principal.getName()); - if (persRequest != null) { - if (!dataValidator.isValid(persRequest)) { - result.setHttpStatusCode((long) HttpServletResponse.SC_NOT_ACCEPTABLE); - return result; - } - } try { - if (persRequest.getWidgetId() == null || user == null) { - EcompPortalUtils.setBadPermissions(user, response, "putWidgetCatalogSelection"); - } else { - persUserWidgetService - .setPersUserAppValue(user, persRequest.getWidgetId(), persRequest.getSelect()); - } + assert persRequest != null; + persUserWidgetService + .setPersUserAppValue(user, persRequest); + } catch (IllegalArgumentException iae) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed in putAppCatalogSelection", iae); + response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, iae.getMessage()); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "Failed in putAppCatalogSelection", e); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } result.setHttpStatusCode((long) HttpServletResponse.SC_OK); return result; diff --git a/portal-BE/src/main/java/org/onap/portal/dao/ep/EpMicroserviceParameterDao.java b/portal-BE/src/main/java/org/onap/portal/dao/ep/EpMicroserviceParameterDao.java index 4bcca7ef..add897c9 100644 --- a/portal-BE/src/main/java/org/onap/portal/dao/ep/EpMicroserviceParameterDao.java +++ b/portal-BE/src/main/java/org/onap/portal/dao/ep/EpMicroserviceParameterDao.java @@ -55,7 +55,5 @@ public interface EpMicroserviceParameterDao extends JpaRepository<EpMicroservice @Query void deleteByServiceId(@Param("SERVICEID") Long userId); @Query - void deleteMicroserviceParameterById(@Param("PARAMID") Long userId); - @Query List<EpMicroserviceParameter> getParametersById(@Param("SERVICEID") long serviceId); } diff --git a/portal-BE/src/main/java/org/onap/portal/dao/ep/EpWidgetCatalogParameterDao.java b/portal-BE/src/main/java/org/onap/portal/dao/ep/EpWidgetCatalogParameterDao.java index 04c12324..c5ec1248 100644 --- a/portal-BE/src/main/java/org/onap/portal/dao/ep/EpWidgetCatalogParameterDao.java +++ b/portal-BE/src/main/java/org/onap/portal/dao/ep/EpWidgetCatalogParameterDao.java @@ -4,6 +4,7 @@ import java.util.List; import java.util.Optional; import org.onap.portal.domain.db.ep.EpWidgetCatalogParameter; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; @@ -17,6 +18,7 @@ public interface EpWidgetCatalogParameterDao extends JpaRepository<EpWidgetCatal Optional<List<EpWidgetCatalogParameter>> retrieveByParamId(@Param("PARAMID") Long paramId); @Query + @Modifying void deleteWidgetCatalogParameter(@Param("PARAMID") Long paramId); @Query diff --git a/portal-BE/src/main/java/org/onap/portal/dao/fn/FnRoleDao.java b/portal-BE/src/main/java/org/onap/portal/dao/fn/FnRoleDao.java new file mode 100644 index 00000000..66f4758c --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/dao/fn/FnRoleDao.java @@ -0,0 +1,57 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.dao.fn; + +import java.util.List; +import org.onap.portal.domain.db.fn.FnRole; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +@Repository +@Transactional +public interface FnRoleDao extends JpaRepository<FnRole, Long> { + + @Query + List<FnRole> retrieveAppRoleByAppRoleIdAndByAppId(final @Param("appId") Long appId, final @Param("appRoleId") Long appRoleId); +} diff --git a/portal-BE/src/main/java/org/onap/portal/dao/fn/FnUserRoleDao.java b/portal-BE/src/main/java/org/onap/portal/dao/fn/FnUserRoleDao.java new file mode 100644 index 00000000..9c0a6fef --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/dao/fn/FnUserRoleDao.java @@ -0,0 +1,65 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.dao.fn; + +import java.util.List; +import java.util.Optional; +import org.onap.portal.domain.db.fn.FnUserRole; +import org.onap.portal.domain.dto.ecomp.UserRole; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +@Repository +@Transactional +public interface FnUserRoleDao extends JpaRepository<FnUserRole, Long> { + + @Query + Optional<List<FnUserRole>> getAdminUserRoles(final @Param("userId") Long userId, final @Param("roleId") Long roleId, final @Param("appId") Long appId); + + @Query + List<UserRole> isSuperAdmin(final @Param("orgUserId") String orgUserId, final @Param("roleId") Long roleId, final @Param("appId") Long appId); + + @Query + List<FnUserRole> getUserRolesForRoleIdAndAppId(final @Param("roleId") Long roleId, final @Param("appId") Long appId); +} diff --git a/portal-BE/src/main/java/org/onap/portal/dao/fn/FnWidgetDao.java b/portal-BE/src/main/java/org/onap/portal/dao/fn/FnWidgetDao.java index a47a1a0d..9c3e7a1f 100644 --- a/portal-BE/src/main/java/org/onap/portal/dao/fn/FnWidgetDao.java +++ b/portal-BE/src/main/java/org/onap/portal/dao/fn/FnWidgetDao.java @@ -40,8 +40,12 @@ package org.onap.portal.dao.fn; +import java.util.List; +import java.util.Optional; import org.onap.portal.domain.db.fn.FnWidget; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @@ -49,4 +53,6 @@ import org.springframework.transaction.annotation.Transactional; @Transactional public interface FnWidgetDao extends JpaRepository<FnWidget, Long> { + @Query + Optional<List<FnWidget>> getForUrlNameAndAppId(final @Param("URL") String url, final @Param("NAME") String name, final @Param("APPID") Long appId); } diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpMicroserviceParameter.java b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpMicroserviceParameter.java index 554dd7b5..36c073ac 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpMicroserviceParameter.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpMicroserviceParameter.java @@ -59,6 +59,7 @@ import javax.persistence.Table; import javax.validation.constraints.Digits; import javax.validation.constraints.Size; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -82,11 +83,7 @@ CREATE TABLE `ep_microservice_parameter` ( query = "DELETE FROM EpMicroserviceParameter WHERE service_id =:SERVICEID"), @NamedQuery( name = "EpMicroserviceParameter.getParametersById", - query = "FROM EpMicroserviceParameter WHERE service_id =:SERVICEID"), - @NamedQuery( - name = "EpMicroserviceParameter.deleteMicroserviceParameterById", - query = "DELETE FROM EpMicroserviceParameter WHERE id =:PARAMID" - ) + query = "FROM EpMicroserviceParameter WHERE service_id =:SERVICEID") }) @Table(name = "ep_microservice_parameter", indexes = { @@ -94,13 +91,14 @@ CREATE TABLE `ep_microservice_parameter` ( }) @NoArgsConstructor @AllArgsConstructor +@Builder @Getter @Setter @Entity public class EpMicroserviceParameter implements Serializable { @Id - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", length = 11, nullable = false) @Digits(integer = 11, fraction = 0) private Long id; diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpPersUserWidgetSel.java b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpPersUserWidgetSel.java index 9cee72a3..4b2785f1 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpPersUserWidgetSel.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpPersUserWidgetSel.java @@ -82,7 +82,7 @@ CREATE TABLE `ep_pers_user_widget_sel` ( @NamedQueries({ @NamedQuery( name = "EpPersUserWidgetSel.getEpPersUserWidgetSelForUserIdAndWidgetId", - query = "FROM EpPersUserWidgetSel WHERE userId = :USERID and widgetId = :WIDGETID") + query = "FROM EpPersUserWidgetSel WHERE userId.userId = :USERID and widgetId.widgetId = :WIDGETID") }) @Table(name = "ep_pers_user_widget_sel", uniqueConstraints = { @UniqueConstraint(columnNames = {"user_id", "widget_id"}) diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpWidgetCatalog.java b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpWidgetCatalog.java index a19af285..061aafc4 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpWidgetCatalog.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpWidgetCatalog.java @@ -60,6 +60,7 @@ import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -83,11 +84,11 @@ CREATE TABLE `ep_widget_catalog` ( @Getter @Setter @Entity +@Builder public class EpWidgetCatalog implements Serializable { @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "widget_id", length = 11, nullable = false) - @Digits(integer = 11, fraction = 0) + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "widget_id", nullable = false) private Long widgetId; @Column(name = "wdg_name", length = 100, columnDefinition = "varchar(100) default '?'", nullable = false) @Size(max = 100) @@ -106,12 +107,9 @@ public class EpWidgetCatalog implements Serializable { @NotNull @SafeHtml private String wdgFileLoc; - @Column(name = "all_user_flag", length = 1, columnDefinition = "char(1) not null default 'N'", nullable = false) - @Pattern(regexp = "[YNyn]") - @Size(max = 1) - @SafeHtml + @Column(name = "all_user_flag", length = 1, columnDefinition = "boolean default '0'", nullable = false) @NotNull - private String allUserFlag; + private Boolean allUserFlag; @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinTable( name = "ep_widget_microservice", diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpWidgetCatalogParameter.java b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpWidgetCatalogParameter.java index 2ac07cc3..ec6bb563 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpWidgetCatalogParameter.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpWidgetCatalogParameter.java @@ -59,11 +59,13 @@ import javax.validation.constraints.Digits; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.validator.constraints.SafeHtml; import org.onap.portal.domain.db.fn.FnUser; +import org.onap.portal.domain.dto.DomainVo; /* CREATE TABLE `ep_widget_catalog_parameter` ( @@ -82,16 +84,17 @@ CREATE TABLE `ep_widget_catalog_parameter` ( ) */ + @NamedQueries({ @NamedQuery( name = "EpWidgetCatalogParameter.retrieveByParamId", - query = "FROM EpWidgetCatalogParameter WHERE paramId = :PARAMID"), + query = "FROM EpWidgetCatalogParameter WHERE paramId.id = :PARAMID"), @NamedQuery( name = "EpWidgetCatalogParameter.deleteWidgetCatalogParameter", - query = "DELETE FROM EpWidgetCatalogParameter WHERE paramId = :PARAMID"), + query = "DELETE FROM EpWidgetCatalogParameter WHERE paramId.id = :PARAMID"), @NamedQuery( name = "EpWidgetCatalogParameter.getUserParamById", - query = "FROM EpWidgetCatalogParameter WHERE paramId = :PARAMID and userId = :USERID and widgetId = :WIDGETID" + query = "FROM EpWidgetCatalogParameter WHERE paramId.id = :PARAMID and userId.userId = :USERID and widgetId.widgetId = :WIDGETID" ) }) @@ -100,12 +103,14 @@ CREATE TABLE `ep_widget_catalog_parameter` ( @Index(name = "EP_WIDGET_CATALOG_WIDGET_PARAMETER_FK", columnList = "widget_id"), @Index(name = "EP_PARAMETER_ID_WIDGET_PARAMETER_FK", columnList = "param_id") }) -@NoArgsConstructor -@AllArgsConstructor + @Getter @Setter @Entity -public class EpWidgetCatalogParameter implements Serializable { +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class EpWidgetCatalogParameter extends DomainVo implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @@ -122,7 +127,7 @@ public class EpWidgetCatalogParameter implements Serializable { @NotNull @Valid private FnUser userId; - @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST) @JoinColumn(name = "param_id", nullable = false) @NotNull @Valid diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnApp.java b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnApp.java index 399cb55c..bada8e14 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnApp.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnApp.java @@ -171,9 +171,9 @@ public class FnApp extends DomainVo implements Serializable { @SafeHtml @NotNull private String appPassword; - @Column(name = "open", length = 1, columnDefinition = "char(1) default 'N'") + @Column(name = "_open", length = 1, columnDefinition = "char(1) default 'N'") private Boolean open; - @Column(name = "ENABLED", length = 1, columnDefinition = "char(1) default 'N'") + @Column(name = "_enabled", length = 1, columnDefinition = "char(1) default 'N'") private Boolean enabled; @Column(name = "active_yn", length = 1, columnDefinition = "char(1) default 'Y'") @Pattern(regexp = "[YNyn]") @@ -181,7 +181,7 @@ public class FnApp extends DomainVo implements Serializable { @NotNull @SafeHtml private String activeYn; - @Column(name = "thumbnail", columnDefinition = "mediumblob null default null") + @Column(name = "_thumbnail", columnDefinition = "mediumblob null default null") private byte[] thumbnail; @Column(name = "app_username", length = 50) @Size(max = 50) diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnLanguage.java b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnLanguage.java index 4b9186eb..ad976fc6 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnLanguage.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnLanguage.java @@ -42,6 +42,7 @@ package org.onap.portal.domain.db.fn; import com.fasterxml.jackson.annotation.JsonInclude; import java.io.Serializable; +import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; @@ -79,13 +80,11 @@ CREATE TABLE `fn_language` ( @Setter @Entity @JsonInclude() -@SequenceGenerator(name="seq", initialValue=1000, allocationSize=100000) public class FnLanguage implements Serializable { @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq") - @Column(name = "language_id", length = 11, nullable = false, columnDefinition = "int(11) AUTO_INCREMENT") - @Digits(integer = 11, fraction = 0) + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "language_id", length = 11, nullable = false) private Long languageId; @Column(name = "language_name", length = 100, nullable = false) @Size(max = 100) @@ -100,10 +99,10 @@ public class FnLanguage implements Serializable { @OneToMany( targetEntity = FnUser.class, mappedBy = "languageId", - cascade = CascadeType.ALL, - fetch = FetchType.LAZY + cascade = CascadeType.PERSIST, + fetch = FetchType.EAGER ) - private Set<FnUser> fnUsers; + private Set<FnUser> fnUsers = new HashSet<>(); @Override public String toString() { diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnQzSimpleTriggers.java b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnQzSimpleTriggers.java index 6f67381f..8bdb1e02 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnQzSimpleTriggers.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnQzSimpleTriggers.java @@ -76,7 +76,6 @@ CREATE TABLE `fn_qz_simple_triggers` ( @Table(name = "fn_qz_simple_triggers") @NoArgsConstructor @AllArgsConstructor - @Getter @Setter @Entity diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnRole.java b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnRole.java index 8465ce23..edd843ac 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnRole.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnRole.java @@ -53,10 +53,13 @@ import javax.persistence.Index; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; +import javax.persistence.NamedNativeQueries; +import javax.persistence.NamedNativeQuery; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; +import javax.persistence.UniqueConstraint; import javax.validation.constraints.Digits; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @@ -99,7 +102,7 @@ CREATE TABLE `fn_role` ( query = "FROM FnRole where role_id =:roleId and app_id is null"), @NamedQuery( name = "FnRole.retrieveAppRoleByAppRoleIdAndByAppId", - query = "FROM FnRole where app_role_id =:appRoleId and app_id =:appId"), + query = "FROM FnRole where appRoleId =:appRoleId and appId =:appId"), @NamedQuery( name = "FnRole.retrieveAppRoleByRoleIdAndAppId", query = "FROM FnRole where role_id =:roleId and app_id =:appId"), diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUser.java b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUser.java index ce28d0fd..c5a97195 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUser.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUser.java @@ -43,6 +43,7 @@ package org.onap.portal.domain.db.fn; import java.io.Serializable; import java.time.LocalDateTime; import java.util.Collection; +import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import javax.persistence.CascadeType; @@ -183,13 +184,11 @@ CREATE TABLE `fn_user` ( @NoArgsConstructor @AllArgsConstructor @DynamicUpdate -@SequenceGenerator(name = "seq", initialValue = 1000, allocationSize = 100000) public class FnUser extends DomainVo implements UserDetails, Serializable { @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq") - @Column(name = "user_id", length = 11, nullable = false) - @Digits(integer = 11, fraction = 0) + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "user_id", nullable = false) private Long userId; @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "org_id") @@ -343,7 +342,7 @@ public class FnUser extends DomainVo implements UserDetails, Serializable { @SafeHtml private String siloStatus; @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) - @JoinColumn(name = "language_id", nullable = false, columnDefinition = "int(11) DEFAULT 1") + @JoinColumn(name = "language_id", nullable = false, columnDefinition = "bigint DEFAULT 1") @NotNull(message = "languageId must not be null") private FnLanguage languageId; @Column(name = "is_guest", nullable = false, columnDefinition = "bit DEFAULT 0") diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUserRole.java b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUserRole.java index 390ef8b4..06320c4c 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUserRole.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUserRole.java @@ -43,6 +43,8 @@ package org.onap.portal.domain.db.fn; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; +import javax.persistence.ColumnResult; +import javax.persistence.ConstructorResult; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; @@ -53,15 +55,20 @@ import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedNativeQueries; import javax.persistence.NamedNativeQuery; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; import javax.persistence.OneToOne; +import javax.persistence.SqlResultSetMapping; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.Valid; import javax.validation.constraints.Digits; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.onap.portal.domain.dto.ecomp.UserRole; /* CREATE TABLE `fn_user_role` ( @@ -82,14 +89,63 @@ CREATE TABLE `fn_user_role` ( @NamedNativeQueries({ @NamedNativeQuery( name = "FnUserRole.retrieveUserRoleOnUserIdAndRoleIdAndAppId", - query = "select * from FnUserRole where user_id= :userId" + query = "FROM FnUserRole where user_id= :userId" + " and role_id= :roleId" + " and app_id= :appId"), @NamedNativeQuery( name = "FnUserRole.retrieveCachedAppRolesForUser", - query = "select * from FnUserRole where user_id= :userId" + query = "FROM FnUserRole where user_id= :userId" + " and user_id= :userId" - + " and app_id= :appId") + + " and app_id= :appId"), + @NamedNativeQuery( + name = "FnUserRole.isSuperAdmin", + query = "SELECT" + + " user.USER_ID as userId," + + " user.org_user_id as orgUserId," + + " userrole.ROLE_ID as roleId," + + " userrole.APP_ID as appId" + + " FROM" + + " fn_user_role userrole" + + " INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID" + + " WHERE" + + " user.org_user_id = :orgUserId" + + " AND userrole.ROLE_ID =:roleId" + + " AND userrole.APP_ID =:appId", + resultSetMapping = "UserRole", + resultClass = UserRole.class + ) +}) + +@SqlResultSetMapping( + name = "UserRole", + classes = { + @ConstructorResult( + targetClass = UserRole.class, + columns = { + @ColumnResult(name = "userId", type = Long.class), + @ColumnResult(name = "orgUserId", type = String.class), + @ColumnResult(name = "roleId", type = Long.class), + @ColumnResult(name = "appId", type = Long.class) + } + ) + } +) + +@NamedQueries({ + @NamedQuery( + name = "FnUserRole.getAdminUserRoles", + query = "FROM FnUserRole fn " + + "WHERE fn.userId.userId = :userId " + + "AND fn.roleId.roleId = :roleId " + + "AND fn.appId.appId = :appId"), + @NamedQuery( + name = "FnUserRole.getUserRolesForRoleIdAndAppId", + query = "FROM\n" + + " FnUserRole userrole\n" + + "WHERE\n" + + " userrole.roleId.roleId = :roleId\n" + + " AND userrole.appId.appId = :appId" + ) }) @Table( @@ -103,7 +159,7 @@ CREATE TABLE `fn_user_role` ( }) @NoArgsConstructor @AllArgsConstructor - +@Builder @Getter @Setter @Entity diff --git a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnWidget.java b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnWidget.java index 649267bf..f595536f 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnWidget.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnWidget.java @@ -42,21 +42,36 @@ package org.onap.portal.domain.db.fn; import javax.persistence.Column; import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; +import javax.persistence.NamedNativeQueries; +import javax.persistence.NamedNativeQuery; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; import javax.persistence.Table; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -@Table(name = "fn_widget") -@NoArgsConstructor -@AllArgsConstructor +@NamedQueries({ + @NamedQuery(name = "FnWidget.getForUrlNameAndAppId", + query = "FROM FnWidget where url =:URL and name =:NAME and appId =:APPID") +}) + @Getter @Setter @Entity +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "fn_widget") public class FnWidget { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) private Long widgetId; @Column(name = "WDG_NAME") private String name; diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/DomainVo.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/DomainVo.java index a965c62d..230da910 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/dto/DomainVo.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/dto/DomainVo.java @@ -76,7 +76,11 @@ public class DomainVo extends FusionVo implements Serializable, Cloneable, Compa protected Serializable auditUserId; protected Set auditTrail = null; private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DomainVo.class); - + + public DomainVo(Long id) { + this.id = id; + } + @Override public int compareTo(Object obj) { Long c1 = this.getId(); diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/EPUserAppCatalogRoles.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/EPUserAppCatalogRoles.java index c5fbd40d..aa57cb83 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/EPUserAppCatalogRoles.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/EPUserAppCatalogRoles.java @@ -57,10 +57,16 @@ import org.onap.portal.domain.dto.DomainVo; public class EPUserAppCatalogRoles extends DomainVo { private static final long serialVersionUID = -5259869298825093816L; - private Long requestedRoleId; - private String rolename; + private String roleName; private String requestStatus; private Long appId; + public EPUserAppCatalogRoles(Long reqId, Long requestedRoleId, String roleName, String requestStatus, Long appId) { + super(reqId); + this.requestedRoleId = requestedRoleId; + this.roleName = roleName; + this.requestStatus = requestStatus; + this.appId = appId; + } } diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/EPUserNotification.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/EPUserNotification.java index 864db8bc..88f2e4f0 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/EPUserNotification.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/EPUserNotification.java @@ -45,7 +45,8 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import org.onap.portal.domain.dto.DomainVo; +import org.onap.portalsdk.core.domain.support.DomainVo; + @Getter @Setter diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/UserRole.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/UserRole.java index 75b4b2d7..824ea0a1 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/UserRole.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/UserRole.java @@ -54,11 +54,18 @@ public class UserRole implements Serializable { private static final long serialVersionUID = 1L; - private Long user_Id; - private Long roleId; + private Long userId; private String orgUserId; + private Long roleId; + private Long appId; private String firstName; private String lastName; private String roleName; + public UserRole(Long userId, String orgUserId, Long roleId, Long appId) { + this.userId = userId; + this.orgUserId = orgUserId; + this.roleId = roleId; + this.appId = appId; + } } diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/UserRoles.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/UserRoles.java index 3b435e89..9b7e6a73 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/UserRoles.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/UserRoles.java @@ -66,7 +66,7 @@ public class UserRoles implements Serializable { setOrgUserId(user.getOrgUserId()); setFirstName(user.getFirstName()); setLastName(user.getLastName()); - setGuestSession(user.getUser_Id() == -1); + setGuestSession(user.getUserId() == -1); addRole(user.getRoleName()); } diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/EpNotificationItem.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/EpNotificationItem.java index a3f8af6e..59a577ae 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/EpNotificationItem.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/EpNotificationItem.java @@ -53,7 +53,8 @@ import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import org.hibernate.validator.constraints.SafeHtml; -import org.onap.portal.domain.dto.DomainVo; +import org.onap.portalsdk.core.domain.support.DomainVo; + @Getter @Setter diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/FieldsValidator.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/FieldsValidator.java index 1999d236..75f04dfd 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/FieldsValidator.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/FieldsValidator.java @@ -42,6 +42,7 @@ package org.onap.portal.domain.dto.transport; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import javax.servlet.http.HttpServletResponse; import lombok.AllArgsConstructor; import lombok.Getter; @@ -71,5 +72,22 @@ public class FieldsValidator { @AllArgsConstructor public class FieldName { public String name; + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof FieldName)) { + return false; + } + FieldName fieldName = (FieldName) o; + return Objects.equals(name, fieldName.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } } } diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/OnboardingWidget.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/OnboardingWidget.java index de13bec5..ccc9a785 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/OnboardingWidget.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/OnboardingWidget.java @@ -41,27 +41,39 @@ package org.onap.portal.domain.dto.transport; import java.io.Serializable; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Positive; +import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.SafeHtml; @Getter @Setter +@Builder @NoArgsConstructor public class OnboardingWidget implements Serializable { private static final long serialVersionUID = 1L; private Long id; - @SafeHtml + @SafeHtml(message = "name may have unsafe html content") private String name; + @NotNull(message = "appId can't be null") + @Min(message = "appId value must be higher than 1",value = 2) private Long appId; - @SafeHtml + @SafeHtml(message = "appName may have unsafe html content") + @NotBlank(message = "appName can't be blank") private String appName; + @Positive(message = "width must be positive number") private Integer width; + @Positive(message = "height must be positive number") private Integer height; - @SafeHtml + @SafeHtml(message = "url may have unsafe html content") + @NotBlank(message = "url can't be blank") private String url; public OnboardingWidget(Long id, String name, Long appId, diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/WidgetCatalogPersonalization.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/WidgetCatalogPersonalization.java index b9e54bfc..d9053f03 100644 --- a/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/WidgetCatalogPersonalization.java +++ b/portal-BE/src/main/java/org/onap/portal/domain/dto/transport/WidgetCatalogPersonalization.java @@ -40,6 +40,7 @@ package org.onap.portal.domain.dto.transport; +import javax.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @@ -51,7 +52,9 @@ import lombok.Setter; @AllArgsConstructor public class WidgetCatalogPersonalization { + @NotNull private Long widgetId; + @NotNull private Boolean select; } diff --git a/portal-BE/src/main/java/org/onap/portal/exception/NotValidDataException.java b/portal-BE/src/main/java/org/onap/portal/exception/NotValidDataException.java new file mode 100644 index 00000000..7a8aadef --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/exception/NotValidDataException.java @@ -0,0 +1,48 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.exception; + +public class NotValidDataException extends Exception { + + public NotValidDataException(String exceptionMsg) { + super(exceptionMsg); + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/exception/RoleFunctionException.java b/portal-BE/src/main/java/org/onap/portal/exception/RoleFunctionException.java index 75ecfa39..8ae396cf 100644 --- a/portal-BE/src/main/java/org/onap/portal/exception/RoleFunctionException.java +++ b/portal-BE/src/main/java/org/onap/portal/exception/RoleFunctionException.java @@ -1,8 +1,10 @@ -/*- +/* * ============LICENSE_START========================================== * ONAP Portal * =================================================================== - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung * =================================================================== * * Unless otherwise specified, all software contained herein is licensed @@ -33,7 +35,7 @@ * * ============LICENSE_END============================================ * - * + * */ package org.onap.portal.exception; diff --git a/portal-BE/src/main/java/org/onap/portal/service/AdminRolesService.java b/portal-BE/src/main/java/org/onap/portal/service/AdminRolesService.java index c948ece4..c2d88bc1 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/AdminRolesService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/AdminRolesService.java @@ -47,15 +47,17 @@ import javax.persistence.EntityManager; import org.onap.portal.domain.db.fn.FnRole; import org.onap.portal.domain.db.fn.FnUser; import org.onap.portal.domain.db.fn.FnUserRole; -import org.onap.portal.domain.dto.ecomp.UserRole; import org.onap.portal.logging.format.EPAppMessagesEnum; import org.onap.portal.logging.logic.EPLogUtil; +import org.onap.portal.service.fn.FnUserRoleService; import org.onap.portal.service.fn.FnUserService; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; @Service +@Transactional public class AdminRolesService { private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminRolesService.class); @@ -63,36 +65,31 @@ public class AdminRolesService { private final Long SYS_ADMIN_ROLE_ID = 1L; private final Long ACCOUNT_ADMIN_ROLE_ID = 999L; private final Long ECOMP_APP_ID = 1L; - private final String ADMIN_ACCOUNT= "Is account admin for user {}"; + private final String ADMIN_ACCOUNT = "Is account admin for user {}"; private final EntityManager entityManager; private final FnUserService fnUserService; + private final FnUserRoleService fnUserRoleService; @Autowired public AdminRolesService(final EntityManager entityManager, - FnUserService fnUserService) { + final FnUserService fnUserService, final FnUserRoleService fnUserRoleService) { this.entityManager = entityManager; this.fnUserService = fnUserService; + this.fnUserRoleService = fnUserRoleService; } - public boolean isSuperAdmin(FnUser user) { - if ((user != 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 userRoleList = entityManager.createNativeQuery(sql, UserRole.class).getResultList(); - if (userRoleList != null && userRoleList.size() > 0) { - return true; - } - } catch (Exception e) { - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); - logger.error(EELFLoggerDelegate.errorLogger, - "Exception occurred while executing isSuperAdmin operation", e); - } + public boolean isSuperAdmin(final String orgUserId) { + boolean isSuperAdmin; + try { + isSuperAdmin = fnUserRoleService + .isSuperAdmin(orgUserId, SYS_ADMIN_ROLE_ID, ECOMP_APP_ID); + } catch (Exception e) { + logger.error("isSuperAdmin exception: " + e.toString()); + throw e; } - return false; + logger.info("isSuperAdmin " + isSuperAdmin); + return isSuperAdmin; } public boolean isAccountAdmin(FnUser user) { @@ -101,22 +98,28 @@ public class AdminRolesService { userParams.put("userId", user.getId()); logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, user.getId()); List<Integer> userAdminApps; - String query = "select fa.app_id from fn_user_role ur,fn_app fa where ur.user_id =:userId and ur.app_id=fa.app_id and ur.role_id= 999 and (fa.enabled = 'Y' || fa.app_id=1)"; - userAdminApps = entityManager.createQuery(query, Integer.class).setParameter("userId", user.getId()).getResultList(); - logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}", user.getOrgUserId(), userAdminApps.size()); - + String query = "select fa.app_id from fn_user_role ur,fn_app fa where ur.user_id =:userId and ur.app_id=fa.app_id and ur.role_id= 999 and (fa.enabled = 'Y' || fa.app_id=1)"; + userAdminApps = entityManager.createQuery(query, Integer.class) + .setParameter("userId", user.getId()).getResultList(); + logger.debug(EELFLoggerDelegate.debugLogger, + "Is account admin for userAdminApps() - for user {}, found userAdminAppsSize {}", + user.getOrgUserId(), userAdminApps.size()); if (user.getId() != null) { for (FnUserRole userApp : user.getFnUserRoles()) { - if (userApp.getRoleId().getId().equals(ACCOUNT_ADMIN_ROLE_ID)||(userAdminApps.size()>1)) { - logger.debug(EELFLoggerDelegate.debugLogger, "Is account admin for userAdminApps() - for user {}, found Id {}", user.getOrgUserId(), userApp.getRoleId().getId()); + if (userApp.getRoleId().getId().equals(ACCOUNT_ADMIN_ROLE_ID) || ( + userAdminApps.size() > 1)) { + logger.debug(EELFLoggerDelegate.debugLogger, + "Is account admin for userAdminApps() - for user {}, found Id {}", + user.getOrgUserId(), userApp.getRoleId().getId()); return true; } } } } catch (Exception e) { EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); - logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isAccountAdmin operation", + logger.error(EELFLoggerDelegate.errorLogger, + "Exception occurred while executing isAccountAdmin operation", e); } return false; @@ -129,7 +132,8 @@ public class AdminRolesService { for (FnUserRole userApp : currentUser.getFnUserRoles()) { if (!userApp.getAppId().getId().equals(ECOMP_APP_ID)) { FnRole role = userApp.getRoleId(); - if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) { + if (!role.getId().equals(SYS_ADMIN_ROLE_ID) && !role.getId() + .equals(ACCOUNT_ADMIN_ROLE_ID)) { if (role.getActiveYn()) { return true; } @@ -139,7 +143,8 @@ public class AdminRolesService { } } catch (Exception e) { EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); - logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation", e); + logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while executing isUser operation", + e); } return false; } diff --git a/portal-BE/src/main/java/org/onap/portal/service/PersUserWidgetService.java b/portal-BE/src/main/java/org/onap/portal/service/PersUserWidgetService.java index 364085c4..38a0a408 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/PersUserWidgetService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/PersUserWidgetService.java @@ -46,14 +46,22 @@ import java.util.stream.Collectors; import org.onap.portal.dao.ep.EpPersUserWidgetSelDao; import org.onap.portal.dao.fn.EpWidgetCatalogDao; import org.onap.portal.domain.db.ep.EpPersUserWidgetSel; +import org.onap.portal.domain.db.ep.EpWidgetCatalog; import org.onap.portal.domain.db.fn.FnUser; import org.onap.portal.domain.dto.ecomp.PersUserWidgetSelection; +import org.onap.portal.domain.dto.transport.WidgetCatalogPersonalization; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; @Service +@Transactional public class PersUserWidgetService { + private static final Logger LOGGER = LoggerFactory.getLogger(PersUserWidgetService.class); private final EpPersUserWidgetSelDao epPersUserWidgetSelDao; private final EpWidgetCatalogDao epWidgetCatalogDao; @@ -64,44 +72,36 @@ public class PersUserWidgetService { this.epWidgetCatalogDao = epWidgetCatalogDao; } - public void setPersUserAppValue(FnUser user, Long widgetId, Boolean select) { - if (user == null || widgetId == null) { - throw new IllegalArgumentException("setPersUserAppValue: Null values"); - } - - List<PersUserWidgetSelection> persList = getUserWidgetSelction(user, widgetId); + public void setPersUserAppValue(FnUser user, WidgetCatalogPersonalization personalization) { + List<PersUserWidgetSelection> persList = getUserWidgetSelction(user, personalization.getWidgetId()); + LOGGER.info("Error: " + persList.size()); // Key constraint limits to 1 row - PersUserWidgetSelection persRow = null; + PersUserWidgetSelection persRow; if (persList.size() == 1) { persRow = persList.get(0); } else { - persRow = new PersUserWidgetSelection(null, user.getId(), widgetId, null); + persRow = new PersUserWidgetSelection(null, user.getUserId(), personalization.getWidgetId(), null); } - if (select) { - if (persRow.getId() != null) { - epPersUserWidgetSelDao.deleteById(persRow.getId()); - } - persRow.setStatusCode("S"); // show - EpPersUserWidgetSel epPersUserWidgetSel = new EpPersUserWidgetSel(); - epPersUserWidgetSel.setUserId(user); - epPersUserWidgetSel.setWidgetId(epWidgetCatalogDao.findById(widgetId).get()); - epPersUserWidgetSelDao.saveAndFlush(epPersUserWidgetSel); - } else { - if (persRow.getId() != null) { - epPersUserWidgetSelDao.deleteById(persRow.getId()); - } - persRow.setStatusCode("H"); // Hide - EpPersUserWidgetSel epPersUserWidgetSel = new EpPersUserWidgetSel(); - epPersUserWidgetSel.setUserId(user); - epPersUserWidgetSel.setWidgetId(epWidgetCatalogDao.findById(widgetId).get()); - epPersUserWidgetSelDao.saveAndFlush(epPersUserWidgetSel); + + if (persRow.getId() != null) { + epPersUserWidgetSelDao.deleteById(persRow.getId()); } + + persRow.setStatusCode(personalization.getSelect() ? "S" : "H"); // Show / Hide + EpPersUserWidgetSel epPersUserWidgetSel = new EpPersUserWidgetSel(); + epPersUserWidgetSel.setUserId(user); + epPersUserWidgetSel.setWidgetId( + epWidgetCatalogDao.findById(personalization.getWidgetId()).orElse(new EpWidgetCatalog())); + epPersUserWidgetSelDao.saveAndFlush(epPersUserWidgetSel); } private List<PersUserWidgetSelection> getUserWidgetSelction(FnUser user, Long widgetId) { - return epPersUserWidgetSelDao.getEpPersUserWidgetSelForUserIdAndWidgetId(user.getId(), widgetId) - .orElse(new ArrayList<>()).stream().map( - this::epPersUserWidgetSelToPersUserWidgetSelection).collect(Collectors.toList()); + return epPersUserWidgetSelDao + .getEpPersUserWidgetSelForUserIdAndWidgetId(user.getId(), widgetId) + .orElse(new ArrayList<>()) + .stream() + .map(this::epPersUserWidgetSelToPersUserWidgetSelection) + .collect(Collectors.toList()); } private PersUserWidgetSelection epPersUserWidgetSelToPersUserWidgetSelection(EpPersUserWidgetSel widgetSel) { diff --git a/portal-BE/src/main/java/org/onap/portal/service/WidgetService.java b/portal-BE/src/main/java/org/onap/portal/service/WidgetService.java index 794f9336..4b037919 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/WidgetService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/WidgetService.java @@ -46,29 +46,33 @@ import javax.persistence.EntityManager; import javax.servlet.http.HttpServletResponse; import org.onap.portal.dao.fn.FnWidgetDao; import org.onap.portal.domain.db.fn.FnUser; +import org.onap.portal.domain.db.fn.FnUserRole; import org.onap.portal.domain.db.fn.FnWidget; import org.onap.portal.domain.dto.ecomp.EPUserApp; -import org.onap.portal.domain.dto.ecomp.Widget; import org.onap.portal.domain.dto.transport.FieldsValidator; import org.onap.portal.domain.dto.transport.OnboardingWidget; +import org.onap.portal.service.fn.FnUserRoleService; import org.onap.portal.utils.EPCommonSystemProperties; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service +@EnableAspectJAutoProxy +@Transactional public class WidgetService { private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(WidgetService.class); - private final Long LONG_ECOMP_APP_ID = 1L; private final Long ACCOUNT_ADMIN_ROLE_ID = 999L; private static String baseSqlToken = " new org.onap.portal.domain.dto.transport.OnboardingWidget(" + "widget.WIDGET_ID,widget.WDG_NAME,widget.APP_ID," + "app.APP_NAME,widget.WDG_WIDTH,widget.WDG_HEIGHT," - + "widget.WDG_URL) 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"; + + "widget.WDG_URL, 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 static final String urlField = "url"; private static final Long DUBLICATED_FIELD_VALUE_ECOMP_ERROR = new Long( @@ -78,19 +82,21 @@ public class WidgetService { private final AdminRolesService adminRolesService; private final EntityManager entityManager; private final FnWidgetDao fnWidgetDao; + private final FnUserRoleService fnUserRoleService; @Autowired public WidgetService(final AdminRolesService adminRolesService, final EntityManager entityManager, - final FnWidgetDao fnWidgetDao) { + final FnWidgetDao fnWidgetDao, FnUserRoleService fnUserRoleService) { this.adminRolesService = adminRolesService; this.entityManager = entityManager; this.fnWidgetDao = fnWidgetDao; + this.fnUserRoleService = fnUserRoleService; } private static final Object syncRests = new Object(); public List<OnboardingWidget> getOnboardingWidgets(FnUser user, boolean managed) { - if (adminRolesService.isSuperAdmin(user)) { + if (adminRolesService.isSuperAdmin(user.getOrgUserId())) { return entityManager.createQuery(sqlWidgetsForAllApps(), OnboardingWidget.class).getResultList(); } else if (managed) { if (adminRolesService.isAccountAdmin(user)) { @@ -122,16 +128,9 @@ public class WidgetService { + ":USERID"; } - public FieldsValidator setOnboardingWidget(FnUser user, OnboardingWidget onboardingWidget) { - if (onboardingWidget.getAppName().isEmpty() || onboardingWidget.getUrl().isEmpty() - || onboardingWidget.getAppId() == null - || onboardingWidget.getAppId().equals(LONG_ECOMP_APP_ID) || onboardingWidget.getWidth() <= 0 || - onboardingWidget.getHeight() <= 0) { - FieldsValidator fieldsValidator = new FieldsValidator(); - fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_BAD_REQUEST); - return fieldsValidator; - } - return this.updateOrSaveWidget(adminRolesService.isSuperAdmin(user), user.getId(), onboardingWidget); + @PreAuthorize("hasRole('System_Administrator')") + public FieldsValidator setOnboardingWidget(final Long userId, final OnboardingWidget onboardingWidget) { + return this.updateOrSaveWidget(true, userId, onboardingWidget); } private FieldsValidator updateOrSaveWidget(boolean superAdmin, Long userId, OnboardingWidget onboardingWidget) { @@ -160,25 +159,16 @@ public class WidgetService { private boolean isUserAdminOfAppForWidget(boolean superAdmin, Long userId, Long appId) { if (!superAdmin) { - List<EPUserApp> userRoles = getAdminUserRoles(userId, appId); + List<FnUserRole> userRoles = getAdminUserRoles(userId, appId); return (userRoles.size() > 0); } return true; } - private List<EPUserApp> getAdminUserRoles(Long userId, Long appId) { - return entityManager.createQuery( - "SELECT new org.onap.portal.domain.dto.ecomp.EPUserApp(fn.userId, fn.roleId, fn.appId) FROM FnUserRole fn" - + "WHERE fn.userId = :USERID " - + "AND fn.roleId = :ROLEID " - + "AND fn.appId = :APPID", EPUserApp.class) - .setParameter("USERID", userId) - .setParameter("ROLEID", ACCOUNT_ADMIN_ROLE_ID) - .setParameter("APPID", appId) - .getResultList(); + private List<FnUserRole> getAdminUserRoles(Long userId, Long appId) { + return fnUserRoleService.getAdminUserRoles(userId, ACCOUNT_ADMIN_ROLE_ID, appId); } - @Transactional private void applyOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) { boolean result; FnWidget widget; @@ -199,11 +189,11 @@ public class WidgetService { } private void validateOnboardingWidget(OnboardingWidget onboardingWidget, FieldsValidator fieldsValidator) { - List<Widget> widgets = getWidgets(onboardingWidget); + List<FnWidget> widgets = getWidgets(onboardingWidget); boolean dublicatedUrl = false; boolean dublicatedName = false; - for (Widget widget : widgets) { - if (onboardingWidget.getId() != null && onboardingWidget.getId().equals(widget.getId())) { + for (FnWidget widget : widgets) { + if (onboardingWidget.getId() != null && onboardingWidget.getId().equals(widget.getWidgetId())) { // widget should not be compared with itself continue; } @@ -233,24 +223,16 @@ public class WidgetService { } } - private List<Widget> getWidgets(OnboardingWidget onboardingWidget) { - return entityManager.createQuery( - "SELECT new org.onap.portal.domain.dto.ecomp.Widget(fn.APP_ID, fn.WDG_NAME, fn.WDG_URL) FROM FnWidget fn" - + "WHERE fn.WDG_URL = :WDGURL " - + "AND fn.WDG_NAME = :WDGNAME " - + "AND fn.APP_ID = :APPID", Widget.class) - .setParameter("WDGURL", onboardingWidget.getUrl()) - .setParameter("WDGNAME", onboardingWidget.getName()) - .getResultList(); + private List<FnWidget> getWidgets(final OnboardingWidget onboardingWidget) { + return fnWidgetDao.getForUrlNameAndAppId(onboardingWidget.getUrl(), onboardingWidget.getName(), onboardingWidget.getAppId()).orElse(new ArrayList<>()); } - @Transactional public FieldsValidator deleteOnboardingWidget(FnUser user, Long onboardingWidgetId) { FieldsValidator fieldsValidator = new FieldsValidator(); synchronized (syncRests) { FnWidget widget = fnWidgetDao.getOne(onboardingWidgetId); if (widget != null && widget.getAppId() != null) { // widget exists - if (!this.isUserAdminOfAppForWidget(adminRolesService.isSuperAdmin(user), user.getId(), + if (!this.isUserAdminOfAppForWidget(adminRolesService.isSuperAdmin(user.getOrgUserId()), user.getUserId(), widget.getAppId())) { fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_FORBIDDEN); } else { @@ -262,4 +244,8 @@ public class WidgetService { } return fieldsValidator; } + + public FnWidget saveOne(final FnWidget widget){ + return fnWidgetDao.saveAndFlush(widget); + } } diff --git a/portal-BE/src/main/java/org/onap/portal/service/ep/EpMicroserviceParameterService.java b/portal-BE/src/main/java/org/onap/portal/service/ep/EpMicroserviceParameterService.java index 2544ae6a..6fa8b7d7 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/ep/EpMicroserviceParameterService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/ep/EpMicroserviceParameterService.java @@ -51,8 +51,10 @@ import org.onap.portal.domain.dto.ecomp.MicroserviceParameter; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; @Service +@Transactional public class EpMicroserviceParameterService { EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EpWidgetCatalogParameterService.class); @@ -84,4 +86,19 @@ public class EpMicroserviceParameterService { private List<MicroserviceParameter> mapToMicroserviceParameterList(final List<EpMicroserviceParameter> list){ return list.stream().map(this::epWidgetCatalogParameterToMicroserviceParameter).collect(Collectors.toList()); } + + public EpMicroserviceParameter save(EpMicroserviceParameter epMicroserviceParameter){ + return epMicroserviceParameterDao.save(epMicroserviceParameter); + } + + @Transactional + public boolean deleteMicroserviceParameterById(final Long paramid){ + try { + epMicroserviceParameterDao.deleteById(paramid); + return true; + }catch (Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + return false; + } + } } diff --git a/portal-BE/src/main/java/org/onap/portal/service/ep/EpWidgetCatalogParameterService.java b/portal-BE/src/main/java/org/onap/portal/service/ep/EpWidgetCatalogParameterService.java index 8488e5ad..d43acc04 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/ep/EpWidgetCatalogParameterService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/ep/EpWidgetCatalogParameterService.java @@ -42,54 +42,60 @@ package org.onap.portal.service.ep; import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; -import org.onap.portal.dao.ep.EpMicroserviceParameterDao; import org.onap.portal.dao.ep.EpWidgetCatalogParameterDao; -import org.onap.portal.dao.fn.EpWidgetCatalogDao; -import org.onap.portal.dao.fn.FnUserDao; import org.onap.portal.domain.db.ep.EpWidgetCatalogParameter; -import org.onap.portal.domain.dto.ecomp.WidgetCatalogParameter; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; @Service +@Transactional public class EpWidgetCatalogParameterService { EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EpWidgetCatalogParameterService.class); private final EpWidgetCatalogParameterDao epWidgetCatalogParameterDao; - private final EpMicroserviceParameterDao epMicroserviceParameterDao; - private final EpWidgetCatalogDao epWidgetCatalogDao; - private final FnUserDao fnUserDao; + private final EpMicroserviceParameterService epMicroserviceParameterService; @Autowired public EpWidgetCatalogParameterService( final EpWidgetCatalogParameterDao epWidgetCatalogParameterDao, - final EpMicroserviceParameterDao epMicroserviceParameterDao, - EpWidgetCatalogDao epWidgetCatalogDao, FnUserDao fnUserDao) { + final EpMicroserviceParameterService epMicroserviceParameterService) { this.epWidgetCatalogParameterDao = epWidgetCatalogParameterDao; - this.epMicroserviceParameterDao = epMicroserviceParameterDao; - this.epWidgetCatalogDao = epWidgetCatalogDao; - this.fnUserDao = fnUserDao; + this.epMicroserviceParameterService = epMicroserviceParameterService; } - public List<WidgetCatalogParameter> getUserParameterById(Long paramId) { - return mapEpWidgetListToWidgetList( - epWidgetCatalogParameterDao.retrieveByParamId(paramId).orElse(new ArrayList<>())); + public List<EpWidgetCatalogParameter> getUserParameterById(final Long paramId) { + return epWidgetCatalogParameterDao.retrieveByParamId(paramId).orElse(new ArrayList<>()); } - public void deleteUserParameterById(Long paramId) { - epWidgetCatalogParameterDao.deleteWidgetCatalogParameter(paramId); - epMicroserviceParameterDao.deleteMicroserviceParameterById(paramId); + public boolean deleteUserParameterById(final Long paramId) { + return (deleteByParamId(paramId) && + epMicroserviceParameterService.deleteMicroserviceParameterById(paramId)); } - public WidgetCatalogParameter getUserParamById(Long widgetId, Long userId, Long paramId) { - WidgetCatalogParameter widgetParam = null; - List<WidgetCatalogParameter> list = mapEpWidgetListToWidgetList( - epWidgetCatalogParameterDao.getUserParamById(widgetId, userId, paramId) - .orElse(new ArrayList<>())); - if (list.size() != 0) { + public EpWidgetCatalogParameter getById(final Long id){ + return epWidgetCatalogParameterDao.getOne(id); + } + + @Transactional + public boolean deleteByParamId(final Long paramId) { + try { + epWidgetCatalogParameterDao.deleteWidgetCatalogParameter(paramId); + return true; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, e.getMessage()); + return false; + } + } + + public EpWidgetCatalogParameter getUserParamById(final Long widgetId, final Long userId, final Long paramId) { + EpWidgetCatalogParameter widgetParam = null; + List<EpWidgetCatalogParameter> list = epWidgetCatalogParameterDao + .getUserParamById(widgetId, userId, paramId) + .orElse(null); + if (list != null && !list.isEmpty()) { widgetParam = list.get(0); } logger.debug(EELFLoggerDelegate.debugLogger, @@ -97,31 +103,7 @@ public class EpWidgetCatalogParameterService { return widgetParam; } - public void saveUserParameter(WidgetCatalogParameter newParameter) { - epWidgetCatalogParameterDao.saveAndFlush(mapToEpWidgetCatalogParameter(newParameter)); - } - - private EpWidgetCatalogParameter mapToEpWidgetCatalogParameter(WidgetCatalogParameter wcp){ - - return new EpWidgetCatalogParameter(wcp.getId(), epWidgetCatalogDao.findById(wcp.getWidgetId()).get(), - fnUserDao.findById(wcp.getUserId()).get(), - epMicroserviceParameterDao.findById(wcp.getParamId()).get(), - wcp.getUserValue()); - } - - private List<EpWidgetCatalogParameter> mapToList(List<WidgetCatalogParameter> list){ - return list.stream().map(this::mapToEpWidgetCatalogParameter).collect(Collectors.toList()); - } - - private WidgetCatalogParameter mapEpWidgetCatalogParametertoWidgetCatalogParameter( - EpWidgetCatalogParameter ewcp) { - return new WidgetCatalogParameter(ewcp.getId(), ewcp.getWidgetId().getWidgetId(), - ewcp.getUserId().getId(), ewcp.getParamId().getId(), ewcp.getUserValue()); - } - - private List<WidgetCatalogParameter> mapEpWidgetListToWidgetList( - List<EpWidgetCatalogParameter> epWidgetCatalogParameters) { - return epWidgetCatalogParameters.stream().map(this::mapEpWidgetCatalogParametertoWidgetCatalogParameter) - .collect(Collectors.toList()); + public void saveUserParameter(final EpWidgetCatalogParameter newParameter) { + epWidgetCatalogParameterDao.save(newParameter); } } diff --git a/portal-BE/src/main/java/org/onap/portal/service/ep/EpWidgetCatalogService.java b/portal-BE/src/main/java/org/onap/portal/service/ep/EpWidgetCatalogService.java new file mode 100644 index 00000000..f0c273ad --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/ep/EpWidgetCatalogService.java @@ -0,0 +1,21 @@ +package org.onap.portal.service.ep; + +import org.onap.portal.dao.fn.EpWidgetCatalogDao; +import org.onap.portal.domain.db.ep.EpWidgetCatalog; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class EpWidgetCatalogService { + + private final EpWidgetCatalogDao epWidgetCatalogDao; + + @Autowired + public EpWidgetCatalogService(EpWidgetCatalogDao epWidgetCatalogDao) { + this.epWidgetCatalogDao = epWidgetCatalogDao; + } + + public EpWidgetCatalog save(final EpWidgetCatalog epWidgetCatalog){ + return epWidgetCatalogDao.save(epWidgetCatalog); + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/fn/FnAppService.java b/portal-BE/src/main/java/org/onap/portal/service/fn/FnAppService.java index 75b32dd3..d8d88c97 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/fn/FnAppService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/fn/FnAppService.java @@ -41,6 +41,8 @@ package org.onap.portal.service.fn; import java.util.List; +import java.util.Optional; +import javax.persistence.EntityExistsException; import org.onap.portal.dao.fn.FnAppDao; import org.onap.portal.domain.db.fn.FnApp; import org.onap.portal.domain.dto.transport.OnboardingApp; @@ -67,6 +69,10 @@ public class FnAppService { return fnAppDao.findAll(); } + public FnApp getById(final Long id){ + return Optional.of(fnAppDao.getOne(id)).orElseThrow(EntityExistsException::new); + } + public void createOnboardingFromApp(FnApp app, OnboardingApp onboardingApp) { onboardingApp.setId(app.getId()); onboardingApp.setName(app.getAppName()); diff --git a/portal-BE/src/main/java/org/onap/portal/service/fn/FnRoleService.java b/portal-BE/src/main/java/org/onap/portal/service/fn/FnRoleService.java new file mode 100644 index 00000000..45867b42 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/fn/FnRoleService.java @@ -0,0 +1,87 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.service.fn; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import javax.persistence.EntityExistsException; +import org.onap.portal.dao.fn.FnRoleDao; +import org.onap.portal.domain.db.fn.FnRole; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +public class FnRoleService { + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnRoleService.class); + + + private final FnRoleDao fnRoleDao; + + @Autowired + public FnRoleService(FnRoleDao fnRoleDao) { + this.fnRoleDao = fnRoleDao; + } + + public FnRole getById(final Long id) { + return fnRoleDao.findById(id).orElseThrow(EntityExistsException::new); + } + + public FnRole getRole(final Long appId, final Long appRoleId) { + + String sql = "SELECT * FROM fn_role where APP_ID = :appId AND APP_ROLE_ID = :appRoleId"; + + List<FnRole> roles = Optional.of(fnRoleDao.retrieveAppRoleByAppRoleIdAndByAppId(appId, appRoleId)).orElse(new ArrayList<>()); + if (!roles.isEmpty()) { + 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, roles.size())); + 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); + } + return null; + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/fn/FnUserRoleService.java b/portal-BE/src/main/java/org/onap/portal/service/fn/FnUserRoleService.java new file mode 100644 index 00000000..9f136df3 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/service/fn/FnUserRoleService.java @@ -0,0 +1,82 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * Modifications Copyright (c) 2019 Samsung + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ + +package org.onap.portal.service.fn; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import org.onap.portal.dao.fn.FnUserRoleDao; +import org.onap.portal.domain.db.fn.FnUserRole; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +public class FnUserRoleService { + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnUserRoleService.class); + private final FnUserRoleDao fnUserRoleDao; + + @Autowired + public FnUserRoleService(FnUserRoleDao fnUserRoleDao) { + this.fnUserRoleDao = fnUserRoleDao; + } + + public List<FnUserRole> getAdminUserRoles(final Long userId, final Long roleId, final Long appId) { + return fnUserRoleDao.getAdminUserRoles(userId, roleId, appId).orElse(new ArrayList<>()); + } + + public boolean isSuperAdmin(final String orgUserId, final Long roleId, final Long appId){ + List<FnUserRole> roles = getUserRolesForRoleIdAndAppId(roleId, appId).stream().filter(role -> role.getUserId().getOrgUserId().equals(orgUserId)).collect(Collectors.toList()); + return !roles.isEmpty(); + } + + private List<FnUserRole> getUserRolesForRoleIdAndAppId(final Long roleId, final Long appId){ + return Optional.of(fnUserRoleDao.getUserRolesForRoleIdAndAppId(roleId, appId)).orElse(new ArrayList<>()); + } + + public FnUserRole saveOne(final FnUserRole fnUserRole){ + return fnUserRoleDao.save(fnUserRole); + } +} diff --git a/portal-BE/src/main/java/org/onap/portal/service/fn/FnUserService.java b/portal-BE/src/main/java/org/onap/portal/service/fn/FnUserService.java index 855e827d..5c1c84b5 100644 --- a/portal-BE/src/main/java/org/onap/portal/service/fn/FnUserService.java +++ b/portal-BE/src/main/java/org/onap/portal/service/fn/FnUserService.java @@ -40,12 +40,18 @@ package org.onap.portal.service.fn; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import java.security.Principal; import java.util.ArrayList; import java.util.List; import java.util.Optional; +import org.onap.portal.controller.UserRolesController; import org.onap.portal.dao.fn.FnUserDao; import org.onap.portal.domain.db.fn.FnUser; +import org.onap.portal.domain.dto.transport.UserWithNameSurnameTitle; +import org.onap.portal.utils.EcompPortalUtils; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.security.core.userdetails.UserDetailsService; @@ -58,6 +64,8 @@ import org.springframework.transaction.annotation.Transactional; @Transactional public class FnUserService implements UserDetailsService { + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnUserService.class); + private FnUserDao fnUserDao; @Autowired @@ -83,24 +91,28 @@ public class FnUserService implements UserDetailsService { return Optional.of(fnUserDao.getOne(id)); } - List<FnUser> getUserWithOrgUserId(final String orgUserIdValue){ + List<FnUser> getUserWithOrgUserId(final String orgUserIdValue) { return fnUserDao.getUserWithOrgUserId(orgUserIdValue).orElse(new ArrayList<>()); } - List<FnUser> getUsersByOrgIds(final List<String> orgIds){ + List<FnUser> getUsersByOrgIds(final List<String> orgIds) { return fnUserDao.getUsersByOrgIds(orgIds).orElse(new ArrayList<>()); } - List<FnUser> getActiveUsers(){ + List<FnUser> getActiveUsers() { return fnUserDao.getActiveUsers().orElse(new ArrayList<>()); } - public void deleteUser(final FnUser fnUser){ + public void deleteUser(final FnUser fnUser) { fnUserDao.delete(fnUser); } public boolean existById(final Long userId) { return fnUserDao.existsById(userId); } -} + + public List<FnUser> findAll() { + return fnUserDao.findAll(); + } + }
\ No newline at end of file diff --git a/portal-BE/src/main/java/org/onap/portal/utils/SystemType.java b/portal-BE/src/main/java/org/onap/portal/utils/SystemType.java new file mode 100644 index 00000000..fe7ff8f2 --- /dev/null +++ b/portal-BE/src/main/java/org/onap/portal/utils/SystemType.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * + */ +package org.onap.portal.utils; + +public enum SystemType { + + APPLICATION, +// SYSTEM +} |