diff options
Diffstat (limited to 'ecomp-portal-BE-common')
11 files changed, 300 insertions, 439 deletions
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/config/NotificationCleanupConfig.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/config/NotificationCleanupConfig.java index f18dea93..c32650e2 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/config/NotificationCleanupConfig.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/config/NotificationCleanupConfig.java @@ -40,6 +40,7 @@ */ package org.onap.portalapp.config; +import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; @@ -51,23 +52,25 @@ import java.util.TimerTask; @Configuration public class NotificationCleanupConfig implements ApplicationContextAware { - + // Once every 10 minutes should be adequate - public static final int CLEANUP_PERIOD_MINUTES = 10; - + private static final int CLEANUP_PERIOD_MINUTES = 10; + private static ApplicationContext applicationContext; - public void setApplicationContext(ApplicationContext context) { - applicationContext = context; + + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + NotificationCleanupConfig.applicationContext = applicationContext; } - public static ApplicationContext getApplicationContext() { + static ApplicationContext getApplicationContext() { return applicationContext; } @PostConstruct - public void StartSchedular() { + public void startSchedular() { TimerTask task = new NotificationCleanup(); Timer timer = new Timer(); timer.schedule(task, 1000, (long) CLEANUP_PERIOD_MINUTES * 60 * 1000); @@ -77,5 +80,4 @@ public class NotificationCleanupConfig implements ApplicationContextAware { public NotificationCleanupConfig getConfig() { return new NotificationCleanupConfig(); } - }
\ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java index 0ae5aa82..d5438f41 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequest.java @@ -37,17 +37,12 @@ */ package org.onap.portalapp.portal.controller; +import io.swagger.annotations.ApiOperation; import java.util.List; - -import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - -import javax.validation.ConstraintViolation; import javax.validation.Valid; -import javax.validation.Validation; -import javax.validation.Validator; -import javax.validation.ValidatorFactory; +import lombok.NoArgsConstructor; import org.onap.portalapp.portal.domain.EPApp; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; @@ -62,6 +57,7 @@ import org.onap.portalapp.portal.transport.OnboardingApp; import org.onap.portalapp.portal.utils.EPCommonSystemProperties; import org.onap.portalapp.portal.utils.EcompPortalUtils; import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalapp.validation.DataValidator; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; @@ -73,8 +69,6 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; -import io.swagger.annotations.ApiOperation; - /** * Processes requests from external systems (i.e., not the front-end web UI). * First use case is ONAP Controller, which has to create an admin and onboard @@ -93,90 +87,72 @@ import io.swagger.annotations.ApiOperation; @Configuration @EnableAspectJAutoProxy @EPAuditLog +@NoArgsConstructor public class AppsControllerExternalRequest implements BasicAuthenticationController { - private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory(); - - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsControllerExternalRequest.class); - private static final String ONBOARD_APP = "/onboardApp"; + private static final String DATA_IS_NOT_VALID = "Data is not valid"; + private static final String REQUEST = "request"; + private static final String RESPONSE = "response"; - /** - * For testing whether a user is a superadmin. - */ - @Autowired - private AdminRolesService adminRolesService; + private static final DataValidator DATA_VALIDATOR = new DataValidator(); + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AppsControllerExternalRequest.class); - /** - * For onboarding or updating an app - */ - @Autowired + private AdminRolesService adminRolesService; private EPAppService appService; - - /** - * For promoting a user to Portal admin - */ - @Autowired private PortalAdminService portalAdminService; + private UserService userService; - /** - * For creating a new user - */ @Autowired - private UserService userService; + public AppsControllerExternalRequest(AdminRolesService adminRolesService, + EPAppService appService, PortalAdminService portalAdminService, + UserService userService) { + this.adminRolesService = adminRolesService; + this.appService = appService; + this.portalAdminService = portalAdminService; + this.userService = userService; + } + /** * Creates a new user as a Portal administrator. - * + * * <PRE> - { - "loginId" : "abc123", - "loginPwd": "", - "email":"ecomp@controller" - } + * { "loginId" : "abc123", "loginPwd": "", "email":"ecomp@controller" } * </PRE> - * - * @param request - * HttpServletRequest - * @param epUser - * User details; the email and orgUserId fields are mandatory - * @param response - * HttpServletResponse + * + * @param request HttpServletRequest + * @param epUser User details; the email and orgUserId fields are mandatory + * @param response HttpServletResponse * @return PortalRestResponse with success or failure */ @ApiOperation(value = "Creates a new user as a Portal administrator.", response = PortalRestResponse.class) @RequestMapping(value = "/portalAdmin", method = RequestMethod.POST, produces = "application/json") @ResponseBody public PortalRestResponse<String> postPortalAdmin(HttpServletRequest request, HttpServletResponse response, - @Valid @RequestBody EPUser epUser) { - EcompPortalUtils.logAndSerializeObject(logger, "postPortalAdmin", "request", epUser); + @Valid @RequestBody EPUser epUser) { + EcompPortalUtils.logAndSerializeObject(logger, "postPortalAdmin", REQUEST, epUser); PortalRestResponse<String> portalResponse = new PortalRestResponse<>(); + if (epUser == null) { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("User can not be NULL"); + return portalResponse; + } else if (!DATA_VALIDATOR.isValid(epUser)) { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage(DATA_IS_NOT_VALID); + return portalResponse; + } - if (epUser != null) { - Validator validator = VALIDATOR_FACTORY.getValidator(); - Set<ConstraintViolation<EPUser>> constraintViolations = validator.validate(epUser); - if (!constraintViolations.isEmpty()) { - portalResponse.setStatus(PortalRestStatusEnum.ERROR); - portalResponse.setMessage("Data is not valid"); - return portalResponse; - } - } - - // Check mandatory fields. - if (epUser != null && (epUser.getEmail() == null || epUser.getEmail().trim().length() == 0 // - || epUser.getLoginId() == null || epUser.getLoginId().trim().length() == 0 // - || epUser.getLoginPwd() == null)) { - portalResponse.setStatus(PortalRestStatusEnum.ERROR); - portalResponse.setMessage("Missing required field: email, loginId, or loginPwd"); - return portalResponse; - } + if (epUser.getEmail() == null || epUser.getEmail().trim().length() == 0 // + || epUser.getLoginId() == null || epUser.getLoginId().trim().length() == 0 // + || epUser.getLoginPwd() == null) { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("Missing required field: email, loginId, or loginPwd"); + return portalResponse; + } try { - // Check for existing user; create if not found. - List<EPUser> userList = null; - if (epUser != null) { - userList = userService.getUserByUserId(epUser.getOrgUserId()); - } - + // Check for existing user; create if not found. + List<EPUser> userList = userService.getUserByUserId(epUser.getOrgUserId()); if (userList == null || userList.isEmpty()) { // Create user with first, last names etc.; do check for // duplicates. @@ -192,11 +168,9 @@ public class AppsControllerExternalRequest implements BasicAuthenticationControl if (adminRolesService.isSuperAdmin(epUser)) { portalResponse.setStatus(PortalRestStatusEnum.OK); } else { - FieldsValidator fv = null; - if (epUser != null) { - fv = portalAdminService.createPortalAdmin(epUser.getOrgUserId()); - } - if (fv != null && fv.httpStatusCode.intValue() == HttpServletResponse.SC_OK) { + FieldsValidator fv; + fv = portalAdminService.createPortalAdmin(epUser.getOrgUserId()); + if (fv != null && fv.httpStatusCode.intValue() == HttpServletResponse.SC_OK) { portalResponse.setStatus(PortalRestStatusEnum.OK); } else { portalResponse.setStatus(PortalRestStatusEnum.ERROR); @@ -207,123 +181,105 @@ public class AppsControllerExternalRequest implements BasicAuthenticationControl } } catch (Exception ex) { // Uncaught exceptions yield 404 and an empty error page + logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), ex); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); portalResponse.setStatus(PortalRestStatusEnum.ERROR); portalResponse.setMessage(ex.toString()); } - EcompPortalUtils.logAndSerializeObject(logger, "postPortalAdmin", "response", portalResponse); + EcompPortalUtils.logAndSerializeObject(logger, "postPortalAdmin", RESPONSE, portalResponse); return portalResponse; } /** * Gets the specified application that is on-boarded in Portal. - * - * @param request - * HttpServletRequest - * @param appId - * Application ID to get - * @param response - * httpServletResponse + * + * @param request HttpServletRequest + * @param appId Application ID to get + * @param response httpServletResponse * @return OnboardingApp objects */ @ApiOperation(value = "Gets the specified application that is on-boarded in Portal.", response = OnboardingApp.class) - @RequestMapping(value = { ONBOARD_APP + "/{appId}" }, method = RequestMethod.GET, produces = "application/json") + @RequestMapping(value = {ONBOARD_APP + "/{appId}"}, method = RequestMethod.GET, produces = "application/json") @ResponseBody public OnboardingApp getOnboardAppExternal(HttpServletRequest request, HttpServletResponse response, - @PathVariable("appId") Long appId) { + @PathVariable("appId") Long appId) { EPApp epApp = appService.getApp(appId); OnboardingApp obApp = new OnboardingApp(); epApp.setAppPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD); //to hide password from get request appService.createOnboardingFromApp(epApp, obApp); - EcompPortalUtils.logAndSerializeObject(logger, "getOnboardAppExternal", "response", obApp); + EcompPortalUtils.logAndSerializeObject(logger, "getOnboardAppExternal", RESPONSE, obApp); return obApp; } /** - * Adds a new application to Portal. The My Logins App Owner in the request - * must be the organization user ID of a person who is a Portal - * administrator. - * + * Adds a new application to Portal. The My Logins App Owner in the request must be the organization user ID of a + * person who is a Portal administrator. + * * <pre> - * { - "myLoginsAppOwner" : "abc123", - "name": "dashboard", - "url": "http://k8s/something", - "restUrl" : "http://targeturl.com", - "restrictedApp" : true, - "isOpen" : true, - "isEnabled": false - } + * { + * "myLoginsAppOwner" : "abc123", + * "name": "dashboard", + * "url": "http://k8s/something", + * "restUrl" : "http://targeturl.com", + * "restrictedApp" : true, + * "isOpen" : true, + * "isEnabled": false + * } * </pre> - * - * @param request - * HttpServletRequest - * @param response - * httpServletResponse - * @param newOnboardApp - * Message with details about the app to add + * + * @param request HttpServletRequest + * @param response httpServletResponse + * @param newOnboardApp Message with details about the app to add * @return PortalRestResponse */ @ApiOperation(value = "Adds a new application to Portal.", response = PortalRestResponse.class) - @RequestMapping(value = { ONBOARD_APP }, method = RequestMethod.POST, produces = "application/json") + @RequestMapping(value = {ONBOARD_APP}, method = RequestMethod.POST, produces = "application/json") @ResponseBody public PortalRestResponse<String> postOnboardAppExternal(HttpServletRequest request, HttpServletResponse response, - @Valid @RequestBody OnboardingApp newOnboardApp) { - EcompPortalUtils.logAndSerializeObject(logger, "postOnboardAppExternal", "request", newOnboardApp); + @Valid @RequestBody OnboardingApp newOnboardApp) { + EcompPortalUtils.logAndSerializeObject(logger, "postOnboardAppExternal", REQUEST, newOnboardApp); PortalRestResponse<String> portalResponse = new PortalRestResponse<>(); - if (newOnboardApp != null){ - Validator validator = VALIDATOR_FACTORY.getValidator(); - Set<ConstraintViolation<OnboardingApp>> constraintViolations = validator.validate(newOnboardApp); - if (!constraintViolations.isEmpty()){ + if (newOnboardApp == null) { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("newOnboardApp can not be NULL"); + return portalResponse; + } else if (!DATA_VALIDATOR.isValid(newOnboardApp)) { portalResponse.setStatus(PortalRestStatusEnum.ERROR); - portalResponse.setMessage("Data is not valid"); + portalResponse.setMessage(DATA_IS_NOT_VALID); return portalResponse; - } } // Validate fields - if (newOnboardApp != null && newOnboardApp.id != null) { + if (newOnboardApp.id != null) { portalResponse.setStatus(PortalRestStatusEnum.ERROR); portalResponse.setMessage("Unexpected field: id"); return portalResponse; } - if (newOnboardApp != null && (newOnboardApp.name == null || newOnboardApp.name.trim().length() == 0 // - || newOnboardApp.url == null || newOnboardApp.url.trim().length() == 0 // - || newOnboardApp.restUrl == null || newOnboardApp.restUrl.trim().length() == 0 - || newOnboardApp.myLoginsAppOwner == null || newOnboardApp.myLoginsAppOwner.trim().length() == 0 - || newOnboardApp.restrictedApp == null // - || newOnboardApp.isOpen == null // - || newOnboardApp.isEnabled == null)) { - portalResponse.setStatus(PortalRestStatusEnum.ERROR); - portalResponse.setMessage( - "Missing required field: name, url, restUrl, restrictedApp, isOpen, isEnabled, myLoginsAppOwner"); - return portalResponse; - } + if (checkOnboardingApp(newOnboardApp)) { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage( + "Missing required field: name, url, restUrl, restrictedApp, isOpen, isEnabled, myLoginsAppOwner"); + return portalResponse; + } try { - List<EPUser> userList = null; - if (newOnboardApp != null) { - userList = userService.getUserByUserId(newOnboardApp.myLoginsAppOwner); - } - if (userList == null || userList.size() != 1) { + List<EPUser> userList; + userList = userService.getUserByUserId(newOnboardApp.myLoginsAppOwner); + if (userList == null || userList.size() != 1) { portalResponse.setStatus(PortalRestStatusEnum.ERROR); - if (newOnboardApp != null) { - portalResponse.setMessage("Failed to find user: " + newOnboardApp.myLoginsAppOwner); - } else { - portalResponse.setMessage("Failed to find user"); - } + portalResponse.setMessage("Failed to find user: " + newOnboardApp.myLoginsAppOwner); return portalResponse; } EPUser epUser = userList.get(0); // Check for Portal admin status - if (! adminRolesService.isSuperAdmin(epUser)) { + if (!adminRolesService.isSuperAdmin(epUser)) { portalResponse.setStatus(PortalRestStatusEnum.ERROR); portalResponse.setMessage("User lacks Portal admin role: " + epUser.getLoginId()); - return portalResponse; + return portalResponse; } - + newOnboardApp.normalize(); FieldsValidator fv = appService.addOnboardingApp(newOnboardApp, epUser); if (fv.httpStatusCode.intValue() == HttpServletResponse.SC_OK) { @@ -334,99 +290,86 @@ public class AppsControllerExternalRequest implements BasicAuthenticationControl } } catch (Exception ex) { // Uncaught exceptions yield 404 and an empty error page + logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), ex); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); portalResponse.setStatus(PortalRestStatusEnum.ERROR); portalResponse.setMessage(ex.toString()); } - EcompPortalUtils.logAndSerializeObject(logger, "postOnboardAppExternal", "response", portalResponse); + EcompPortalUtils.logAndSerializeObject(logger, "postOnboardAppExternal", RESPONSE, portalResponse); return portalResponse; } /** - * Updates information about an on-boarded application in Portal. The My - * Logins App Owner in the request must be the organization user ID of a - * person who is a Portal administrator. + * Updates information about an on-boarded application in Portal. The My Logins App Owner in the request must be + * the organization user ID of a person who is a Portal administrator. * <pre> - { - "id" : 123, - "myLoginsAppOwner" : "abc123", - "name": "dashboard", - "url": "http://k8s/something", - "restUrl" : "http://targeturl.com", - "restrictedApp" : true, - "isOpen" : true, - "isEnabled": false - } - </pre> - * @param request - * HttpServletRequest - * @param response - * httpServletResponse - * @param appId - * application id - * @param oldOnboardApp - * Message with details about the app to add + * { + * "id" : 123, + * "myLoginsAppOwner" : "abc123", + * "name": "dashboard", + * "url": "http://k8s/something", + * "restUrl" : "http://targeturl.com", + * "restrictedApp" : true, + * "isOpen" : true, + * "isEnabled": false + * } + * </pre> + * + * @param request HttpServletRequest + * @param response httpServletResponse + * @param appId application id + * @param oldOnboardApp Message with details about the app to add * @return PortalRestResponse */ @ApiOperation(value = "Updates information about an on-boarded application in Portal.", response = PortalRestResponse.class) - @RequestMapping(value = { ONBOARD_APP + "/{appId}" }, method = RequestMethod.PUT, produces = "application/json") + @RequestMapping(value = {ONBOARD_APP + "/{appId}"}, method = RequestMethod.PUT, produces = "application/json") @ResponseBody public PortalRestResponse<String> putOnboardAppExternal(HttpServletRequest request, HttpServletResponse response, - @PathVariable("appId") Long appId, @Valid @RequestBody OnboardingApp oldOnboardApp) { - EcompPortalUtils.logAndSerializeObject(logger, "putOnboardAppExternal", "request", oldOnboardApp); + @PathVariable("appId") Long appId, @Valid @RequestBody OnboardingApp oldOnboardApp) { + EcompPortalUtils.logAndSerializeObject(logger, "putOnboardAppExternal", REQUEST, oldOnboardApp); PortalRestResponse<String> portalResponse = new PortalRestResponse<>(); - if (oldOnboardApp != null){ - Validator validator = VALIDATOR_FACTORY.getValidator(); - Set<ConstraintViolation<OnboardingApp>> constraintViolations = validator.validate(oldOnboardApp); - if (!constraintViolations.isEmpty()){ + if (oldOnboardApp == null){ + portalResponse.setStatus(PortalRestStatusEnum.ERROR); + portalResponse.setMessage("OnboardingApp can not be NULL"); + return portalResponse; + }else if (!DATA_VALIDATOR.isValid(oldOnboardApp)) { portalResponse.setStatus(PortalRestStatusEnum.ERROR); - portalResponse.setMessage("Data is not valid"); + portalResponse.setMessage(DATA_IS_NOT_VALID); return portalResponse; - } } // Validate fields. - if (oldOnboardApp !=null && (oldOnboardApp.id == null || !appId.equals(oldOnboardApp.id))) { + + if (appId == null || !appId.equals(oldOnboardApp.id)) { portalResponse.setStatus(PortalRestStatusEnum.ERROR); portalResponse.setMessage("Unexpected value for field: id"); return portalResponse; } - if (oldOnboardApp !=null && (oldOnboardApp.name == null || oldOnboardApp.name.trim().length() == 0 // - || oldOnboardApp.url == null || oldOnboardApp.url.trim().length() == 0 // - || oldOnboardApp.restUrl == null || oldOnboardApp.restUrl.trim().length() == 0 - || oldOnboardApp.myLoginsAppOwner == null || oldOnboardApp.myLoginsAppOwner.trim().length() == 0 - || oldOnboardApp.restrictedApp == null // - || oldOnboardApp.isOpen == null // - || oldOnboardApp.isEnabled == null)) { + if (checkOnboardingApp(oldOnboardApp)) { + portalResponse.setStatus(PortalRestStatusEnum.ERROR); portalResponse.setMessage( - "Missing required field: name, url, restUrl, restrictedApp, isOpen, isEnabled, myLoginsAppOwner"); + "Missing required field: name, url, restUrl, restrictedApp, isOpen, isEnabled, myLoginsAppOwner"); return portalResponse; } try { - List<EPUser> userList = null; - if (oldOnboardApp != null) { - userList = userService.getUserByUserId(oldOnboardApp.myLoginsAppOwner); - } - if (userList == null || userList.size() != 1) { + List<EPUser> userList; + userList = userService.getUserByUserId(oldOnboardApp.myLoginsAppOwner); + if (userList == null || userList.size() != 1) { portalResponse.setStatus(PortalRestStatusEnum.ERROR); - if (oldOnboardApp != null) { - portalResponse.setMessage("Failed to find user: " + oldOnboardApp.myLoginsAppOwner); - } else { - portalResponse.setMessage("Failed to find user"); - } + portalResponse.setMessage("Failed to find user: " + oldOnboardApp.myLoginsAppOwner); - return portalResponse; + return portalResponse; } EPUser epUser = userList.get(0); // Check for Portal admin status - if (! adminRolesService.isSuperAdmin(epUser)) { + if (!adminRolesService.isSuperAdmin(epUser)) { portalResponse.setStatus(PortalRestStatusEnum.ERROR); portalResponse.setMessage("User lacks Portal admin role: " + epUser.getLoginId()); - return portalResponse; + return portalResponse; } oldOnboardApp.normalize(); @@ -439,12 +382,29 @@ public class AppsControllerExternalRequest implements BasicAuthenticationControl } } catch (Exception ex) { // Uncaught exceptions yield 404 and an empty error page + logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), ex); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); portalResponse.setStatus(PortalRestStatusEnum.ERROR); portalResponse.setMessage(ex.toString()); } - EcompPortalUtils.logAndSerializeObject(logger, "putOnboardAppExternal", "response", portalResponse); + EcompPortalUtils.logAndSerializeObject(logger, "putOnboardAppExternal", RESPONSE, portalResponse); return portalResponse; } + private boolean checkOnboardingApp(OnboardingApp onboardingApp) { + return checkIfFieldsAreNull(onboardingApp) || checkIfFieldsAreEmpty(onboardingApp); + } + + private boolean checkIfFieldsAreNull(OnboardingApp onboardingApp) { + return onboardingApp.name == null || onboardingApp.url == null || onboardingApp.restUrl == null + || onboardingApp.myLoginsAppOwner == null || onboardingApp.restrictedApp == null + || onboardingApp.isOpen == null || onboardingApp.isEnabled == null; + } + + private boolean checkIfFieldsAreEmpty(OnboardingApp onboardingApp) { + return onboardingApp.name.trim().isEmpty() + || onboardingApp.url.trim().isEmpty() + || onboardingApp.restUrl.trim().isEmpty() + || onboardingApp.myLoginsAppOwner.trim().isEmpty(); + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerController.java index af34176c..69f25683 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerController.java @@ -41,7 +41,6 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; @@ -49,12 +48,12 @@ import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import lombok.NoArgsConstructor; import org.json.simple.JSONObject; import org.onap.portalapp.controller.EPRestrictedBaseController; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum; -import org.onap.portalapp.portal.exceptions.RoleFunctionException; import org.onap.portalapp.portal.logging.aop.EPAuditLog; import org.onap.portalapp.portal.logging.logic.EPLogUtil; import org.onap.portalapp.portal.scheduler.SchedulerProperties; @@ -70,7 +69,6 @@ import org.onap.portalapp.portal.service.AdminRolesService; import org.onap.portalapp.portal.utils.PortalConstants; import org.onap.portalapp.util.EPUserUtils; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.service.DataAccessService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @@ -87,62 +85,66 @@ import org.springframework.web.bind.annotation.RestController; @Configuration @EnableAspectJAutoProxy @EPAuditLog +@NoArgsConstructor public class SchedulerController extends EPRestrictedBaseController { + private static final String USER_IS_UNAUTHORIZED_TO_MAKE_THIS_CALL = "User is unauthorized to make this call"; + + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerController.class); + private static final DateFormat requestDateFormat = new SimpleDateFormat("EEE, dd MMM YYYY HH:mm:ss z"); - @Autowired private SchedulerRestInterface schedulerRestController; - - @Autowired private AdminRolesService adminRolesService; - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerController.class); - - /** The request date format. */ - public DateFormat requestDateFormat = new SimpleDateFormat("EEE, dd MMM YYYY HH:mm:ss z"); + @Autowired + public SchedulerController(SchedulerRestInterface schedulerRestController, + AdminRolesService adminRolesService) { + this.schedulerRestController = schedulerRestController; + this.adminRolesService = adminRolesService; + } @RequestMapping(value = "/get_time_slots/{scheduler_request}", method = RequestMethod.GET, produces = "application/json") public ResponseEntity<String> getTimeSlots(HttpServletRequest request, - @PathVariable("scheduler_request") String scheduler_request) throws Exception { + @PathVariable("scheduler_request") String schedulerRequest) throws Exception { if (checkIfUserISValidToMakeSchedule(request)) { try { Date startingTime = new Date(); String startTimeRequest = requestDateFormat.format(startingTime); logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler GET Timeslots for startTimeRequest: ", startTimeRequest); - logger.debug(EELFLoggerDelegate.debugLogger, "Original Request = {} ", scheduler_request); + logger.debug(EELFLoggerDelegate.debugLogger, "Original Request = {} ", schedulerRequest); String path = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_GET_TIME_SLOTS) - + scheduler_request; + + schedulerRequest; - GetTimeSlotsWrapper schedulerResWrapper = getTimeSlots(scheduler_request, path, scheduler_request); + GetTimeSlotsWrapper schedulerResWrapper = getTimeSlots(path, schedulerRequest); Date endTime = new Date(); String endTimeRequest = requestDateFormat.format(endTime); logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler - GET for EndTimeRequest = {}", endTimeRequest); - return (new ResponseEntity<String>(schedulerResWrapper.getResponse(), - HttpStatus.valueOf(schedulerResWrapper.getStatus()))); + return (new ResponseEntity<>(schedulerResWrapper.getResponse(), + HttpStatus.valueOf(schedulerResWrapper.getStatus()))); } catch (Exception e) { GetTimeSlotsWrapper schedulerResWrapper = new GetTimeSlotsWrapper(); schedulerResWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); schedulerResWrapper.setEntity(e.getMessage()); logger.error(EELFLoggerDelegate.errorLogger, "Exception with getTimeslots", e); - return (new ResponseEntity<String>(schedulerResWrapper.getResponse(), - HttpStatus.INTERNAL_SERVER_ERROR)); + return (new ResponseEntity<>(schedulerResWrapper.getResponse(), + HttpStatus.INTERNAL_SERVER_ERROR)); } }else{ - return (new ResponseEntity<String>("User is unauthorized to make this call", HttpStatus.UNAUTHORIZED)); + return (new ResponseEntity<>(USER_IS_UNAUTHORIZED_TO_MAKE_THIS_CALL, HttpStatus.UNAUTHORIZED)); } } - protected GetTimeSlotsWrapper getTimeSlots(String request, String path, String uuid) throws Exception { + protected GetTimeSlotsWrapper getTimeSlots(String path, String uuid) throws Exception { try { // STARTING REST API CALL AS AN FACTORY INSTACE logger.debug(EELFLoggerDelegate.debugLogger, "Get Time Slots Request START"); - GetTimeSlotsRestObject<String> restObjStr = new GetTimeSlotsRestObject<String>(); - String str = new String(); + GetTimeSlotsRestObject<String> restObjStr = new GetTimeSlotsRestObject<>(); + String str = ""; restObjStr.set(str); @@ -169,7 +171,7 @@ public class SchedulerController extends EPRestrictedBaseController { @SuppressWarnings("unchecked") @RequestMapping(value = "/post_create_new_vnf_change", method = RequestMethod.POST, produces = "application/json") public ResponseEntity<String> postCreateNewVNFChange(HttpServletRequest request, - @RequestBody JSONObject scheduler_request) throws Exception { + @RequestBody JSONObject schedulerRequest) throws Exception { if (checkIfUserISValidToMakeSchedule(request)) { try { Date startingTime = new Date(); @@ -181,34 +183,34 @@ public class SchedulerController extends EPRestrictedBaseController { // Generating uuid String uuid = UUID.randomUUID().toString(); - scheduler_request.put("scheduleId", uuid); + schedulerRequest.put("scheduleId", uuid); logger.debug(EELFLoggerDelegate.debugLogger, "UUID = {} ", uuid); // adding uuid to the request payload - scheduler_request.put("scheduleId", uuid); - logger.debug(EELFLoggerDelegate.debugLogger, "Original Request = {}", scheduler_request.toString()); + schedulerRequest.put("scheduleId", uuid); + logger.debug(EELFLoggerDelegate.debugLogger, "Original Request = {}", schedulerRequest.toString()); String path = SchedulerProperties .getProperty(SchedulerProperties.SCHEDULER_CREATE_NEW_VNF_CHANGE_INSTANCE_VAL) + uuid; - PostCreateNewVnfWrapper responseWrapper = postSchedulingRequest(scheduler_request, path, uuid); + PostCreateNewVnfWrapper responseWrapper = postSchedulingRequest(schedulerRequest, path, uuid); Date endTime = new Date(); String endTimeRequest = requestDateFormat.format(endTime); logger.debug(EELFLoggerDelegate.debugLogger, "Controller Scheduler - POST= {}", endTimeRequest); - return new ResponseEntity<String>(responseWrapper.getResponse(), - HttpStatus.valueOf(responseWrapper.getStatus())); + return new ResponseEntity<>(responseWrapper.getResponse(), + HttpStatus.valueOf(responseWrapper.getStatus())); } catch (Exception e) { PostCreateNewVnfWrapper responseWrapper = new PostCreateNewVnfWrapper(); responseWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); responseWrapper.setEntity(e.getMessage()); logger.error(EELFLoggerDelegate.errorLogger, "Exception with postCreateNewVNFChange ", e); - return (new ResponseEntity<String>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR)); + return (new ResponseEntity<>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR)); } }else{ - return (new ResponseEntity<String>("User is unauthorized to make this call",HttpStatus.UNAUTHORIZED)); + return (new ResponseEntity<>(USER_IS_UNAUTHORIZED_TO_MAKE_THIS_CALL, HttpStatus.UNAUTHORIZED)); } } @@ -219,11 +221,11 @@ public class SchedulerController extends EPRestrictedBaseController { try { // STARTING REST API CALL AS AN FACTORY INSTACE - PostCreateNewVnfRestObject<String> restObjStr = new PostCreateNewVnfRestObject<String>(); - String str = new String(); + PostCreateNewVnfRestObject<String> restObjStr = new PostCreateNewVnfRestObject<>(); + String str = ""; restObjStr.set(str); - schedulerRestController.<String>Post(str, request, path, restObjStr); + schedulerRestController.Post(str, request, path, restObjStr); int status = restObjStr.getStatusCode(); if (status >= 200 && status <= 299) { @@ -249,7 +251,7 @@ public class SchedulerController extends EPRestrictedBaseController { @RequestMapping(value = "/submit_vnf_change_timeslots", method = RequestMethod.POST, produces = "application/json") public ResponseEntity<String> postSubmitVnfChangeTimeslots(HttpServletRequest request, - @RequestBody JSONObject scheduler_request) throws Exception { + @RequestBody JSONObject schedulerRequest) throws Exception { if (checkIfUserISValidToMakeSchedule(request)) { try { Date startingTime = new Date(); @@ -258,17 +260,17 @@ public class SchedulerController extends EPRestrictedBaseController { startTimeRequest); // Generating uuid - String uuid = (String) scheduler_request.get("scheduleId"); + String uuid = (String) schedulerRequest.get("scheduleId"); logger.debug(EELFLoggerDelegate.debugLogger, "UUID = {} ", uuid); - scheduler_request.remove("scheduleId"); + schedulerRequest.remove("scheduleId"); logger.debug(EELFLoggerDelegate.debugLogger, "Original Request for the schedulerId= {} ", - scheduler_request.toString()); + schedulerRequest.toString()); String path = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SUBMIT_NEW_VNF_CHANGE) .replace("{scheduleId}", uuid); - PostSubmitVnfChangeTimeSlotsWrapper responseWrapper = postSubmitSchedulingRequest(scheduler_request, path, + PostSubmitVnfChangeTimeSlotsWrapper responseWrapper = postSubmitSchedulingRequest(schedulerRequest, path, uuid); Date endTime = new Date(); @@ -276,17 +278,17 @@ public class SchedulerController extends EPRestrictedBaseController { logger.debug(EELFLoggerDelegate.debugLogger, " Controller Scheduler - POST Submit for end time request= {}", endTimeRequest); - return (new ResponseEntity<String>(responseWrapper.getResponse(),HttpStatus.valueOf(responseWrapper.getStatus()))); + return (new ResponseEntity<>(responseWrapper.getResponse(), HttpStatus.valueOf(responseWrapper.getStatus()))); } catch (Exception e) { PostSubmitVnfChangeTimeSlotsWrapper responseWrapper = new PostSubmitVnfChangeTimeSlotsWrapper(); responseWrapper.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); responseWrapper.setEntity(e.getMessage()); logger.error(EELFLoggerDelegate.errorLogger, "Exception with Post submit Vnf change Timeslots", e); - return (new ResponseEntity<String>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR)); + return (new ResponseEntity<>(responseWrapper.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR)); } }else{ - return (new ResponseEntity<String>("User is unauthorized to make this call",HttpStatus.UNAUTHORIZED)); + return (new ResponseEntity<>(USER_IS_UNAUTHORIZED_TO_MAKE_THIS_CALL, HttpStatus.UNAUTHORIZED)); } } @@ -296,11 +298,11 @@ public class SchedulerController extends EPRestrictedBaseController { try { // STARTING REST API CALL AS AN FACTORY INSTACE - PostSubmitVnfChangeRestObject<String> restObjStr = new PostSubmitVnfChangeRestObject<String>(); - String str = new String(); + PostSubmitVnfChangeRestObject<String> restObjStr = new PostSubmitVnfChangeRestObject<>(); + String str = ""; restObjStr.set(str); - schedulerRestController.<String>Post(str, request, path, restObjStr); + schedulerRestController.Post(str, request, path, restObjStr); int status = restObjStr.getStatusCode(); if (status >= 200 && status <= 299) { @@ -362,19 +364,19 @@ public class SchedulerController extends EPRestrictedBaseController { throw new Exception(entry.getKey() + errorMsg); } logger.debug(EELFLoggerDelegate.debugLogger, " portalRestResponse - getSchedulerConstant= {}", map); - portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.OK, "success", - map); + portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", + map); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "getSchedulerConstant failed", e); - portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.ERROR, - e.getMessage(), null); + portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, + e.getMessage(), null); } } else{ logger.error(EELFLoggerDelegate.errorLogger, "getSchedulerConstant failed: User unauthorized to make this call"); - portalRestResponse = new PortalRestResponse<Map<String, String>>(PortalRestStatusEnum.ERROR, "failed : Unauthorized", null); + portalRestResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "failed : Unauthorized", null); } return portalRestResponse; } @@ -397,8 +399,6 @@ public class SchedulerController extends EPRestrictedBaseController { EPUser user = EPUserUtils.getUserSession(request); String portalApiPath = getPath(request); Set<String> functionCodeList = adminRolesService.getAllAppsFunctionsOfUser(user.getId().toString()); - boolean isValidUser = EPUserUtils.matchRoleFunctions(portalApiPath, functionCodeList); -// boolean isValidUser = functionCodeList.stream().anyMatch(x -> functionCodeList.contains(portalApiPath)); - return isValidUser; + return EPUserUtils.matchRoleFunctions(portalApiPath, functionCodeList); } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/ExternalRoleDetails.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/ExternalRoleDetails.java index e561c8d3..bb902786 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/ExternalRoleDetails.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/ExternalRoleDetails.java @@ -38,78 +38,27 @@ package org.onap.portalapp.portal.domain; import java.util.List; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; +@Getter +@Setter +@EqualsAndHashCode public class ExternalRoleDetails implements Comparable { - private String name; private boolean active; private Integer priority; - private Long appId; // used by ONAP only private Long appRoleId; // used by ONAP only - private List<EPAppRoleFunction> perms; - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public boolean isActive() { - return active; - } - - public void setActive(boolean active) { - this.active = active; - } - - public Integer getPriority() { - return priority; - } - - public void setPriority(Integer priority) { - this.priority = priority; - } - - public Long getAppId() { - return appId; - } - - public void setAppId(Long appId) { - this.appId = appId; - } - - public Long getAppRoleId() { - return appRoleId; - } - - public void setAppRoleId(Long appRoleId) { - this.appRoleId = appRoleId; - } - - - - public List<EPAppRoleFunction> getPerms() { - return perms; - } - - public void setPerms(List<EPAppRoleFunction> perms) { - this.perms = perms; - } - @Override public int compareTo(Object obj) { EPRole other = (EPRole)obj; - - String c1 = getName(); - String c2 = other.getName(); - - return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); + return (this.getName() == null || other.getName() == null) ? 1 : getName().equals(other.getName()) ? 0 : 1; } - + } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterface.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterface.java index 1886b8b5..14dfebee 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterface.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterface.java @@ -37,20 +37,20 @@ */ package org.onap.portalapp.portal.scheduler; -import java.lang.reflect.Type; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializer; import java.util.Collections; import java.util.Date; - import javax.security.auth.login.CredentialException; import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.Response; - +import lombok.NoArgsConstructor; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; -import org.apache.cxf.jaxrs.impl.ResponseImpl; import org.eclipse.jetty.util.security.Password; import org.json.simple.JSONObject; import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum; @@ -63,45 +63,28 @@ import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.client.HttpClientErrorException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonParseException; - +@SuppressWarnings("MalformedFormatString") @Service +@NoArgsConstructor public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { - + private static final String APPLICATION_JSON = "application/json"; private static final String PASSWORD_IS_EMPTY = "Password is Empty"; + private static final String HTTP_CLIENT_ERROR = " HttpClientErrorException: Exception For the POST ." + + " MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON"; + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class); private static Client client = null; + private static Gson gson = null; private MultivaluedHashMap<String, Object> commonHeaders; - /** The logger. */ - static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class); - - public SchedulerRestInterface() { - super(); - } - - Gson gson = null; - - private final ObjectMapper mapper = new ObjectMapper(); - - private void init() { + private static void init() { logger.debug(EELFLoggerDelegate.debugLogger, "initializing"); GsonBuilder builder = new GsonBuilder(); // Register an adapter to manage the date types as long values - builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { - public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { - return new Date(json.getAsJsonPrimitive().getAsLong()); - } - }); + builder.registerTypeAdapter(Date.class, + (JsonDeserializer<Date>) (json, typeOfT, context) -> new Date(json.getAsJsonPrimitive().getAsLong())); gson = builder.create(); } @@ -114,7 +97,6 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { final String username; final String password; - String methodName = "initRestClient"; /* Setting user name based on properties */ String retrievedUsername = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_USER_NAME_VAL); if (retrievedUsername.isEmpty()) { @@ -145,8 +127,8 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); - commonHeaders = new MultivaluedHashMap<String, Object>(); - commonHeaders.put("Authorization", Collections.singletonList((Object) ("Basic " + authStringEnc))); + commonHeaders = new MultivaluedHashMap<>(); + commonHeaders.put("Authorization", Collections.singletonList(("Basic " + authStringEnc))); try { if (!username.isEmpty()) { @@ -166,7 +148,7 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { @SuppressWarnings("unchecked") public <T> void Get(T t, String sourceId, String path, - org.onap.portalapp.portal.scheduler.restobjects.RestObject<T> restObject) throws Exception { + org.onap.portalapp.portal.scheduler.restobjects.RestObject<T> restObject) { String methodName = "Get"; String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path; @@ -175,14 +157,14 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { try { initRestClient(); - final Response cres = client.target(url).request().accept("application/json").headers(commonHeaders).get(); + final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders).get(); int status = cres.getStatus(); restObject.setStatusCode(status); - if (cres != null && cres.getEntity() != null) { + if (cres.getEntity() != null) { try { - String str = ((ResponseImpl) cres).readEntity(String.class); + String str = (cres).readEntity(String.class); if (t.getClass().getName().equals(String.class.getName())) { t = (T) str; @@ -195,23 +177,21 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { } } else { t = null; - restObject.set(t); + restObject.set(null); } - // t = (T) cres.readEntity(t.getClass()); - - if (t.equals("")) { + if ("".equals(t)) { restObject.set(null); } else { restObject.set(t); } } catch (HttpClientErrorException e) { String message = String.format( - " HttpClientErrorException: Exception For the POST . MethodName: %s, Url: %s", methodName, url); + HTTP_CLIENT_ERROR, methodName, url); logger.error(EELFLoggerDelegate.errorLogger, message, e); EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value()); } catch (Exception e) { - String message = String.format("Exception For the POST . MethodName: %s, Url: %s", methodName, url); + String message = String.format("Exception For the POST . MethodName: %APPLICATION_JSON, Url: %APPLICATION_JSON", methodName, url); logger.error(EELFLoggerDelegate.errorLogger, message, e); EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value()); @@ -223,7 +203,7 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { } @SuppressWarnings("unchecked") - public <T> void Post(T t, JSONObject requestDetails, String path, RestObject<T> restObject) throws Exception { + public <T> void Post(T t, JSONObject requestDetails, String path, RestObject<T> restObject) { String methodName = "Post"; String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path; @@ -234,13 +214,13 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { initRestClient(); // Change the content length - final Response cres = client.target(url).request().accept("application/json").headers(commonHeaders) + final Response cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders) .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON)); if (cres != null && cres.getEntity() != null) { try { - String str = ((ResponseImpl) cres).readEntity(String.class); + String str = (cres).readEntity(String.class); if (t.getClass().getName().equals(String.class.getName())) { t = (T) str; @@ -251,14 +231,12 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { } catch (Exception e) { EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e); } - // t = (T) cres.readEntity(t.getClass()); restObject.set(t); } else { - t = null; - restObject.set(t); + restObject.set(null); } - int status = cres.getStatus(); + int status = cres != null ? cres.getStatus() : 0; restObject.setStatusCode(status); if (status >= 200 && status <= 299) { @@ -266,19 +244,19 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { logger.debug(EELFLoggerDelegate.debugLogger, message); } else { - String message = String.format(" FAILED with http status . MethodName: %s, Status: %s, Url: %s", + String message = String.format(" FAILED with http status . MethodName: %APPLICATION_JSON, Status: %APPLICATION_JSON, Url: %APPLICATION_JSON", methodName, status, url); logger.debug(EELFLoggerDelegate.debugLogger, message); } } catch (HttpClientErrorException e) { String message = String.format( - " HttpClientErrorException: Exception For the POST . MethodName: %s, Url: %s", methodName, url); + HTTP_CLIENT_ERROR, methodName, url); logger.error(EELFLoggerDelegate.errorLogger, message, e); EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value()); } catch (Exception e) { String message = String.format( - " HttpClientErrorException: Exception For the POST . MethodName: %s, Url: %s", methodName, url); + HTTP_CLIENT_ERROR, methodName, url); logger.error(EELFLoggerDelegate.errorLogger, message, e); EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value()); throw e; @@ -287,6 +265,7 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { @Override public void logRequest(JSONObject requestDetails) { + throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") @@ -294,18 +273,16 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { String methodName = "Delete"; String url = ""; - Response cres = null; + Response cres; try { initRestClient(); url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path; - cres = client.target(url).request().accept("application/json").headers(commonHeaders) + cres = client.target(url).request().accept(APPLICATION_JSON).headers(commonHeaders) // .entity(r) .build("DELETE", Entity.entity(requestDetails, MediaType.APPLICATION_JSON)).invoke(); - // .method("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)); - // .delete(Entity.entity(r, MediaType.APPLICATION_JSON)); int status = cres.getStatus(); restObject.setStatusCode(status); @@ -325,8 +302,4 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { } } - public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException { - return clazz.newInstance(); - } - } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterfaceIfc.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterfaceIfc.java index c49dd1d1..8d37a125 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterfaceIfc.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/SchedulerRestInterfaceIfc.java @@ -45,14 +45,14 @@ import org.springframework.stereotype.Service; @Service public interface SchedulerRestInterfaceIfc { - public void initRestClient(); + void initRestClient(); - public <T> void Get(T t, String sourceId, String path, org.onap.portalapp.portal.scheduler.restobjects.RestObject<T> restObject ) throws Exception; + <T> void Get(T t, String sourceId, String path, org.onap.portalapp.portal.scheduler.restobjects.RestObject<T> restObject ) throws Exception; - public <T> void Delete(T t, JSONObject requestDetails, String sourceID, String path, RestObject<T> restObject) + <T> void Delete(T t, JSONObject requestDetails, String sourceID, String path, RestObject<T> restObject) throws Exception; - public <T> void Post(T t, JSONObject r, String path, RestObject<T> restObject) throws Exception; + <T> void Post(T t, JSONObject r, String path, RestObject<T> restObject) throws Exception; - public void logRequest(JSONObject requestDetails); -}
\ No newline at end of file + void logRequest(JSONObject requestDetails); +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPRoleFunctionServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPRoleFunctionServiceImpl.java index 4a3cf63c..c0881640 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPRoleFunctionServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPRoleFunctionServiceImpl.java @@ -86,7 +86,7 @@ public class EPRoleFunctionServiceImpl implements EPRoleFunctionService { .getAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME)); if (roleFunctions == null) { - HashMap roles = EPUserUtils.getRoles(request); + HashMap roles = (HashMap) EPUserUtils.getRoles(request); roleFunctions = new HashSet(); Iterator i = roles.keySet().iterator(); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/EPUserUtils.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/EPUserUtils.java index 99a29116..80db8c86 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/EPUserUtils.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/util/EPUserUtils.java @@ -2,7 +2,7 @@ * ============LICENSE_START========================================== * ONAP Portal * =================================================================== - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * =================================================================== * * Unless otherwise specified, all software contained herein is licensed @@ -41,18 +41,16 @@ import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; - import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; - import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; import org.onap.portalapp.portal.domain.EPRole; @@ -70,18 +68,14 @@ import org.onap.portalsdk.core.web.support.AppUtils; import org.springframework.beans.factory.annotation.Autowired; public class EPUserUtils { - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUserUtils.class); - - private final static Long ACCOUNT_ADMIN_ROLE_ID = 999L; - public static final String ALL_ROLE_FUNCTIONS = "allRoleFunctions"; - - // These decode values are based on HexDecoder + private static final String decodeValueOfForwardSlash = "2f"; private static final String decodeValueOfHyphen = "2d"; private static final String decodeValueOfAsterisk = "2a"; + private static final Long ACCOUNT_ADMIN_ROLE_ID = 999L; + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUserUtils.class); private static DataAccessService dataAccessService; /** @@ -111,15 +105,13 @@ public class EPUserUtils { * Menu data * @param businessDirectMenuData * Menu data - * @param loginMethod_ignored - * How the user authenticated; ignored * @param ePRoleFunctionService * role function service * @throws DecoderException */ @SuppressWarnings("rawtypes") public static void setUserSession(HttpServletRequest request, EPUser user, Set applicationMenuData, - Set businessDirectMenuData, String loginMethod_ignored, EPRoleFunctionService ePRoleFunctionService) throws RoleFunctionException { + Set businessDirectMenuData, EPRoleFunctionService ePRoleFunctionService) throws RoleFunctionException { HttpSession session = request.getSession(true); // clear the current user session to avoid any conflicts @@ -136,9 +128,8 @@ public class EPUserUtils { session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_NAME), user.getFullName()); ServletContext context = session.getServletContext(); - int licenseVerificationFlag = 3; try { - licenseVerificationFlag = (Integer) context.getAttribute("licenseVerification"); + context.getAttribute("licenseVerification"); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "setUserSession failed to get licenseVerification attribute", e); @@ -163,7 +154,7 @@ public class EPUserUtils { private static void setAllRoleFunctions(List<RoleFunction> allRoleFunctions, HttpSession session) throws RoleFunctionException { if (allRoleFunctions == null) return; - Set<String> roleFnSet = new HashSet<String>(); + Set<String> roleFnSet = new HashSet<>(); for (RoleFunction roleFn : allRoleFunctions){ roleFnSet.add(decodeFunctionCode(roleFn.getCode())); } @@ -221,8 +212,8 @@ public class EPUserUtils { * @return Map of role ID to role object */ @SuppressWarnings("rawtypes") - public static HashMap getRoles(HttpServletRequest request) { - HashMap roles = null; + public static Map getRoles(HttpServletRequest request) { + HashMap roles; HttpSession session = AppUtils.getSession(request); roles = (HashMap) session.getAttribute(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME)); @@ -251,11 +242,8 @@ public class EPUserUtils { @SuppressWarnings({ "rawtypes", "unchecked" }) private static HashMap getAllUserRoles(EPUser user) { HashMap roles = new HashMap(); - Iterator i = user.getEPRoles().iterator(); - - while (i.hasNext()) { - EPRole role = (EPRole) i.next(); + for (EPRole role : user.getEPRoles()) { if (role.getActive()) { roles.put(role.getId(), role); @@ -267,9 +255,8 @@ public class EPUserUtils { // Additionally; the account admin role is overloaded between onap // portal and partners; lets also include that - Iterator<EPUserApp> appRolesIterator = user.getEPUserApps().iterator(); - while (appRolesIterator.hasNext()) { - EPRole role = (EPRole) appRolesIterator.next().getRole(); + for (EPUserApp epUserApp : user.getEPUserApps()) { + EPRole role = epUserApp.getRole(); if (role.getActive() && role.getId().equals(ACCOUNT_ADMIN_ROLE_ID)) { roles.put(role.getId(), role); @@ -295,10 +282,9 @@ public class EPUserUtils { private static void addChildRoles(EPRole role, HashMap roles) { Set childRoles = role.getChildRoles(); - if (childRoles != null && childRoles.size() > 0) { - Iterator j = childRoles.iterator(); - while (j.hasNext()) { - EPRole childRole = (EPRole) j.next(); + if (childRoles != null && !childRoles.isEmpty()) { + for (Object o : childRoles) { + EPRole childRole = (EPRole) o; if (childRole.getActive()) { roles.put(childRole.getId(), childRole); @@ -319,7 +305,7 @@ public class EPUserUtils { } @Autowired - public void setDataAccessService(DataAccessService dataAccessService) { + public static void setDataAccessService(DataAccessService dataAccessService) { EPUserUtils.dataAccessService = dataAccessService; } @@ -341,12 +327,10 @@ public class EPUserUtils { * HttpServletREquest * @return Long ID of current user */ - public static Long getUserIdAsLong(HttpServletRequest request) { + static Long getUserIdAsLong(HttpServletRequest request) { Long userId = new Long(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID)); - if (request != null) { - if (getUserSession(request) != null) { + if (request != null && getUserSession(request) != null) { userId = getUserSession(request).getId(); - } } return userId; } @@ -364,7 +348,7 @@ public class EPUserUtils { String requestId = ""; try { while (headerNames.hasMoreElements()) { - String headerName = (String) headerNames.nextElement(); + String headerName = headerNames.nextElement(); logger.debug(EELFLoggerDelegate.debugLogger, "One header is " + headerName + " : " + request.getHeader(headerName)); if (headerName.equalsIgnoreCase(SystemProperties.ECOMP_REQUEST_ID)) { @@ -386,7 +370,7 @@ public class EPUserUtils { * HttpServletRequest * @return Full URL */ - public static String getFullURL(HttpServletRequest request) { + static String getFullURL(HttpServletRequest request) { if (request != null) { StringBuffer requestURL = request.getRequestURL(); String queryString = request.getQueryString(); @@ -402,7 +386,7 @@ public class EPUserUtils { public static Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) { String[] path = portalApiPath.split("/"); - List<String> roleFunList = new ArrayList<>(); + List<String> roleFunList; if (path.length > 1) { roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0])).collect(Collectors.toList()); if (roleFunList.size() >= 1) { @@ -411,17 +395,13 @@ public class EPUserUtils { boolean b = true; if (roleFunctionArray.length == path.length) { for (int i = 0; i < roleFunctionArray.length; i++) { - if (b) { if (!roleFunctionArray[i].equals("*")) { Pattern p = Pattern.compile(Pattern.quote(path[i]), Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(roleFunctionArray[i]); b = m.matches(); - } } - } - if (b) - return b; + if (b) return true; } } } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequestTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequestTest.java index 9d3c7785..4535cf17 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequestTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppsControllerExternalRequestTest.java @@ -51,7 +51,6 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.onap.portalapp.portal.controller.AppsControllerExternalRequest; import org.onap.portalapp.portal.core.MockEPUser; import org.onap.portalapp.portal.domain.EPApp; import org.onap.portalapp.portal.domain.EPUser; @@ -82,7 +81,7 @@ public class AppsControllerExternalRequestTest extends MockitoTestSuite { UserService userService = new UserServiceImpl(); @InjectMocks - AppsControllerExternalRequest appsControllerExternalRequest = new AppsControllerExternalRequest(); + AppsControllerExternalRequest appsControllerExternalRequest; @Before public void setup() { diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java index b1816ec6..5d323012 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/SchedulerControllerTest.java @@ -48,7 +48,6 @@ import javax.servlet.http.HttpServletResponse; import org.apache.poi.ss.formula.functions.T; import org.json.simple.JSONObject; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -56,7 +55,6 @@ import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.onap.portalapp.portal.controller.SchedulerController; import org.onap.portalapp.portal.core.MockEPUser; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.framework.MockitoTestSuite; @@ -84,7 +82,7 @@ public class SchedulerControllerTest { AdminRolesService adminRolesService; @InjectMocks - SchedulerController schedulerController = new SchedulerController(); + SchedulerController schedulerController; @Before public void setup() { diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/util/EPUserUtilsTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/util/EPUserUtilsTest.java index 7383330d..80ca1424 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/util/EPUserUtilsTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/util/EPUserUtilsTest.java @@ -256,7 +256,7 @@ public class EPUserUtilsTest { PowerMockito.when(AppUtils.getSession(mockedRequest)).thenReturn(session); PowerMockito.when(SystemProperties.getProperty(Matchers.anyString())).thenReturn("12"); Mockito.when(session.getAttribute(Matchers.anyString())).thenReturn(roles); - roles=EPUserUtils.getRoles(mockedRequest); + roles= (HashMap) EPUserUtils.getRoles(mockedRequest); assertEquals(roles,expected); @@ -279,7 +279,7 @@ public class EPUserUtilsTest { Mockito.when(session.getAttribute("attr_name")).thenReturn(user); Mockito.when(user.getEPRoles()).thenReturn(role); Mockito.when(session.getAttribute("12")).thenReturn(null); - roles=EPUserUtils.getRoles(mockedRequest); + roles= (HashMap) EPUserUtils.getRoles(mockedRequest); assertEquals(roles,expected); } @@ -320,7 +320,7 @@ public class EPUserUtilsTest { Mockito.when(epRole.getChildRoles()).thenReturn(childRoles); Mockito.when(user.getEPUserApps()).thenReturn(epUserApps); Mockito.when(session.getAttribute("12")).thenReturn(null); - roles= EPUserUtils.getRoles(mockedRequest); + roles= (HashMap) EPUserUtils.getRoles(mockedRequest); assertNotNull(roles); } @@ -358,7 +358,7 @@ public class EPUserUtilsTest { Mockito.when(epRoleFunctionService.getRoleFunctions()).thenReturn(roleFunctions); Mockito.when(MenuBuilder.filterMenu(applicationMenuData, mockedRequest)).thenReturn(applicationMenuData); PowerMockito.when(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).thenReturn("12"); - EPUserUtils.setUserSession(mockedRequest, user, applicationMenuData, businessDirectMenuData, "login_method", epRoleFunctionService); + EPUserUtils.setUserSession(mockedRequest, user, applicationMenuData, businessDirectMenuData, epRoleFunctionService); assertNotNull(session); @@ -383,7 +383,7 @@ public class EPUserUtilsTest { Mockito.when(epRoleFunctionService.getRoleFunctions()).thenReturn(null); Mockito.when(MenuBuilder.filterMenu(applicationMenuData, mockedRequest)).thenReturn(applicationMenuData); PowerMockito.when(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).thenReturn("12"); - EPUserUtils.setUserSession(mockedRequest, user, applicationMenuData, businessDirectMenuData, "login_method", epRoleFunctionService); + EPUserUtils.setUserSession(mockedRequest, user, applicationMenuData, businessDirectMenuData, epRoleFunctionService); assertNotNull(session); } @@ -408,7 +408,7 @@ public class EPUserUtilsTest { Mockito.when(epRoleFunctionService.getRoleFunctions()).thenReturn(null); Mockito.when(MenuBuilder.filterMenu(applicationMenuData, mockedRequest)).thenReturn(applicationMenuData); PowerMockito.when(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).thenReturn("12"); - EPUserUtils.setUserSession(mockedRequest, user, applicationMenuData, businessDirectMenuData, "login_method", epRoleFunctionService); + EPUserUtils.setUserSession(mockedRequest, user, applicationMenuData, businessDirectMenuData, epRoleFunctionService); assertNotNull(session); |