diff options
author | Christopher Lott (cl778h) <clott@research.att.com> | 2017-09-25 16:07:54 -0400 |
---|---|---|
committer | Christopher Lott (cl778h) <clott@research.att.com> | 2017-09-25 16:09:15 -0400 |
commit | 23634dba70b166ad3c79b5eadfbd32b5375d44be (patch) | |
tree | ab0ea364c8da4f91fb8c7e2819692498939fb419 /ecomp-portal-BE-common/src/main | |
parent | 4ba6a0f20a190030700917a6065a6779ca9d308f (diff) |
MariaDB Connector and Sonar Scans; clean nl
PORTAL-50: Fix to get the Sonar coverage for ONAP
PORTAL-72: Sonar scan - resolving severity Blocker issues
PORTAL-86: Remove internal att.com usages from tests and other files
PORTAL-102: Fixed the page refresh issue on App Account Management page
PORTAL-103: Fix to enhanced notification ticket source for ONAP
PORTAL-104: Replaced mysql DB connector with mariaDB
Issue: PORTAL-50 PORTAL-72 PORTAL-86 PORTAL-102 PORTAL-103 PORTAL-104
Change-Id: Iae78ad34ed9ce5ae1f2d36fcbb93fbc1e39944e5
Signed-off-by: Christopher Lott (cl778h) <clott@research.att.com>
Diffstat (limited to 'ecomp-portal-BE-common/src/main')
67 files changed, 4106 insertions, 331 deletions
diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/controller/EPFusionBaseController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/controller/EPFusionBaseController.java index 986f6387..dfea5fef 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/controller/EPFusionBaseController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/controller/EPFusionBaseController.java @@ -78,9 +78,9 @@ public abstract class EPFusionBaseController extends FusionBaseController { public Map<String, Object> setMenu(Set<MenuData> menuResult) throws Exception { ObjectMapper mapper = new ObjectMapper(); List<List<MenuData>> childItemList = new ArrayList<List<MenuData>>(); - ; + List<MenuData> parentList = new ArrayList<MenuData>(); - ; + Map<String, Object> model = new HashMap<String, Object>(); for (MenuData menu : menuResult) { MenuData parentData = new MenuData(); @@ -99,8 +99,8 @@ public abstract class EPFusionBaseController extends FusionBaseController { } childItemList.add(tempList); } - model.put("childItemList", childItemList != null ? mapper.writeValueAsString(childItemList) : ""); - model.put("parentList", parentList != null ? mapper.writeValueAsString(parentList) : ""); + model.put("childItemList", mapper.writeValueAsString(childItemList)); + model.put("parentList", mapper.writeValueAsString(parentList)); return model; } } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAccessRolesController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAccessRolesController.java index fabf5e10..1e9c83e7 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAccessRolesController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAccessRolesController.java @@ -25,6 +25,7 @@ import org.openecomp.portalsdk.core.domain.AuditLog; import org.openecomp.portalsdk.core.domain.Role; import org.openecomp.portalsdk.core.domain.RoleFunction; import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.restful.domain.EcompUser; import org.openecomp.portalsdk.core.service.AuditService; import org.openecomp.portalsdk.core.util.SystemProperties; import org.slf4j.MDC; @@ -469,4 +470,18 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl return functionsList; } + + @ApiOperation(value = "Gets all active Users of application", response = String.class, responseContainer = "Json") + @RequestMapping(value = { "/users" }, method = RequestMethod.GET, produces = "application/json") + public List<EcompUser> getUsersOfApplication(HttpServletRequest request, HttpServletResponse response) throws Exception { + List<EcompUser> users = null; + try { + users = externalAccessRolesService.getAllAppUsers(request.getHeader(UEBKEY)); + } catch (Exception e) { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + logger.error(EELFLoggerDelegate.errorLogger, "getUsersOfApplication failed", e); + throw new Exception(e.getMessage()); + } + return users; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/FunctionalMenuController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/FunctionalMenuController.java index 490a1829..21a6e8ef 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/FunctionalMenuController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/FunctionalMenuController.java @@ -267,6 +267,7 @@ public class FunctionalMenuController extends EPRestrictedBaseController { @RequestMapping(value = { "/portalApi/functionalMenuForAuthUser" }, method = RequestMethod.GET, produces = "application/json") public List<FunctionalMenuItem> getMenuItemsForAuthUser(HttpServletRequest request, HttpServletResponse response) { + EPUser user = EPUserUtils.getUserSession(request); List<FunctionalMenuItem> menuItems = null; try { diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/PolicyController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/PolicyController.java new file mode 100644 index 00000000..5f691d2d --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/PolicyController.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.portalapp.portal.controller; + +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; + +import org.json.simple.JSONObject; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.scheduler.policy.PolicyProperties; +import org.openecomp.portalapp.portal.scheduler.policy.PolicyResponseWrapper; +import org.openecomp.portalapp.portal.scheduler.policy.PolicyRestInterfaceFactory; +import org.openecomp.portalapp.portal.scheduler.policy.PolicyRestInterfaceIfc; +import org.openecomp.portalapp.portal.scheduler.policy.PolicyUtil; +import org.openecomp.portalapp.portal.scheduler.policy.RestObject; +import org.openecomp.portalapp.portal.utils.PortalConstants; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +/*import org.openecomp.vid.policy.PolicyProperties; +import org.openecomp.vid.policy.PolicyResponseWrapper; +import org.openecomp.vid.policy.PolicyRestInterfaceFactory; +import org.openecomp.vid.policy.PolicyRestInterfaceIfc; +import org.openecomp.vid.policy.PolicyUtil;*/ +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + + + +/** + * Controller to handle Policy requests. + */ + +@RestController +@RequestMapping(PortalConstants.REST_AUX_API) +@Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class PolicyController implements BasicAuthenticationController{ + + /** The logger. */ + static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PolicyController.class); + + @RequestMapping(value="/get_policy",method = RequestMethod.POST) + public ResponseEntity<String> getPolicyInfo( HttpServletRequest request, @RequestBody JSONObject policy_request) throws Exception { + + logger.debug(EELFLoggerDelegate.debugLogger, "#####################POLICY API CALL STARTED ###############"+ PolicyProperties.POLICY_GET_CONFIG_VAL); + logger.debug(EELFLoggerDelegate.debugLogger, "#####################Policy Request ###############"+policy_request.toString()); + + String path = SystemProperties.getProperty(PolicyProperties.POLICY_GET_CONFIG_VAL); + PolicyResponseWrapper policyResWrapper = getPolicyConfig(policy_request,path); + + logger.debug(EELFLoggerDelegate.debugLogger, "$$$$$$$$$$$$$$$$$$$$$$ " + new ResponseEntity<String>(policyResWrapper.getResponse(), HttpStatus.OK).toString()); + + return ( new ResponseEntity<String>(policyResWrapper.getResponse(), HttpStatus.valueOf(policyResWrapper.getStatus())) ); + } + + protected static PolicyResponseWrapper getPolicyConfig(JSONObject request, String path) throws Exception { + String methodName = "getPolicyConfig"; + String uuid = UUID.randomUUID().toString(); + logger.debug(EELFLoggerDelegate.debugLogger, "starting getPolicyConfig "); + + try { + //STARTING REST API CALL AS AN FACTORY INSTACE + PolicyRestInterfaceIfc policyRestController = PolicyRestInterfaceFactory.getInstance(); + + RestObject<String> restObjStr = new RestObject<String>(); + String str = new String(); + restObjStr.set(str); + policyRestController.<String>Post(str, request, uuid, path, restObjStr ); + PolicyResponseWrapper policyRespWrapper = PolicyUtil.wrapResponse (restObjStr); + logger.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + " w=" + policyRespWrapper.getResponse()); + return policyRespWrapper; + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, "EXCEPTION in getPolicyConfig <== " + "." + methodName + e.toString()); + + throw e; + } + } +} + diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/SchedulerController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/SchedulerController.java new file mode 100644 index 00000000..54e95ae0 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/SchedulerController.java @@ -0,0 +1,248 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; + +import org.json.simple.JSONObject; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.scheduler.SchedulerProperties; +import org.openecomp.portalapp.portal.scheduler.SchedulerRestInterface; +import org.openecomp.portalapp.portal.scheduler.SchedulerUtil; +import org.openecomp.portalapp.portal.scheduler.restobjects.GetTimeSlotsRestObject; +import org.openecomp.portalapp.portal.scheduler.restobjects.PostCreateNewVnfRestObject; +import org.openecomp.portalapp.portal.scheduler.restobjects.PostSubmitVnfChangeRestObject; +import org.openecomp.portalapp.portal.scheduler.wrapper.GetTimeSlotsWrapper; +import org.openecomp.portalapp.portal.scheduler.wrapper.PostCreateNewVnfWrapper; +import org.openecomp.portalapp.portal.scheduler.wrapper.PostSubmitVnfChangeTimeSlotsWrapper; +import org.openecomp.portalapp.portal.utils.PortalConstants; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(PortalConstants.REST_AUX_API) +@Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class SchedulerController implements BasicAuthenticationController { + + @Autowired + private SchedulerRestInterface schedulerRestController; + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerController.class); + + /** The request date format. */ + public DateFormat requestDateFormat = new SimpleDateFormat("EEE, dd MMM YYYY HH:mm:ss z"); + + @RequestMapping(value = "/get_time_slots/{scheduler_request}", method = RequestMethod.GET) + public ResponseEntity<String> getTimeSlots(HttpServletRequest request, + @PathVariable("scheduler_request") String scheduler_request) throws Exception { + + Date startingTime = new Date(); + String startTimeRequest = requestDateFormat.format(startingTime); + + System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); + System.out.println(startTimeRequest + " | Controller Scheduler GET : /get_time_slots/{scheduler_request} \n"); + System.out.println("Original Request : \n " + scheduler_request + '\n'); + + String path = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_GET_TIME_SLOTS) + scheduler_request; + + GetTimeSlotsWrapper schedulerResWrapper = getTimeSlots(scheduler_request, path, scheduler_request); + + Date endTime = new Date(); + String endTimeRequest = requestDateFormat.format(endTime); + System.out.println(endTimeRequest + " | Controller Scheduler - GET\n"); + + return (new ResponseEntity<String>(schedulerResWrapper.getResponse(), HttpStatus.OK)); + + } + + protected GetTimeSlotsWrapper getTimeSlots(String request, String path, String uuid) throws Exception { + + try { + // STARTING REST API CALL AS AN FACTORY INSTACE + System.out.println("<== Get Time Slots Request START \n"); + + GetTimeSlotsRestObject<String> restObjStr = new GetTimeSlotsRestObject<String>(); + String str = new String(); + + restObjStr.set(str); + + schedulerRestController.Get(str, uuid, path, restObjStr); + GetTimeSlotsWrapper schedulerRespWrapper = SchedulerUtil.getTimeSlotsWrapResponse(restObjStr); + + System.out.println( + "<== Get Time Slots Request END : Response = " + schedulerRespWrapper.getResponse() + '\n'); + + return schedulerRespWrapper; + + } catch (Exception e) { + System.out.println("<== Get Time Slots Request ERROR : " + e.toString() + '\n'); + logger.error(EELFLoggerDelegate.errorLogger, "Get Time Slots Request failed", e); + throw e; + } + } + + @SuppressWarnings("unchecked") + @RequestMapping(value = "/post_create_new_vnf_change", method = RequestMethod.POST) + public ResponseEntity<String> postCreateNewVNFChange(HttpServletRequest request, + @RequestBody JSONObject scheduler_request) throws Exception { + + Date startingTime = new Date(); + String startTimeRequest = requestDateFormat.format(startingTime); + + System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); + System.out.println(startTimeRequest + " | Controller Scheduler POST : post_create_new_vnf_change \n"); + + // Generating uuid + String uuid = UUID.randomUUID().toString(); + + scheduler_request.put("scheduleId", uuid); + System.out.println("<== UUID : " + uuid + '\n'); + + // adding uuid to the request payload + scheduler_request.put("scheduleId", uuid); + + System.out.println("<== UUID : " + uuid + '\n'); + System.out.println("Original Request : \n " + scheduler_request.toString() + '\n'); + + String path = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_CREATE_NEW_VNF_CHANGE_INSTANCE_VAL) + + uuid; + + PostCreateNewVnfWrapper responseWrapper = postSchedulingRequest(scheduler_request, path, uuid); + + Date endTime = new Date(); + String endTimeRequest = requestDateFormat.format(endTime); + System.out.println(endTimeRequest + " | Controller Scheduler - POST\n"); + + return (new ResponseEntity<String>(responseWrapper.getResponse(), HttpStatus.OK)); + } + + protected PostCreateNewVnfWrapper postSchedulingRequest(JSONObject request, String path, String uuid) + throws Exception { + + try { + // STARTING REST API CALL AS AN FACTORY INSTACE + System.out.println("<== Post Create New Vnf Scheduling Request START \n"); + + PostCreateNewVnfRestObject<String> restObjStr = new PostCreateNewVnfRestObject<String>(); + String str = new String(); + + restObjStr.set(str); + schedulerRestController.<String>Post(str, request, path, restObjStr); + + int status = restObjStr.getStatusCode(); + if (status >= 200 && status <= 299) { + restObjStr.setUUID(uuid); + } + + PostCreateNewVnfWrapper responseWrapper = SchedulerUtil.postCreateNewVnfWrapResponse(restObjStr); + + System.out.println("<== Post Create New Vnf Scheduling Request END : Response = " + + responseWrapper.getResponse() + '\n'); + + return responseWrapper; + + } catch (Exception e) { + System.out.println("<== Post Create New Vnf Scheduling Request ERROR : " + e.toString() + '\n'); + logger.error(EELFLoggerDelegate.errorLogger, "Post Create New Vnf Scheduling Request failed", e); + throw e; + } + } + + @RequestMapping(value = "/submit_vnf_change_timeslots", method = RequestMethod.POST) + public ResponseEntity<String> postSubmitVnfChangeTimeslots(HttpServletRequest request, + @RequestBody JSONObject scheduler_request) throws Exception { + + Date startingTime = new Date(); + String startTimeRequest = requestDateFormat.format(startingTime); + + System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); + System.out.println(startTimeRequest + " | Controller Scheduler POST : submit_vnf_change_timeslots \n"); + + // Generating uuid + String uuid = (String) scheduler_request.get("scheduleId"); + scheduler_request.remove("scheduleId"); + + System.out.println("<== UUID : " + uuid + '\n'); + System.out.println("Original Request : \n " + scheduler_request.toString() + '\n'); + + String path = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SUBMIT_NEW_VNF_CHANGE) + .replace("{scheduleId}", uuid); + + PostSubmitVnfChangeTimeSlotsWrapper responseWrapper = postSubmitSchedulingRequest(scheduler_request, path, + uuid); + + Date endTime = new Date(); + String endTimeRequest = requestDateFormat.format(endTime); + System.out.println(endTimeRequest + " | Controller Scheduler - POST Submit\n"); + + return (new ResponseEntity<String>(responseWrapper.getResponse(), HttpStatus.OK)); + } + + protected PostSubmitVnfChangeTimeSlotsWrapper postSubmitSchedulingRequest(JSONObject request, String path, + String uuid) throws Exception { + + try { + // STARTING REST API CALL AS AN FACTORY INSTACE + System.out.println("<== Post Submit Scheduling Request START \n"); + + PostSubmitVnfChangeRestObject<String> restObjStr = new PostSubmitVnfChangeRestObject<String>(); + String str = new String(); + + restObjStr.set(str); + schedulerRestController.<String>Post(str, request, path, restObjStr); + + int status = restObjStr.getStatusCode(); + if (status >= 200 && status <= 299) { + restObjStr.setUUID(uuid); + } + + PostSubmitVnfChangeTimeSlotsWrapper responseWrapper = SchedulerUtil + .postSubmitNewVnfWrapResponse(restObjStr); + + System.out.println( + "<== Post Submit Scheduling Request END : Response = " + responseWrapper.getResponse() + '\n'); + + return responseWrapper; + + } catch (Exception e) { + System.out.println("<== Post Submit Scheduling Request ERROR : " + e.toString() + '\n'); + logger.error(EELFLoggerDelegate.errorLogger, "Post Submit Scheduling Request failed", e); + throw e; + } + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java index 222f4502..7a5196ca 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java @@ -33,13 +33,12 @@ import org.openecomp.portalapp.portal.domain.EPUser; import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.TicketEventService; import org.openecomp.portalapp.portal.service.UserNotificationService; import org.openecomp.portalapp.portal.transport.EpNotificationItem; import org.openecomp.portalapp.portal.transport.EpRoleNotificationItem; -import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; import org.openecomp.portalapp.portal.utils.PortalConstants; import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @@ -67,6 +66,9 @@ public class TicketEventController implements BasicAuthenticationController { @Autowired private UserNotificationService userNotificationService; + + @Autowired + private TicketEventService ticketEventService; private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(TicketEventController.class); @@ -106,6 +108,7 @@ public class TicketEventController implements BasicAuthenticationController { JsonNode event = ticketEventNotif.get("event"); JsonNode header = event.get("header"); JsonNode body = event.get("body"); + JsonNode application = ticketEventNotif.get("application"); epItem.setMsgDescription(body.toString()); Long eventDate = System.currentTimeMillis(); if (body.get("eventDate") != null) { @@ -114,7 +117,7 @@ public class TicketEventController implements BasicAuthenticationController { String eventSource = header.get("eventSource").asText(); epItem.setMsgSource(eventSource); String ticket = body.get("ticketNum").asText(); - String hyperlink = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_SYSTEM_NOTIFICATION_URL)+eventSource+"num="+ticket; + String hyperlink = ticketEventService.getNotificationHyperLink(application, ticket, eventSource); if(body.get("notificationHyperlink")!=null){ hyperlink=body.get("notificationHyperlink").asText(); } @@ -201,7 +204,7 @@ public class TicketEventController implements BasicAuthenticationController { .split(","); List<EPUser> users = userNotificationService.getUsersByOrgIds(Arrays.asList(UserIds)); if(users==null||users.size()==0) - return "Invalid Attuid"; + return "Invalid Org User ID"; return null; } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java index 4bb447d1..c5cd5c90 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/UserRolesController.java @@ -153,17 +153,22 @@ public class UserRolesController extends EPRestrictedBaseController { } StringBuilder adminAppRoles = new StringBuilder(); - if (result != null && result.appsRoles.size() >= 1) { - adminAppRoles.append("User '" + result.orgUserId + "' has admin role to the apps = {"); - for (AppNameIdIsAdmin adminAppRole : result.appsRoles) { - if (adminAppRole.isAdmin) { - adminAppRoles.append(adminAppRole.appName + ", "); + if(result != null){ + if ( result.appsRoles.size() >= 1) { + adminAppRoles.append("User '" + result.orgUserId + "' has admin role to the apps = {"); + for (AppNameIdIsAdmin adminAppRole : result.appsRoles) { + if (adminAppRole.isAdmin) { + adminAppRoles.append(adminAppRole.appName + ", "); + } } + adminAppRoles.append("}."); + } else { + adminAppRoles.append("User '" + result.orgUserId + "' has no Apps with Admin Role."); } - 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); @@ -189,18 +194,23 @@ public class UserRolesController extends EPRestrictedBaseController { // newAppsListWithAdminRoles.appsRoles FieldsValidator fieldsValidator = new FieldsValidator(); StringBuilder newAppRoles = new StringBuilder(); - if (newAppsListWithAdminRoles != null && newAppsListWithAdminRoles.appsRoles.size() >= 1) { - newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has admin role to the apps = { "); - for (AppNameIdIsAdmin adminAppRole : newAppsListWithAdminRoles.appsRoles) { - if (adminAppRole.isAdmin) { - newAppRoles.append(adminAppRole.appName + " ,"); + if(newAppsListWithAdminRoles != null ){ + if (newAppsListWithAdminRoles.appsRoles.size() >= 1) { + newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has admin role to the apps = { "); + for (AppNameIdIsAdmin adminAppRole : newAppsListWithAdminRoles.appsRoles) { + if (adminAppRole.isAdmin) { + newAppRoles.append(adminAppRole.appName + " ,"); + } } + newAppRoles.deleteCharAt(newAppRoles.length() - 1); + newAppRoles.append("}."); + } else { + newAppRoles.append("User '" + newAppsListWithAdminRoles.orgUserId + "' has no Apps with Admin Role."); } - 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"); } + logger.info(EELFLoggerDelegate.errorLogger, newAppRoles.toString()); EPUser user = EPUserUtils.getUserSession(request); @@ -339,7 +349,9 @@ public class UserRolesController extends EPRestrictedBaseController { boolean changesApplied = false; if (!adminRolesService.isAccountAdmin(user)) { EcompPortalUtils.setBadPermissions(user, response, "putAppWithUserRoleStateForUser"); - } else { + } else if(newAppRolesForUser==null){ + logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleStateForUser: newAppRolesForUser is null"); + } else{ changesApplied = userRolesService.setAppWithUserRoleStateForUser(user, newAppRolesForUser); if (changesApplied) { logger.info(EELFLoggerDelegate.applicationLogger, diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WebAnalyticsExtAppController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WebAnalyticsExtAppController.java index 662de30a..44a5dcdf 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WebAnalyticsExtAppController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/WebAnalyticsExtAppController.java @@ -178,7 +178,7 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP), MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)); logger.info(EELFLoggerDelegate.auditLogger, - EPLogUtil.formatStoreAnalyticsAuditLogMessage(analyticsMap.getUserId(), appName, + EPLogUtil.formatStoreAnalyticsAuditLogMessage(analyticsMap.getUserid(), appName, "WebAnalyticsExtAppController.postWebAnalyticsData", EcompAuditLog.CD_ACTIVITY_STORE_ANALYTICS, analyticsMap.getAction(), analyticsMap.getPage(), analyticsMap.getFunction(), analyticsMap.getType())); @@ -214,10 +214,10 @@ public class WebAnalyticsExtAppController extends EPRestrictedRESTfulBaseControl protected void storeAuxAnalytics(Analytics analyticsMap, String appName) { logger.info(EELFLoggerDelegate.debugLogger, " Registering an action for recommendation: AppName/Function/UserId " + appName + "/" - + analyticsMap.getFunction() + "/" + analyticsMap.getUserId()); + + analyticsMap.getFunction() + "/" + analyticsMap.getUserid()); Map<String, String> requestMapping = new HashMap<String, String>(); - requestMapping.put("id", analyticsMap.getUserId()); + requestMapping.put("id", analyticsMap.getUserid()); requestMapping.put("action", appName + "|" + analyticsMap.getFunction()); HttpHeaders headers = new HttpHeaders(); diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPApp.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPApp.java index edb3c905..ad9dec56 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPApp.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPApp.java @@ -19,6 +19,8 @@ */ package org.openecomp.portalapp.portal.domain; +import java.util.Arrays; + import javax.persistence.Lob; import org.apache.commons.lang.StringUtils; @@ -94,6 +96,8 @@ public class EPApp extends DomainVo { this.imageUrl = imageUrl; } + + public byte[] getThumbnail() { return this.thumbnail; } @@ -312,4 +316,151 @@ public class EPApp extends DomainVo { return str; } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((alternateUrl == null) ? 0 : alternateUrl.hashCode()); + result = prime * result + ((appPassword == null) ? 0 : appPassword.hashCode()); + result = prime * result + ((appRestEndpoint == null) ? 0 : appRestEndpoint.hashCode()); + result = prime * result + ((appType == null) ? 0 : appType.hashCode()); + result = prime * result + ((centralAuth == null) ? 0 : centralAuth.hashCode()); + result = prime * result + ((contactUs == null) ? 0 : contactUs.hashCode()); + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((enabled == null) ? 0 : enabled.hashCode()); + result = prime * result + ((imageUrl == null) ? 0 : imageUrl.hashCode()); + result = prime * result + ((mlAppAdminId == null) ? 0 : mlAppAdminId.hashCode()); + result = prime * result + ((mlAppName == null) ? 0 : mlAppName.hashCode()); + result = prime * result + ((motsId == null) ? 0 : motsId.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((nameSpace == null) ? 0 : nameSpace.hashCode()); + result = prime * result + ((notes == null) ? 0 : notes.hashCode()); + result = prime * result + ((open == null) ? 0 : open.hashCode()); + result = prime * result + Arrays.hashCode(thumbnail); + result = prime * result + ((uebKey == null) ? 0 : uebKey.hashCode()); + result = prime * result + ((uebSecret == null) ? 0 : uebSecret.hashCode()); + result = prime * result + ((uebTopicName == null) ? 0 : uebTopicName.hashCode()); + result = prime * result + ((url == null) ? 0 : url.hashCode()); + result = prime * result + ((username == null) ? 0 : username.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + EPApp other = (EPApp) obj; + if (alternateUrl == null) { + if (other.alternateUrl != null) + return false; + } else if (!alternateUrl.equals(other.alternateUrl)) + return false; + if (appPassword == null) { + if (other.appPassword != null) + return false; + } else if (!appPassword.equals(other.appPassword)) + return false; + if (appRestEndpoint == null) { + if (other.appRestEndpoint != null) + return false; + } else if (!appRestEndpoint.equals(other.appRestEndpoint)) + return false; + if (appType == null) { + if (other.appType != null) + return false; + } else if (!appType.equals(other.appType)) + return false; + if (centralAuth == null) { + if (other.centralAuth != null) + return false; + } else if (!centralAuth.equals(other.centralAuth)) + return false; + if (contactUs == null) { + if (other.contactUs != null) + return false; + } else if (!contactUs.equals(other.contactUs)) + return false; + if (description == null) { + if (other.description != null) + return false; + } else if (!description.equals(other.description)) + return false; + if (enabled == null) { + if (other.enabled != null) + return false; + } else if (!enabled.equals(other.enabled)) + return false; + if (imageUrl == null) { + if (other.imageUrl != null) + return false; + } else if (!imageUrl.equals(other.imageUrl)) + return false; + if (mlAppAdminId == null) { + if (other.mlAppAdminId != null) + return false; + } else if (!mlAppAdminId.equals(other.mlAppAdminId)) + return false; + if (mlAppName == null) { + if (other.mlAppName != null) + return false; + } else if (!mlAppName.equals(other.mlAppName)) + return false; + if (motsId == null) { + if (other.motsId != null) + return false; + } else if (!motsId.equals(other.motsId)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (nameSpace == null) { + if (other.nameSpace != null) + return false; + } else if (!nameSpace.equals(other.nameSpace)) + return false; + if (notes == null) { + if (other.notes != null) + return false; + } else if (!notes.equals(other.notes)) + return false; + if (open == null) { + if (other.open != null) + return false; + } else if (!open.equals(other.open)) + return false; + if (!Arrays.equals(thumbnail, other.thumbnail)) + return false; + if (uebKey == null) { + if (other.uebKey != null) + return false; + } else if (!uebKey.equals(other.uebKey)) + return false; + if (uebSecret == null) { + if (other.uebSecret != null) + return false; + } else if (!uebSecret.equals(other.uebSecret)) + return false; + if (uebTopicName == null) { + if (other.uebTopicName != null) + return false; + } else if (!uebTopicName.equals(other.uebTopicName)) + return false; + if (url == null) { + if (other.url != null) + return false; + } else if (!url.equals(other.url)) + return false; + if (username == null) { + if (other.username != null) + return false; + } else if (!username.equals(other.username)) + return false; + return true; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPRole.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPRole.java index a1e44575..90990ef4 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPRole.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPRole.java @@ -199,4 +199,5 @@ public class EPRole extends DomainVo { public String toString() { return "[Id = " + id + ", name = " + name + "]"; } + } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesRequest.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesRequest.java index c756ef58..616246d8 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesRequest.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesRequest.java @@ -82,4 +82,59 @@ public class EPUserAppRolesRequest extends DomainVo { public void setEpRequestIdDetail(Set<EPUserAppRolesRequestDetail> epMyLoginsDetail) { this.epRequestIdDetail = epMyLoginsDetail; } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((appId == null) ? 0 : appId.hashCode()); + result = prime * result + ((createdDate == null) ? 0 : createdDate.hashCode()); + result = prime * result + ((epRequestIdDetail == null) ? 0 : epRequestIdDetail.hashCode()); + result = prime * result + ((requestStatus == null) ? 0 : requestStatus.hashCode()); + result = prime * result + ((updatedDate == null) ? 0 : updatedDate.hashCode()); + result = prime * result + ((userId == null) ? 0 : userId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + EPUserAppRolesRequest other = (EPUserAppRolesRequest) obj; + if (appId == null) { + if (other.appId != null) + return false; + } else if (!appId.equals(other.appId)) + return false; + if (createdDate == null) { + if (other.createdDate != null) + return false; + } else if (!createdDate.equals(other.createdDate)) + return false; + if (epRequestIdDetail == null) { + if (other.epRequestIdDetail != null) + return false; + } else if (!epRequestIdDetail.equals(other.epRequestIdDetail)) + return false; + if (requestStatus == null) { + if (other.requestStatus != null) + return false; + } else if (!requestStatus.equals(other.requestStatus)) + return false; + if (updatedDate == null) { + if (other.updatedDate != null) + return false; + } else if (!updatedDate.equals(other.updatedDate)) + return false; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + return true; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesRequestDetail.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesRequestDetail.java index 3b466f52..eeb34451 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesRequestDetail.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesRequestDetail.java @@ -53,4 +53,41 @@ public class EPUserAppRolesRequestDetail extends DomainVo { this.reqType = reqType; } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((epRequestIdData == null) ? 0 : epRequestIdData.hashCode()); + result = prime * result + ((reqRoleId == null) ? 0 : reqRoleId.hashCode()); + result = prime * result + ((reqType == null) ? 0 : reqType.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + EPUserAppRolesRequestDetail other = (EPUserAppRolesRequestDetail) obj; + if (epRequestIdData == null) { + if (other.epRequestIdData != null) + return false; + } else if (!epRequestIdData.equals(other.epRequestIdData)) + return false; + if (reqRoleId == null) { + if (other.reqRoleId != null) + return false; + } else if (!reqRoleId.equals(other.reqRoleId)) + return false; + if (reqType == null) { + if (other.reqType != null) + return false; + } else if (!reqType.equals(other.reqType)) + return false; + return true; + } + } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/MicroserviceParameter.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/MicroserviceParameter.java index 0796a5a9..80c48fcc 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/MicroserviceParameter.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/MicroserviceParameter.java @@ -19,10 +19,6 @@ */ package org.openecomp.portalapp.portal.domain; -import javax.persistence.Column; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; import org.openecomp.portalsdk.core.domain.support.DomainVo; public class MicroserviceParameter extends DomainVo { diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/PersUserAppSelection.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/PersUserAppSelection.java index 331cdb81..81a5942e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/PersUserAppSelection.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/PersUserAppSelection.java @@ -75,4 +75,41 @@ public class PersUserAppSelection extends DomainVo { this.statusCode = statusCode; } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((appId == null) ? 0 : appId.hashCode()); + result = prime * result + ((statusCode == null) ? 0 : statusCode.hashCode()); + result = prime * result + ((userId == null) ? 0 : userId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + PersUserAppSelection other = (PersUserAppSelection) obj; + if (appId == null) { + if (other.appId != null) + return false; + } else if (!appId.equals(other.appId)) + return false; + if (statusCode == null) { + if (other.statusCode != null) + return false; + } else if (!statusCode.equals(other.statusCode)) + return false; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + return true; + } + } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/PersUserWidgetSelection.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/PersUserWidgetSelection.java index 692479b4..5ef8a21b 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/PersUserWidgetSelection.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/PersUserWidgetSelection.java @@ -77,5 +77,42 @@ public class PersUserWidgetSelection extends DomainVo { public void setStatusCode(String statusCode) { this.statusCode = statusCode; } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((statusCode == null) ? 0 : statusCode.hashCode()); + result = prime * result + ((userId == null) ? 0 : userId.hashCode()); + result = prime * result + ((widgetId == null) ? 0 : widgetId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + PersUserWidgetSelection other = (PersUserWidgetSelection) obj; + if (statusCode == null) { + if (other.statusCode != null) + return false; + } else if (!statusCode.equals(other.statusCode)) + return false; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + if (widgetId == null) { + if (other.widgetId != null) + return false; + } else if (!widgetId.equals(other.widgetId)) + return false; + return true; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/listener/HealthMonitor.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/listener/HealthMonitor.java index f9a6b905..27c43160 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/listener/HealthMonitor.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/listener/HealthMonitor.java @@ -218,9 +218,8 @@ public class HealthMonitor { } } }; - if (healthMonitorThread != null) { - healthMonitorThread.start(); - } + healthMonitorThread.start(); + } @PreDestroy diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/RestObject.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/RestObject.java new file mode 100644 index 00000000..a1030e3a --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/RestObject.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.portalapp.portal.scheduler; + + +public class RestObject<T> { + + private T t; + + private int statusCode= 0; + + public String uuid; + + public void set(T t) { this.t = t; } + + public T get() { return t; } + + public void setStatusCode(int v) { this.statusCode = v; } + + public int getStatusCode() { return this.statusCode; } + + public void setUUID(String uuid) { this.uuid = uuid; } + + public String getUUID() { return this.uuid; } +} + diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerProperties.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerProperties.java new file mode 100644 index 00000000..2d65b6c3 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerProperties.java @@ -0,0 +1,20 @@ +package org.openecomp.portalapp.portal.scheduler; + +import org.openecomp.portalsdk.core.util.SystemProperties; + + +public class SchedulerProperties extends SystemProperties { + + public static final String SCHEDULER_USER_NAME_VAL = "scheduler.user.name";; + + public static final String SCHEDULER_PASSWORD_VAL = "scheduler.password"; + + public static final String SCHEDULER_SERVER_URL_VAL = "scheduler.server.url"; + + public static final String SCHEDULER_CREATE_NEW_VNF_CHANGE_INSTANCE_VAL = "scheduler.create.new.vnf.change.instance"; + + public static final String SCHEDULER_GET_TIME_SLOTS = "scheduler.get.time.slots"; + + public static final String SCHEDULER_SUBMIT_NEW_VNF_CHANGE = "scheduler.submit.new.vnf.change"; + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerResponseWrapper.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerResponseWrapper.java new file mode 100644 index 00000000..d30f0568 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerResponseWrapper.java @@ -0,0 +1,71 @@ +package org.openecomp.portalapp.portal.scheduler; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +/** + * This wrapper encapsulates the Scheduler response + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "status", + "entity", + "uuid" +}) + +public class SchedulerResponseWrapper { + + @JsonProperty("status") + private int status; + + @JsonProperty("entity") + private String entity; + + @JsonProperty("uuid") + private String uuid; + + @JsonProperty("entity") + public String getEntity() { + return entity; + } + + @JsonProperty("status") + public int getStatus() { + return status; + } + + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + + @JsonProperty("status") + public void setStatus(int v) { + this.status = v; + } + + @JsonProperty("entity") + public void setEntity(String v) { + this.entity = v; + } + + @JsonProperty("uuid") + public void setUuid(String v) { + this.uuid = v; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + public String getResponse () { + + StringBuilder b = new StringBuilder ("{ \"status\": "); + b.append(getStatus()).append(", \"entity\": \" " ).append(this.getEntity()).append("\" ,\"uuid\": \"" ).append(this.getUuid()).append("\"}"); + return (b.toString()); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerRestInt.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerRestInt.java new file mode 100644 index 00000000..d532fd79 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerRestInt.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.portalapp.portal.scheduler; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class SchedulerRestInt { + + /** The logger. */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class); + + /** The Constant dateFormat. */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + /** The request date format. */ + public DateFormat requestDateFormat = new SimpleDateFormat("EEE, dd MMM YYYY HH:mm:ss z"); + + public SchedulerRestInt() { + requestDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT")); + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerRestInterface.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerRestInterface.java new file mode 100644 index 00000000..337c1fcf --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerRestInterface.java @@ -0,0 +1,200 @@ +package org.openecomp.portalapp.portal.scheduler; + +import java.util.Collections; + +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 org.apache.commons.codec.binary.Base64; +import org.json.simple.JSONObject; +import org.openecomp.portalapp.portal.scheduler.client.HttpBasicClient; +import org.openecomp.portalapp.portal.scheduler.client.HttpsBasicClient; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.stereotype.Service; +import org.openecomp.portalapp.portal.scheduler.restobjects.RestObject; + + +@Service +public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { + + private static Client client = null; + + private MultivaluedHashMap<String, Object> commonHeaders; + + public SchedulerRestInterface() { + super(); + } + + public void initRestClient() + { + final String methodname = "initRestClient()"; + + final String username = "";//SystemProperties.getProperty(SchedulerProperties.SCHEDULER_USER_NAME_VAL); + //final String password = "";//SystemProperties.getProperty(SchedulerProperties.SCHEDULER_PASSWORD_VAL); + final String scheduler_url = "";//SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL); + final String decrypted_password = "";//Password.deobfuscate(password); + + String authString = username + ":" + decrypted_password; + + byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); + String authStringEnc = new String(authEncBytes); + + commonHeaders = new MultivaluedHashMap<String, Object> (); + commonHeaders.put("Authorization", Collections.singletonList((Object) ("Basic " + authStringEnc))); + + boolean use_ssl = true; + if ( (scheduler_url != null) && ( !(scheduler_url.isEmpty()) ) ) { + if ( scheduler_url.startsWith("https")) { + use_ssl = true; + } + else { + use_ssl = false; + } + } + if (client == null) { + + try { + if ( use_ssl ) { + + client = HttpsBasicClient.getClient(); + } + else { + + client = HttpBasicClient.getClient(); + } + } catch (Exception e) { + System.out.println( methodname + " Unable to get the SSL client"); + } + } + } + + @SuppressWarnings("unchecked") + public <T> void Get (T t, String sourceId, String path, org.openecomp.portalapp.portal.scheduler.restobjects.RestObject<T> restObject ) throws Exception { + + String methodName = "Get"; + String url = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path; + + + System.out.println( "<== URL FOR GET : " + url + "\n"); + + initRestClient(); + + final Response cres = client.target(url) + .request() + .accept("application/json") + .headers(commonHeaders) + .get(); + + int status = cres.getStatus(); + restObject.setStatusCode (status); + + if (status == 200) { + t = (T) cres.readEntity(t.getClass()); + restObject.set(t); + + } else { + throw new Exception(methodName + " with status="+ status + ", url= " + url ); + } + + return; + } + + @SuppressWarnings("unchecked") + public <T> void Post(T t, JSONObject requestDetails, String path, RestObject<T> restObject) throws Exception { + + String methodName = "Post"; + String url = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path; + + System.out.println( "<== URL FOR POST : " + url + "\n"); + + try { + + initRestClient(); + + // Change the content length + final Response cres = client.target(url) + .request() + .accept("application/json") + .headers(commonHeaders) + //.header("content-length", 201) + //.header("X-FromAppId", sourceID) + .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON)); + + try { + t = (T) cres.readEntity(t.getClass()); + restObject.set(t); + } + catch ( Exception e ) { + + System.out.println("<== " + methodName + " : No response entity, this is probably ok, e=" + e.getMessage()); + } + + int status = cres.getStatus(); + restObject.setStatusCode (status); + + if ( status >= 200 && status <= 299 ) { + + System.out.println( "<== " + methodName + " : REST api POST was successful!" + "\n"); + + } else { + System.out.println( "<== " + methodName + " : FAILED with http status : "+status+", url = " + url + "\n"); + } + + } catch (Exception e) + { + System.out.println( "<== " + methodName + " : with url="+url+ ", Exception: " + e.toString() + "\n"); + throw e; + } + } + + @SuppressWarnings("unchecked") + public <T> void Delete(T t, JSONObject requestDetails, String sourceID, String path, RestObject<T> restObject) { + + String url=""; + Response cres = null; + + try { + initRestClient(); + + url = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path; + + 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); + + try { + t = (T) cres.readEntity(t.getClass()); + restObject.set(t); + } + catch ( Exception e ) { + } + + } + catch (Exception e) + { + throw e; + } + } + + public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException + { + return clazz.newInstance(); + } + + @Override + public void logRequest(JSONObject requestDetails) { + // TODO Auto-generated method stub + + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerRestInterfaceFactory.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerRestInterfaceFactory.java new file mode 100644 index 00000000..34433e5a --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerRestInterfaceFactory.java @@ -0,0 +1,15 @@ + +package org.openecomp.portalapp.portal.scheduler; + +public class SchedulerRestInterfaceFactory { + + + public static SchedulerRestInterfaceIfc getInstance () { + SchedulerRestInterfaceIfc obj = null; + + obj = new SchedulerRestInterface(); + + return ( obj ); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerRestInterfaceIfc.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerRestInterfaceIfc.java new file mode 100644 index 00000000..77353e5e --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerRestInterfaceIfc.java @@ -0,0 +1,22 @@ + +package org.openecomp.portalapp.portal.scheduler; + +import org.json.simple.JSONObject; +import org.springframework.stereotype.Service; +import org.openecomp.portalapp.portal.scheduler.restobjects.RestObject; + + +@Service +public interface SchedulerRestInterfaceIfc { + + public void initRestClient(); + + public <T> void Get(T t, String sourceId, String path, org.openecomp.portalapp.portal.scheduler.restobjects.RestObject<T> restObject ) throws Exception; + + public <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; + + public void logRequest(JSONObject requestDetails); +}
\ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerUtil.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerUtil.java new file mode 100644 index 00000000..37dddc29 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/SchedulerUtil.java @@ -0,0 +1,99 @@ +package org.openecomp.portalapp.portal.scheduler; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.openecomp.portalapp.portal.scheduler.restobjects.GetTimeSlotsRestObject; +import org.openecomp.portalapp.portal.scheduler.restobjects.PostCreateNewVnfRestObject; +import org.openecomp.portalapp.portal.scheduler.restobjects.PostSubmitVnfChangeRestObject; +import org.openecomp.portalapp.portal.scheduler.wrapper.GetTimeSlotsWrapper; +import org.openecomp.portalapp.portal.scheduler.wrapper.PostCreateNewVnfWrapper; +import org.openecomp.portalapp.portal.scheduler.wrapper.PostSubmitVnfChangeTimeSlotsWrapper; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class SchedulerUtil { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerUtil.class); + + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + public static GetTimeSlotsWrapper getTimeSlotsWrapResponse (GetTimeSlotsRestObject<String> rs) { + + String resp_str = ""; + int status = 0; + + if ( rs != null ) { + resp_str = rs.get(); + status = rs.getStatusCode(); + } + + GetTimeSlotsWrapper w = new GetTimeSlotsWrapper(); + + w.setEntity(resp_str); + w.setStatus (status); + + return (w); + } + + public static PostSubmitVnfChangeTimeSlotsWrapper postSubmitNewVnfWrapResponse (PostSubmitVnfChangeRestObject<String> rs) { + + String resp_str = ""; + int status = 0; + String uuid = ""; + + if ( rs != null ) { + resp_str = rs.get(); + status = rs.getStatusCode(); + uuid = rs.getUUID(); + } + + PostSubmitVnfChangeTimeSlotsWrapper w = new PostSubmitVnfChangeTimeSlotsWrapper(); + + w.setEntity(resp_str); + w.setStatus (status); + w.setUuid(uuid); + + return (w); + } + + public static PostCreateNewVnfWrapper postCreateNewVnfWrapResponse (PostCreateNewVnfRestObject<String> rs) { + + String resp_str = ""; + int status = 0; + String uuid = ""; + + if ( rs != null ) { + resp_str = rs.get(); + status = rs.getStatusCode(); + uuid = rs.getUUID(); + } + + PostCreateNewVnfWrapper w = new PostCreateNewVnfWrapper(); + + w.setEntity(resp_str); + w.setStatus (status); + w.setUuid(uuid); + + return (w); + } + + public static <T> String convertPojoToString ( T t ) throws com.fasterxml.jackson.core.JsonProcessingException { + + String methodName = "convertPojoToString"; + ObjectMapper mapper = new ObjectMapper(); + String r_json_str = ""; + if ( t != null ) { + try { + r_json_str = mapper.writeValueAsString(t); + } + catch ( com.fasterxml.jackson.core.JsonProcessingException j ) { + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Unable to parse object as json"); + } + } + return (r_json_str); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/client/HttpBasicClient.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/client/HttpBasicClient.java new file mode 100644 index 00000000..f0ec2769 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/client/HttpBasicClient.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.portalapp.portal.scheduler.client; + + +import java.text.DateFormat; +import java.text.SimpleDateFormat; + +import javax.servlet.ServletContext; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; + +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; +import org.openecomp.portalapp.portal.scheduler.util.CustomJacksonJaxBJsonProvider; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; + +/** + * General HTTP client. + */ + +public class HttpBasicClient{ + + /** The servlet context. */ + @Autowired + private ServletContext servletContext; + + /** The logger. */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HttpBasicClient.class); + + /** The Constant dateFormat. */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + /** + * Obtain a basic HTTP client . + * + * @return Client client object + * @throws Exception the exception + */ + public static Client getClient() throws Exception { + + ClientConfig config = new ClientConfig(); + config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true); + + return ClientBuilder.newClient(config) + .register(CustomJacksonJaxBJsonProvider.class); + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/client/HttpsBasicClient.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/client/HttpsBasicClient.java new file mode 100644 index 00000000..be244865 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/client/HttpsBasicClient.java @@ -0,0 +1,144 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.portalapp.portal.scheduler.client; + +import java.io.File; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; + +import org.eclipse.jetty.util.security.Password; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; +import org.openecomp.portalapp.portal.scheduler.properties.VidProperties; +import org.openecomp.portalapp.portal.scheduler.util.CustomJacksonJaxBJsonProvider; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; + + /** + * General SSL client using the VID tomcat keystore. It doesn't use client certificates. + */ + +public class HttpsBasicClient{ + + /** The logger. */ + static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HttpsBasicClient.class); + + /** The Constant dateFormat. */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + /** + * Retrieve an SSL client. + * + * @return Client The SSL client + * @throws Exception the exception + */ + public static Client getClient() throws Exception { + String methodName = "getClient"; + ClientConfig config = new ClientConfig(); + //config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); + //config.getClasses().add(org.openecomp.aai.util.CustomJacksonJaxBJsonProvider.class); + + SSLContext ctx = null; + + try { + + config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true); + + String truststore_path = SystemProperties.getProperty(VidProperties.VID_TRUSTSTORE_FILENAME); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + " " + methodName + " truststore_path=" + truststore_path); + String truststore_password = SystemProperties.getProperty(VidProperties.VID_TRUSTSTORE_PASSWD_X); + + + String decrypted_truststore_password = Password.deobfuscate(truststore_password); + //logger.debug(dateFormat.format(new Date()) + " " + methodName + " decrypted_truststore_password=" + decrypted_truststore_password); + + File tr = new File (truststore_path); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + " " + methodName + " absolute truststore path=" + tr.getAbsolutePath()); + + //String keystore_path = certFilePath + AAIProperties.FILESEPARTOR + SystemProperties.getProperty(AAIProperties.AAI_KEYSTORE_FILENAME); + //String keystore_password = SystemProperties.getProperty(AAIProperties.AAI_KEYSTORE_PASSWD_X); + //String decrypted_keystore_password = EncryptedPropValue.decryptTriple(keystore_password); + + System.setProperty("javax.net.ssl.trustStore", truststore_path); + System.setProperty("javax.net.ssl.trustStorePassword", decrypted_truststore_password); + HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){ + public boolean verify(String string,SSLSession ssls) { + return true; + } + }); + + //May need to make the algorithm a parameter. MSO requires TLSv1.1 or TLSv1.2 + ctx = SSLContext.getInstance("TLSv1.2"); + + /* + KeyManagerFactory kmf = null; + try { + kmf = KeyManagerFactory.getInstance("SunX509"); + FileInputStream fin = new FileInputStream(keystore_path); + KeyStore ks = KeyStore.getInstance("PKCS12"); + char[] pwd = decrypted_keystore_password.toCharArray(); + ks.load(fin, pwd); + kmf.init(ks, pwd); + } catch (Exception e) { + System.out.println("Error setting up kmf: exiting"); + e.printStackTrace(); + System.exit(1); + } + + ctx.init(kmf.getKeyManagers(), null, null); + */ + ctx.init(null, null, null); + //config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, + // new HTTPSProperties( , ctx)); + + return ClientBuilder.newBuilder() + .sslContext(ctx) + .hostnameVerifier(new HostnameVerifier() { + @Override + public boolean verify( String s, SSLSession sslSession ) { + return true; + } + }).withConfig(config) + .build() + .register(CustomJacksonJaxBJsonProvider.class); + + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up config: exiting"); + //System.out.println("Error setting up config: exiting"); + e.printStackTrace(); + return null; + } + + //Client client = ClientBuilder.newClient(config); + // uncomment this line to get more logging for the request/response + // client.addFilter(new LoggingFilter(System.out)); + + //return client; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyProperties.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyProperties.java new file mode 100644 index 00000000..cf10d8f6 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyProperties.java @@ -0,0 +1,26 @@ +package org.openecomp.portalapp.portal.scheduler.policy; + +import org.openecomp.portalsdk.core.util.SystemProperties; + + +public class PolicyProperties extends SystemProperties { + + public static final String POLICY_CLIENTAUTH_VAL = "policy.ClientAuth"; + + public static final String POLICY_CLIENT_MECHID_VAL = "policy.client.mechId"; + + public static final String POLICY_CLIENT_PASSWORD_VAL = "policy.client.password"; + + public static final String POLICY_USERNAME_VAL = "policy.username"; + + public static final String POLICY_PASSWORD_VAL = "policy.password"; + + public static final String POLICY_AUTHORIZATION_VAL = "policy.Authorization"; + + public static final String POLICY_SERVER_URL_VAL = "policy.server.url"; + + public static final String POLICY_ENVIRONMENT_VAL = "policy.environment"; + + public static final String POLICY_GET_CONFIG_VAL = "policy.get.config"; + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyResponseWrapper.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyResponseWrapper.java new file mode 100644 index 00000000..ed51456e --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyResponseWrapper.java @@ -0,0 +1,56 @@ +package org.openecomp.portalapp.portal.scheduler.policy; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +/** + * This wrapper encapsulates the Policy response + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "status", + "entity" +}) + +public class PolicyResponseWrapper { + + @JsonProperty("status") + private int status; + + @JsonProperty("entity") + private String entity; + + @JsonProperty("entity") + public String getEntity() { + return entity; + } + + @JsonProperty("status") + public int getStatus() { + return status; + } + + @JsonProperty("status") + public void setStatus(int v) { + this.status = v; + } + + @JsonProperty("entity") + public void setEntity(String v) { + this.entity = v; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + public String getResponse () { + + StringBuilder b = new StringBuilder ("{ \"status\": "); + b.append(getStatus()).append(", \"entity\": " ).append(this.getEntity()).append("}"); + return (b.toString()); + } +}
\ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyRestInt.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyRestInt.java new file mode 100644 index 00000000..ce930c9a --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyRestInt.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.portalapp.portal.scheduler.policy; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.openecomp.portalapp.portal.scheduler.policy.rest.RequestDetails; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class PolicyRestInt { + + /** The logger. */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PolicyRestInterface.class); + + /** The Constant dateFormat. */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + /** The request date format. */ + public DateFormat requestDateFormat = new SimpleDateFormat("EEE, dd MMM YYYY HH:mm:ss z"); + + public PolicyRestInt() { + requestDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT")); + } + + /** + * Log request. + * + * @param r the r + */ + public void logRequest ( RequestDetails r ) { + String methodName = "logRequest"; + ObjectMapper mapper = new ObjectMapper(); + String r_json_str = ""; + if ( r != null ) { + r_json_str = r.toString(); + try { + r_json_str = mapper.writeValueAsString(r); + } + catch ( com.fasterxml.jackson.core.JsonProcessingException j ) { + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Unable to parse request as json"); + } + } + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Request=(" + r_json_str + ")"); + } +}
\ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyRestInterface.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyRestInterface.java new file mode 100644 index 00000000..70b4f818 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyRestInterface.java @@ -0,0 +1,235 @@ +package org.openecomp.portalapp.portal.scheduler.policy; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Collections; +import java.util.Date; + +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 org.apache.commons.codec.binary.Base64; +import org.eclipse.jetty.util.security.Password; +import org.json.simple.JSONObject; +import org.openecomp.portalapp.portal.scheduler.client.HttpBasicClient; +import org.openecomp.portalapp.portal.scheduler.policy.rest.RequestDetails; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; + + +public class PolicyRestInterface extends PolicyRestInt implements PolicyRestInterfaceIfc { + + /** The logger. */ + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PolicyRestInterface.class); + + /** The Constant dateFormat. */ + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + /** The client. */ + private static Client client = null; + + /** The common headers. */ + private MultivaluedHashMap<String, Object> commonHeaders; + + public PolicyRestInterface() { + super(); + } + + public void initRestClient() + { + final String methodname = "initRestClient()"; + + //final String clientAuth = SystemProperties.getProperty(PolicyProperties.POLICY_CLIENTAUTH_VAL); + //final String authorization = SystemProperties.getProperty(PolicyProperties.POLICY_AUTHORIZATION_VAL); + final String mechId = SystemProperties.getProperty(PolicyProperties.POLICY_CLIENT_MECHID_VAL); + final String clientPassword = SystemProperties.getProperty(PolicyProperties.POLICY_CLIENT_PASSWORD_VAL); + final String username = SystemProperties.getProperty(PolicyProperties.POLICY_USERNAME_VAL); + final String password = SystemProperties.getProperty(PolicyProperties.POLICY_PASSWORD_VAL); + final String environment = SystemProperties.getProperty(PolicyProperties.POLICY_ENVIRONMENT_VAL); + + final String decrypted_client_password = Password.deobfuscate(clientPassword); + String mechAuthString = mechId + ":" + decrypted_client_password; + byte[] mechAuthEncBytes = Base64.encodeBase64(mechAuthString.getBytes()); + String clientAuth = new String(mechAuthEncBytes); + + final String decrypted_password = Password.deobfuscate(password); + String authString = username + ":" + decrypted_password; + byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); + String authorization = new String(authEncBytes); + + commonHeaders = new MultivaluedHashMap<String, Object> (); + commonHeaders.put("ClientAuth", Collections.singletonList((Object) ("Basic " + clientAuth))); + commonHeaders.put("Authorization", Collections.singletonList((Object) ("Basic " + authorization))); + commonHeaders.put("Environment", Collections.singletonList((Object) (environment))); + + if (client == null) { + + try { + client = HttpBasicClient.getClient(); + } catch (Exception e) { + System.out.println( methodname + " Unable to get the SSL client"); + } + } + } + + @SuppressWarnings("unchecked") + public <T> void Get (T t, String sourceId, String path, RestObject<T> restObject ) throws Exception { + String methodName = "Get"; + + logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start"); + + String url=""; + restObject.set(t); + + url = SystemProperties.getProperty(PolicyProperties.POLICY_SERVER_URL_VAL) + path; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " sending request to url= " + url); + + initRestClient(); + + final Response cres = client.target(url) + .request() + .accept("application/json") + .headers(commonHeaders) + .get(); + + int status = cres.getStatus(); + restObject.setStatusCode (status); + + if (status == 200) { + t = (T) cres.readEntity(t.getClass()); + restObject.set(t); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " REST api was successfull!"); + + } else { + throw new Exception(methodName + " with status="+ status + ", url= " + url ); + } + + logger.debug(EELFLoggerDelegate.debugLogger,methodName + " received status=" + status ); + + return; + } + + @SuppressWarnings("unchecked") + public <T> void Delete(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) { + + String methodName = "Delete"; + String url=""; + Response cres = null; + + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " start"); + logRequest (r); + + try { + initRestClient(); + + url = SystemProperties.getProperty(PolicyProperties.POLICY_SERVER_URL_VAL) + path; + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + " methodName sending request to: " + url); + + cres = client.target(url) + .request() + .accept("application/json") + .headers(commonHeaders) + //.entity(r) + .build("DELETE", Entity.entity(r, 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); + + if (status == 404) { // resource not found + String msg = "Resource does not exist...: " + cres.getStatus(); + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg); + } else if (status == 200 || status == 204){ + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + "Resource " + url + " deleted"); + } else if (status == 202) { + String msg = "Delete in progress: " + status; + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg); + } + else { + String msg = "Deleting Resource failed: " + status; + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg); + } + + try { + t = (T) cres.readEntity(t.getClass()); + restObject.set(t); + } + catch ( Exception e ) { + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " No response entity, this is probably ok, e=" + + e.getMessage()); + } + + } + catch (Exception e) + { + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with url="+url+ ", Exception: " + e.toString()); + throw e; + + } + } + + @SuppressWarnings("unchecked") + public <T> void Post(T t, JSONObject requestDetails, String uuid, String path, RestObject<T> restObject) throws Exception { + + String methodName = "Post"; + String url=""; + + System.out.println( "POST policy rest interface"); + + // logRequest (requestDetails); + try { + + initRestClient(); + + url = SystemProperties.getProperty(PolicyProperties.POLICY_SERVER_URL_VAL) + path; + System.out.println( "<== " + methodName + " sending request to url= " + url); + // Change the content length + final Response cres = client.target(url) + .request() + .accept("application/json") + .headers(commonHeaders) + //.header("content-length", 201) + //.header("X-FromAppId", sourceID) + .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON)); + + try { + t = (T) cres.readEntity(t.getClass()); + restObject.set(t); + } + catch ( Exception e ) { + + System.out.println("<== " + methodName + " No response entity, this is probably ok, e=" + e.getMessage()); + } + + int status = cres.getStatus(); + restObject.setStatusCode (status); + + if ( status >= 200 && status <= 299 ) { + System.out.println( "<== " + methodName + " REST api POST was successful!"); + + } else { + System.out.println( "<== " + methodName + " with status="+status+", url="+url); + } + + } catch (Exception e) + { + System.out.println( "<== " + methodName + " with url="+url+ ", Exception: " + e.toString()); + throw e; + + } + } + + public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException + { + return clazz.newInstance(); + } + + @Override + public void logRequest(RequestDetails r) { + // TODO Auto-generated method stub + } +}
\ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyRestInterfaceFactory.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyRestInterfaceFactory.java new file mode 100644 index 00000000..c6dd440d --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyRestInterfaceFactory.java @@ -0,0 +1,14 @@ + +package org.openecomp.portalapp.portal.scheduler.policy; + +public class PolicyRestInterfaceFactory { + + + public static PolicyRestInterfaceIfc getInstance () { + PolicyRestInterfaceIfc obj = null; + + obj = new PolicyRestInterface(); + + return ( obj ); + } +}
\ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyRestInterfaceIfc.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyRestInterfaceIfc.java new file mode 100644 index 00000000..38fedb9c --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyRestInterfaceIfc.java @@ -0,0 +1,58 @@ + +package org.openecomp.portalapp.portal.scheduler.policy; + +import org.json.simple.JSONObject; +import org.openecomp.portalapp.portal.scheduler.policy.rest.RequestDetails; + +public interface PolicyRestInterfaceIfc { + /** + * Inits the rest client. + */ + public void initRestClient(); + + /** + * Gets the. + * + * @param <T> the generic type + * @param t the t + * @param sourceId the source id + * @param path the path + * @param restObject the rest object + * @throws Exception the exception + */ + public <T> void Get (T t, String sourceId, String path, RestObject<T> restObject ) throws Exception; + + /** + * Delete. + * + * @param <T> the generic type + * @param t the t + * @param r the r + * @param sourceID the source ID + * @param path the path + * @param restObject the rest object + * @throws Exception the exception + */ + public <T> void Delete(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) throws Exception; + + /** + * Post. + * + * @param <T> the generic type + * @param t the t + * @param r the r + * @param sourceID the source ID + * @param path the path + * @param restObject the rest object + * @throws Exception the exception + */ + public <T> void Post(T t, JSONObject r, String sourceID, String path, RestObject<T> restObject) throws Exception; + + /*** + * Log request. + * + * @param r the r + */ + public void logRequest ( RequestDetails r ); + +}
\ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyUtil.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyUtil.java new file mode 100644 index 00000000..8ec8323d --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/PolicyUtil.java @@ -0,0 +1,71 @@ +package org.openecomp.portalapp.portal.scheduler.policy; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.glassfish.jersey.client.ClientResponse; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +/*import org.openecomp.vid.policy.PolicyResponseWrapper; +import org.openecomp.vid.policy.PolicyUtil; +import org.openecomp.vid.policy.RestObject;*/ + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class PolicyUtil { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PolicyUtil.class); + + final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + public static PolicyResponseWrapper wrapResponse ( String body, int statusCode ) { + + PolicyResponseWrapper w = new PolicyResponseWrapper(); + w.setStatus (statusCode); + w.setEntity(body); + + return w; + } + + public static PolicyResponseWrapper wrapResponse (ClientResponse cres) { + String resp_str = ""; + if ( cres != null ) { + resp_str = cres.readEntity(String.class); + } + int statuscode = cres.getStatus(); + PolicyResponseWrapper w = PolicyUtil.wrapResponse ( resp_str, statuscode ); + return (w); + } + + public static PolicyResponseWrapper wrapResponse (RestObject<String> rs) { + String resp_str = ""; + int status = 0; + if ( rs != null ) { + resp_str = rs.get(); + status = rs.getStatusCode(); + } + PolicyResponseWrapper w = PolicyUtil.wrapResponse ( resp_str, status ); + return (w); + } + + public static <T> String convertPojoToString ( T t ) throws com.fasterxml.jackson.core.JsonProcessingException { + + String methodName = "convertPojoToString"; + ObjectMapper mapper = new ObjectMapper(); + String r_json_str = ""; + if ( t != null ) { + try { + r_json_str = mapper.writeValueAsString(t); + } + catch ( com.fasterxml.jackson.core.JsonProcessingException j ) { + logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Unable to parse object as json"); + } + } + return (r_json_str); + } + + + public static void main(String[] args) { + // TODO Auto-generated method stub + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/RestObject.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/RestObject.java new file mode 100644 index 00000000..040971e5 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/RestObject.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.portalapp.portal.scheduler.policy; + +/** + * The Class RestObject. + * + * @param <T> the generic type + */ +public class RestObject<T> { + + /** + * Generic version of the RestObject class. + * + */ + // T stands for "Type" + private T t; + + /** The status code. */ + private int statusCode= 0; + + /** + * Sets the. + * + * @param t the t + */ + public void set(T t) { this.t = t; } + + /** + * Gets the. + * + * @return the t + */ + public T get() { return t; } + + /** + * Sets the status code. + * + * @param v the new status code + */ + public void setStatusCode(int v) { this.statusCode = v; } + + /** + * Gets the status code. + * + * @return the status code + */ + public int getStatusCode() { return this.statusCode; } + +}
\ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/rest/RequestDetails.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/rest/RequestDetails.java new file mode 100644 index 00000000..9c5debee --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/policy/rest/RequestDetails.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.portalapp.portal.scheduler.policy.rest; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +/* + [ + { + "policyConfigMessage": "Config Retrieved! ", + "policyConfigStatus": "CONFIG_RETRIEVED", + "type": "JSON", + "config": "{\"service\":\"TimeLimitAndVerticalTopology\",\"policyName\":\"SNIRO_CM_1707.Demo_TimeLimitAndVerticalTopology_zone_localTime\",\"description\":\"dev instance\",\"templateVersion\":\"1702.03\",\"version\":\"1707\",\"priority\":\"4\",\"riskType\":\"test\",\"riskLevel\":\"3\",\"guard\":\"False\",\"content\":{\"serviceType\":\"networkOnDemand\",\"identity\":\"vnf_upgrade_policy\",\"policyScope\":{\"serviceType\":[\"networkOnDemand\"],\"aicZone\":[\" \"],\"entityType\":[\"vnf\"]},\"timeSchedule\":{\"allowedPeriodicTime\":[{\"day\":\"weekday\",\"timeRange\":[{\"start_time\":\"04:00:00\",\"end_time\":\"13:00:00\"}]}]},\"nodeType\":[\"vnf\"],\"type\":\"timeLimitAndVerticalTopology\",\"conflictScope\":\"vnf_zone\"}}", + "policyName": "SNIRO_CM_1707.Config_MS_Demo_TimeLimitAndVerticalTopology_zone_localTime.1.xml", + "policyVersion": "1", + "matchingConditions": { + "ECOMPName": "SNIRO-Placement", + "ConfigName": "", + "service": "TimeLimitAndVerticalTopology", + "uuid": "", + "Location": "" + }, + "responseAttributes": {}, + "property": null + }, + { + "policyConfigMessage": "Config Retrieved! ", + "policyConfigStatus": "CONFIG_RETRIEVED", + "type": "JSON", + "config": "{\"service\":\"TimeLimitAndVerticalTopology\",\"policyName\":\"SNIRO_CM_1707.Demo_TimeLimitAndVerticalTopology_pserver_localTime\",\"description\":\"dev instance\",\"templateVersion\":\"1702.03\",\"version\":\"1707\",\"priority\":\"4\",\"riskType\":\"test\",\"riskLevel\":\"3\",\"guard\":\"False\",\"content\":{\"serviceType\":\"networkOnDemand\",\"identity\":\"vnf_upgrade_policy\",\"policyScope\":{\"serviceType\":[\"networkOnDemand\"],\"aicZone\":[\" \"],\"entityType\":[\"vnf\"]},\"timeSchedule\":{\"allowedPeriodicTime\":[{\"day\":\"weekday\",\"timeRange\":[{\"start_time\":\"04:00:00\",\"end_time\":\"13:00:00\"}]}]},\"nodeType\":[\"vnf\"],\"type\":\"timeLimitAndVerticalTopology\",\"conflictScope\":\"vnf_pserver\"}}", + "policyName": "SNIRO_CM_1707.Config_MS_Demo_TimeLimitAndVerticalTopology_pserver_localTime.1.xml", + "policyVersion": "1", + "matchingConditions": { + "ECOMPName": "SNIRO-Placement", + "ConfigName": "", + "service": "TimeLimitAndVerticalTopology", + "uuid": "", + "Location": "" + }, + "responseAttributes": {}, + "property": null + }, + { + "policyConfigMessage": "Config Retrieved! ", + "policyConfigStatus": "CONFIG_RETRIEVED", + "type": "JSON", + "config": "{\"service\":\"TimeLimitAndVerticalTopology\",\"policyName\":\"SNIRO_CM_1707.Demo_TimeLimitAndVerticalTopology_vnf_localTime\",\"description\":\"dev instance\",\"templateVersion\":\"1702.03\",\"version\":\"1707\",\"priority\":\"4\",\"riskType\":\"test\",\"riskLevel\":\"3\",\"guard\":\"False\",\"content\":{\"serviceType\":\"networkOnDemand\",\"identity\":\"vnf_upgrade_policy\",\"policyScope\":{\"serviceType\":[\"networkOnDemand\"],\"aicZone\":[\" \"],\"entityType\":[\"vnf\"]},\"timeSchedule\":{\"allowedPeriodicTime\":[{\"day\":\"weekday\",\"timeRange\":[{\"start_time\":\"04:00:00\",\"end_time\":\"13:00:00\"}]}]},\"nodeType\":[\"vnf\"],\"type\":\"timeLimitAndVerticalTopology\",\"conflictScope\":\"vnf\"}}", + "policyName": "SNIRO_CM_1707.Config_MS_Demo_TimeLimitAndVerticalTopology_vnf_localTime.1.xml", + "policyVersion": "1", + "matchingConditions": { + "ECOMPName": "SNIRO-Placement", + "ConfigName": "", + "service": "TimeLimitAndVerticalTopology", + "uuid": "", + "Location": "" + }, + "responseAttributes": {}, + "property": null + } + ] +*/ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "policyConfigMessage", + "policyConfigStatus", + "type", + "config", + "policyName", + "policyVersion", + "matchingConditions" +}) +public class RequestDetails { + + @JsonProperty("policyName") + private String policyName; + + @JsonProperty("policyName") + public String getPolicyName() { + return policyName; + } + + @JsonProperty("policyName") + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + +}
\ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/properties/VidProperties.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/properties/VidProperties.java new file mode 100644 index 00000000..883f8714 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/properties/VidProperties.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.portalapp.portal.scheduler.properties; +import org.openecomp.portalsdk.core.util.SystemProperties; +/** + * The Class VidProperties. + */ +public class VidProperties extends SystemProperties { + + //VID General Properties + + /** The Constant VID_TRUSTSTORE_FILENAME. */ + public static final String VID_TRUSTSTORE_FILENAME = "vid.truststore.filename"; + + /** The Constant VID_TRUSTSTORE_PASSWD_X. */ + public static final String VID_TRUSTSTORE_PASSWD_X = "vid.truststore.passwd.x"; + + /** The Constant FILESEPARATOR. */ + public static final String FILESEPARATOR = (System.getProperty("file.separator") == null) ? "/" : System.getProperty("file.separator"); + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/restobjects/GetTimeSlotsRestObject.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/restobjects/GetTimeSlotsRestObject.java new file mode 100644 index 00000000..3e7771ae --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/restobjects/GetTimeSlotsRestObject.java @@ -0,0 +1,11 @@ +package org.openecomp.portalapp.portal.scheduler.restobjects; + +public class GetTimeSlotsRestObject<T> extends RestObject<T> { + + public String uuid; + + public void setUUID(String uuid) { this.uuid = uuid; } + + public String getUUID() { return this.uuid; } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/restobjects/PostCreateNewVnfRestObject.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/restobjects/PostCreateNewVnfRestObject.java new file mode 100644 index 00000000..7e92307b --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/restobjects/PostCreateNewVnfRestObject.java @@ -0,0 +1,10 @@ +package org.openecomp.portalapp.portal.scheduler.restobjects; + +public class PostCreateNewVnfRestObject<T> extends RestObject<T> { + + public String uuid; + + public void setUUID(String uuid) { this.uuid = uuid; } + + public String getUUID() { return this.uuid; } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/restobjects/PostSubmitVnfChangeRestObject.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/restobjects/PostSubmitVnfChangeRestObject.java new file mode 100644 index 00000000..9dd66afc --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/restobjects/PostSubmitVnfChangeRestObject.java @@ -0,0 +1,10 @@ +package org.openecomp.portalapp.portal.scheduler.restobjects; + +public class PostSubmitVnfChangeRestObject<T> extends RestObject<T> { + + public String uuid; + + public void setUUID(String uuid) { this.uuid = uuid; } + + public String getUUID() { return this.uuid; } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/restobjects/RestObject.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/restobjects/RestObject.java new file mode 100644 index 00000000..6bb74431 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/restobjects/RestObject.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.portalapp.portal.scheduler.restobjects; + + +public class RestObject<T> { + + private T t; + + private int statusCode= 0; + + public void set(T t) { this.t = t; } + + public T get() { return t; } + + public void setStatusCode(int v) { this.statusCode = v; } + + public int getStatusCode() { return this.statusCode; } + +} + diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/util/CustomJacksonJaxBJsonProvider.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/util/CustomJacksonJaxBJsonProvider.java new file mode 100644 index 00000000..e6953838 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/util/CustomJacksonJaxBJsonProvider.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.portalapp.portal.scheduler.util; + + +import javax.ws.rs.ext.Provider; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; +import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; + +/** + * The Class CustomJacksonJaxBJsonProvider. + */ +@Provider +public class CustomJacksonJaxBJsonProvider extends JacksonJaxbJsonProvider { + + /** The common mapper. */ + private static ObjectMapper commonMapper = null; + + /** + * Instantiates a new custom jackson jax B json provider. + */ + public CustomJacksonJaxBJsonProvider() { + if (commonMapper == null) { + ObjectMapper mapper = new ObjectMapper(); + + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + + mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); + mapper.configure(SerializationFeature.INDENT_OUTPUT, false); + mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); + + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false); + + mapper.registerModule(new JaxbAnnotationModule()); + + commonMapper = mapper; + } + super.setMapper(commonMapper); + } + + /** + * Gets the mapper. + * + * @return the mapper + */ + public ObjectMapper getMapper() { + return commonMapper; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/wrapper/GetTimeSlotsWrapper.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/wrapper/GetTimeSlotsWrapper.java new file mode 100644 index 00000000..81aafc62 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/wrapper/GetTimeSlotsWrapper.java @@ -0,0 +1,5 @@ +package org.openecomp.portalapp.portal.scheduler.wrapper; + +public class GetTimeSlotsWrapper extends SchedulerResponseWrapper { + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/wrapper/PostCreateNewVnfWrapper.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/wrapper/PostCreateNewVnfWrapper.java new file mode 100644 index 00000000..38aa6347 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/wrapper/PostCreateNewVnfWrapper.java @@ -0,0 +1,39 @@ +package org.openecomp.portalapp.portal.scheduler.wrapper; + +import org.apache.commons.lang.builder.ToStringBuilder; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "uuid" +}) +public class PostCreateNewVnfWrapper extends SchedulerResponseWrapper { + + @JsonProperty("uuid") + private String uuid; + + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + + @JsonProperty("uuid") + public void setUuid(String v) { + this.uuid = v; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + public String getResponse () { + + StringBuilder b = new StringBuilder ("{ \"status\": "); + b.append(getStatus()).append(", \"entity\": \" " ).append(this.getEntity()).append("\" ,\"uuid\": \"" ).append(this.getUuid()).append("\"}"); + return (b.toString()); + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/wrapper/PostSubmitVnfChangeTimeSlotsWrapper.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/wrapper/PostSubmitVnfChangeTimeSlotsWrapper.java new file mode 100644 index 00000000..9d6725ab --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/wrapper/PostSubmitVnfChangeTimeSlotsWrapper.java @@ -0,0 +1,38 @@ +package org.openecomp.portalapp.portal.scheduler.wrapper; + +import org.apache.commons.lang.builder.ToStringBuilder; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "uuid" +}) +public class PostSubmitVnfChangeTimeSlotsWrapper extends SchedulerResponseWrapper { + @JsonProperty("uuid") + private String uuid; + + @JsonProperty("uuid") + public String getUuid() { + return uuid; + } + + @JsonProperty("uuid") + public void setUuid(String v) { + this.uuid = v; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + public String getResponse () { + + StringBuilder b = new StringBuilder ("{ \"status\": "); + b.append(getStatus()).append(", \"entity\": \" " ).append(this.getEntity()).append("\" ,\"uuid\": \"" ).append(this.getUuid()).append("\"}"); + return (b.toString()); + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/wrapper/SchedulerResponseWrapper.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/wrapper/SchedulerResponseWrapper.java new file mode 100644 index 00000000..e10505c0 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/scheduler/wrapper/SchedulerResponseWrapper.java @@ -0,0 +1,57 @@ +package org.openecomp.portalapp.portal.scheduler.wrapper; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.ToStringBuilder; + +/** + * This wrapper encapsulates the Scheduler response + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "status", + "entity" +}) + +public class SchedulerResponseWrapper { + + @JsonProperty("status") + private int status; + + @JsonProperty("entity") + private String entity; + + @JsonProperty("entity") + public String getEntity() { + return entity; + } + + @JsonProperty("status") + public int getStatus() { + return status; + } + + @JsonProperty("status") + public void setStatus(int v) { + this.status = v; + } + + @JsonProperty("entity") + public void setEntity(String v) { + this.entity = v; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + public String getResponse () { + + StringBuilder b = new StringBuilder ("{ \"status\": "); + + b.append(getStatus()).append(", \"entity\": " ).append(this.getEntity()).append("}"); + return (b.toString()); + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesServiceImpl.java index b5bccfe3..9025b598 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesServiceImpl.java @@ -228,7 +228,10 @@ public class AdminRolesServiceImpl implements AdminRolesService { EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 2", e); try { - transaction.rollback(); + if(transaction!=null) + transaction.rollback(); + else + logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: transaction is null cannot rollback"); } catch (Exception ex) { EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeExecuteRollbackError, e); logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 3", ex); diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleServiceImpl.java index e509fcf5..3efe4382 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleServiceImpl.java @@ -145,7 +145,7 @@ public class EPRoleServiceImpl implements EPRoleService { } else if (appId != 1 && !roleName.equals(PortalConstants.ADMIN_ROLE)) { roles = (List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", params, null); } - int resultsCount = roles.size(); + int resultsCount = (roles == null ? 0 : roles.size()); if (resultsCount > 1) { 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."); diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesService.java index 34088a22..77ce88c5 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesService.java @@ -10,6 +10,7 @@ import org.openecomp.portalapp.portal.domain.EPUser; import org.openecomp.portalapp.portal.transport.CentralRole; import org.openecomp.portalsdk.core.domain.Role; import org.openecomp.portalsdk.core.domain.RoleFunction; +import org.openecomp.portalsdk.core.restful.domain.EcompUser; public interface ExternalAccessRolesService { @@ -246,6 +247,14 @@ public interface ExternalAccessRolesService { * @throws Exception */ List<String> getMenuFunctionsList(String uebkey) throws Exception; - + + /** + * + * @param uebkey applications UebKey + * @return + * @throws Exception + * Method getAllUsers returns all the active users of application + */ + List<EcompUser> getAllAppUsers(String uebkey) throws Exception; } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesServiceImpl.java index 95e5ddce..97fa98e5 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesServiceImpl.java @@ -2,6 +2,7 @@ package org.openecomp.portalapp.portal.service; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; @@ -11,6 +12,7 @@ import java.util.SortedSet; import java.util.TreeSet; import java.util.stream.Collectors; +import org.apache.commons.lang.StringUtils; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; @@ -33,6 +35,7 @@ import org.openecomp.portalapp.portal.transport.CentralApp; import org.openecomp.portalapp.portal.transport.CentralRole; import org.openecomp.portalapp.portal.transport.CentralUser; import org.openecomp.portalapp.portal.transport.CentralUserApp; +import org.openecomp.portalapp.portal.transport.EcompUserRoles; import org.openecomp.portalapp.portal.transport.ExternalAccessPerms; import org.openecomp.portalapp.portal.transport.ExternalAccessPermsDetail; import org.openecomp.portalapp.portal.transport.ExternalAccessRole; @@ -45,6 +48,8 @@ import org.openecomp.portalapp.portal.utils.PortalConstants; import org.openecomp.portalsdk.core.domain.Role; import org.openecomp.portalsdk.core.domain.RoleFunction; import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.restful.domain.EcompRole; +import org.openecomp.portalsdk.core.restful.domain.EcompUser; import org.openecomp.portalsdk.core.service.DataAccessService; import org.openecomp.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; @@ -69,6 +74,18 @@ import com.fasterxml.jackson.databind.type.TypeFactory; @EPAuditLog public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService { + private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '"; + + private static final String OWNER = ".owner"; + + private static final String ADMIN = ".admin"; + + private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator"; + + private static final String FUNCTION_CD_LIKE_CLAUSE = " and function_cd like '%"; + + private static final String FUNCTION_PIPE = "|"; + private static final String IS_NULL_STRING = "null"; private static final String EXTERNAL_AUTH_PERMS = "perms"; @@ -133,7 +150,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic List<EPApp> app = null; try { app = (List<EPApp>) dataAccessService.getList(EPApp.class, " where ueb_key = '" + uebkey + "'", null, null); - if(!app.get(0).getEnabled()){ + if(!app.get(0).getEnabled() && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)){ throw new Exception("Application:"+app.get(0).getName()+" is Unavailable"); } } catch (Exception e) { @@ -225,7 +242,13 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic ExternalAccessRolePerms extRolePerms = null; ExternalAccessPerms extPerms = null; List<EPRole> epRoleList = null; - epRoleList = dataAccessService.getList(EPRole.class, WHERE_ROLE_ID_EQUALS + updateExtRole.getId(), null, null); + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + epRoleList = dataAccessService.getList(EPRole.class, + WHERE_ROLE_ID_EQUALS + updateExtRole.getId() + " and app_id is null", null, null); + } else { + epRoleList = dataAccessService.getList(EPRole.class, + " where app_role_id = " + updateExtRole.getId() + " and app_id = " + app.getId(), null, null); + } String appRole = getSingleAppRole(epRoleList.get(0).getName(), app); if (!appRole.equals(IS_EMPTY_JSON_STRING)) { JSONObject jsonObj = new JSONObject(appRole); @@ -268,9 +291,10 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic addRole(updateExtRole, app.getUebKey()); addRoleFunctionsInExternalSystem(updateExtRole, mapper, app); } + boolean checkPriorityStatus = StringUtils.equals(String.valueOf(sysRoleList.getPriority()),String.valueOf(updateExtRole.getPriority())); ExternalAccessRole updateRole = new ExternalAccessRole(); if (!isActiveValueChanged - || !sysRoleList.getPriority().equals(String.valueOf(updateExtRole.getPriority())) + || !checkPriorityStatus || sysRoleList.getId().equals(IS_NULL_STRING) || !sysRoleList.getId().equals(String.valueOf(epRoleList.get(0).getId()))) { String updateDesc = ""; @@ -278,17 +302,17 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic : APP_ID_EQUALS + app.getId(); List<EPRole> getRole = dataAccessService.getList(EPRole.class, WHERE_ROLE_NAME_EQUALS + updateExtRole.getName() + "' and " + appId, null, null); - Map<String, Object> extSystemUpdateRoleJsonMapper = new LinkedHashMap<>(); - extSystemUpdateRoleJsonMapper.put(ID, getRole.get(0).getId()); - extSystemUpdateRoleJsonMapper.put(ROLE_NAME, updateExtRole.getName()); - extSystemUpdateRoleJsonMapper.put(ACTIVE, updateExtRole.getActive()); - extSystemUpdateRoleJsonMapper.put(PRIORITY, updateExtRole.getPriority()); + Map<String, String> extSystemUpdateRoleJsonMapper = new LinkedHashMap<>(); + extSystemUpdateRoleJsonMapper.put(ID, String.valueOf(getRole.get(0).getId())); + extSystemUpdateRoleJsonMapper.put(ROLE_NAME, String.valueOf(updateExtRole.getName())); + extSystemUpdateRoleJsonMapper.put(ACTIVE, String.valueOf(updateExtRole.getActive())); + extSystemUpdateRoleJsonMapper.put(PRIORITY, String.valueOf(updateExtRole.getPriority())); if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - extSystemUpdateRoleJsonMapper.put(APP_ID, null); - extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, null); + extSystemUpdateRoleJsonMapper.put(APP_ID, "null"); + extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, "null"); } else { - extSystemUpdateRoleJsonMapper.put(APP_ID, app.getId()); - extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, getRole.get(0).getAppRoleId()); + extSystemUpdateRoleJsonMapper.put(APP_ID, String.valueOf(app.getId())); + extSystemUpdateRoleJsonMapper.put(APP_ROLE_ID, String.valueOf(getRole.get(0).getAppRoleId())); } updateDesc = mapper.writeValueAsString(extSystemUpdateRoleJsonMapper); @@ -465,13 +489,13 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic String addNewRole = ""; ExternalAccessRole extRole = new ExternalAccessRole(); String addDesc = null; - Map<String, Object> extSystemJsonMapper = new LinkedHashMap<>(); - extSystemJsonMapper.put(ID, newRole.get(0).getId()); - extSystemJsonMapper.put(ROLE_NAME, newRole.get(0).getName()); - extSystemJsonMapper.put(ACTIVE, newRole.get(0).getActive()); - extSystemJsonMapper.put(PRIORITY, newRole.get(0).getPriority()); - extSystemJsonMapper.put(APP_ID, newRole.get(0).getAppId()); - extSystemJsonMapper.put(APP_ROLE_ID, newRole.get(0).getAppRoleId()); + Map<String, String> extSystemJsonMapper = new LinkedHashMap<>(); + extSystemJsonMapper.put(ID, String.valueOf(newRole.get(0).getId())); + extSystemJsonMapper.put(ROLE_NAME, String.valueOf(newRole.get(0).getName())); + extSystemJsonMapper.put(ACTIVE, String.valueOf(newRole.get(0).getActive())); + extSystemJsonMapper.put(PRIORITY, String.valueOf(newRole.get(0).getPriority())); + extSystemJsonMapper.put(APP_ID, String.valueOf(newRole.get(0).getAppId())); + extSystemJsonMapper.put(APP_ROLE_ID, String.valueOf(newRole.get(0).getAppRoleId())); addDesc = mapper.writeValueAsString(extSystemJsonMapper); extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName().replaceAll(" ", "_")); extRole.setDescription(addDesc); @@ -508,18 +532,18 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic ExternalAccessRole extRole = new ExternalAccessRole(); List<EPRole> role = null; String addDesc = null; - Map<String, Object> extSystemUpdateRole = new LinkedHashMap<>(); + Map<String, String> extSystemUpdateRole = new LinkedHashMap<>(); if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - role = dataAccessService.getList(EPRole.class, WHERE_ROLE_ID_EQUALS + addRole.getId(), null, null); + role = dataAccessService.getList(EPRole.class, WHERE_ROLE_ID_EQUALS + addRole.getId() + " and app_id is null", null, null); } else { - role = dataAccessService.getList(EPRole.class, " where app_role_id = " + addRole.getId(), null, null); + role = dataAccessService.getList(EPRole.class, " where app_role_id = " + addRole.getId() + " and app_id ="+app.getId(), null, null); } - extSystemUpdateRole.put(ID, role.get(0).getId()); - extSystemUpdateRole.put(ROLE_NAME, addRole.getName()); - extSystemUpdateRole.put(ACTIVE, role.get(0).getActive()); - extSystemUpdateRole.put(PRIORITY, role.get(0).getPriority()); - extSystemUpdateRole.put(APP_ID, role.get(0).getAppId()); - extSystemUpdateRole.put(APP_ROLE_ID, role.get(0).getAppRoleId()); + extSystemUpdateRole.put(ID, String.valueOf(role.get(0).getId())); + extSystemUpdateRole.put(ROLE_NAME, String.valueOf(addRole.getName())); + extSystemUpdateRole.put(ACTIVE, String.valueOf(role.get(0).getActive())); + extSystemUpdateRole.put(PRIORITY, String.valueOf(role.get(0).getPriority())); + extSystemUpdateRole.put(APP_ID, String.valueOf(role.get(0).getAppId())); + extSystemUpdateRole.put(APP_ROLE_ID, String.valueOf(role.get(0).getAppRoleId())); addDesc = mapper.writeValueAsString(extSystemUpdateRole); extRole.setName(app.getNameSpace() + "." + addRole.getName().replaceAll(" ", "_")); extRole.setDescription(addDesc); @@ -652,13 +676,17 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic * @param applicationRoles * @throws Exception */ + @SuppressWarnings("unchecked") private void saveRoleFunction(List<RoleFunction> roleFunctionListNew, EPApp app, List<EPRole> applicationRoles) throws Exception { for (RoleFunction roleFunc : roleFunctionListNew) { EPAppRoleFunction appRoleFunc = new EPAppRoleFunction(); appRoleFunc.setAppId(app.getId()); appRoleFunc.setRoleId(applicationRoles.get(0).getId()); - appRoleFunc.setCode(roleFunc.getCode()); + // query to check if function code is different for safe operation + List<CentralRoleFunction> roleFunction = dataAccessService.getList(CentralRoleFunction.class, + WHERE_APP_ID_EQUALS+ app.getId()+FUNCTION_CD_LIKE_CLAUSE + roleFunc.getCode() + "'", null, null); + appRoleFunc.setCode(roleFunction.get(0).getCode()); dataAccessService.saveDomainObject(appRoleFunc, null); } } @@ -739,15 +767,33 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic @Override public List<CentralRoleFunction> getRoleFuncList(String uebkey) throws Exception { EPApp app = getApp(uebkey).get(0); - List<CentralRoleFunction> getRoleFuncList = null; + List<CentralRoleFunction> finalRoleList = new ArrayList<>(); final Map<String, Long> params = new HashMap<>(); params.put(APP_ID, app.getId()); // Sync all functions from external system into Ecomp portal DB logger.debug(EELFLoggerDelegate.debugLogger, "getRoleFuncList: Entering into syncRoleFunctionFromExternalAccessSystem"); syncRoleFunctionFromExternalAccessSystem(app); logger.debug(EELFLoggerDelegate.debugLogger, "getRoleFuncList: Finished syncRoleFunctionFromExternalAccessSystem"); - getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null); - return getRoleFuncList; + List<CentralRoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null); + for(CentralRoleFunction roleFuncItem : getRoleFuncList ){ + if(roleFuncItem.getCode().contains(FUNCTION_PIPE)){ + String code = ""; + int count = StringUtils.countMatches(roleFuncItem.getCode(), FUNCTION_PIPE); + if (count == 2) + code = roleFuncItem.getCode().substring( + roleFuncItem.getCode().indexOf(FUNCTION_PIPE) + 1, + roleFuncItem.getCode().lastIndexOf(FUNCTION_PIPE)); + else + code = roleFuncItem.getCode() + .substring(roleFuncItem.getCode().lastIndexOf(FUNCTION_PIPE) + 1); + + roleFuncItem.setCode(code); + finalRoleList.add(roleFuncItem); + } else{ + finalRoleList.add(roleFuncItem); + } + } + return finalRoleList; } /** @@ -792,8 +838,24 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic .executeNamedQuery("getAppRoleFunctionList", params, null); SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<>(); for (CentralRoleFunction roleFunc : appRoleFunctionList) { - CentralRoleFunction cenRoleFunc = new CentralRoleFunction(roleFunc.getId(), - roleFunc.getCode(), roleFunc.getName(), null, null); + String functionCode = ""; + if (roleFunc.getCode().contains(FUNCTION_PIPE)) { + int count = StringUtils.countMatches(roleFunc.getCode(), FUNCTION_PIPE); + String finalFunctionCodeVal; + if (count == 2) + finalFunctionCodeVal = roleFunc.getCode().substring( + roleFunc.getCode().indexOf(FUNCTION_PIPE) + 1, + roleFunc.getCode().lastIndexOf(FUNCTION_PIPE)); + else + finalFunctionCodeVal = roleFunc.getCode() + .substring(roleFunc.getCode().lastIndexOf(FUNCTION_PIPE) + 1); + + functionCode = finalFunctionCodeVal; + } else { + functionCode = roleFunc.getCode(); + } + CentralRoleFunction cenRoleFunc = new CentralRoleFunction(roleFunc.getId(), functionCode, + roleFunc.getName(), null, null); roleFunctionSet.add(cenRoleFunc); } Long userRoleId = null; @@ -892,7 +954,22 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic params, null); SortedSet<CentralRoleFunction> roleFunctionSet = new TreeSet<>(); for (CentralRoleFunction roleFunc : cenRoleFuncList) { - CentralRoleFunction cenRoleFunc = new CentralRoleFunction(role.getId(), roleFunc.getCode(), + String functionCode = ""; + if (roleFunc.getCode().contains(FUNCTION_PIPE)) { + int count = StringUtils.countMatches(roleFunc.getCode(), FUNCTION_PIPE); + String finalFunctionCodeVal; + if (count == 2) + finalFunctionCodeVal = roleFunc.getCode().substring( + roleFunc.getCode().indexOf(FUNCTION_PIPE) + 1, + roleFunc.getCode().lastIndexOf(FUNCTION_PIPE)); + else + finalFunctionCodeVal = roleFunc.getCode() + .substring(roleFunc.getCode().lastIndexOf(FUNCTION_PIPE) + 1); + functionCode = finalFunctionCodeVal; + } else { + functionCode = roleFunc.getCode(); + } + CentralRoleFunction cenRoleFunc = new CentralRoleFunction(role.getId(), functionCode, roleFunc.getName(), null, null); roleFunctionSet.add(cenRoleFunc); } @@ -925,13 +1002,20 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic getRoleFuncList = dataAccessService.executeNamedQuery("getRoleFunction", params, null); if (getRoleFuncList.isEmpty()) { return roleFunc; + } else{ + String functionCodeFormat = getRoleFuncList.get(0).getCode(); + if(functionCodeFormat.contains(FUNCTION_PIPE)){ + String newfunctionCodeFormat = functionCodeFormat.substring(functionCodeFormat.lastIndexOf(FUNCTION_PIPE)+1); + roleFunc = new CentralRoleFunction(getRoleFuncList.get(0).getId(), newfunctionCodeFormat, getRoleFuncList.get(0).getName(), getRoleFuncList.get(0).getAppId(), getRoleFuncList.get(0).getEditUrl()); + } else{ + roleFunc = new CentralRoleFunction(getRoleFuncList.get(0).getId(), functionCodeFormat, getRoleFuncList.get(0).getName(), getRoleFuncList.get(0).getAppId(), getRoleFuncList.get(0).getEditUrl()); + } } - } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e); throw new Exception("getRoleFunction failed", e); } - return getRoleFuncList.get(0); + return roleFunc; } @Override @@ -959,13 +1043,10 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic private void addRoleFunctionInExternalSystem(CentralRoleFunction domainCentralRoleFunction, EPApp app) throws Exception { ObjectMapper mapper = new ObjectMapper(); - final Map<String, String> params = new HashMap<>(); - params.put("functionCd", domainCentralRoleFunction.getCode()); - params.put(APP_ID, String.valueOf(app.getId())); ExternalAccessPerms extPerms = new ExternalAccessPerms(); HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); - List<CentralRoleFunction> appRoleFunc = dataAccessService.executeNamedQuery("getAppFunctionDetails", params, - null); + List<CentralRoleFunction> appRoleFunc = dataAccessService.getList(CentralRoleFunction.class, + WHERE_APP_ID_EQUALS + app.getId() + AND_FUNCTION_CD_EQUALS + domainCentralRoleFunction.getCode() + "'", null, null); String roleFuncName = null; if (!appRoleFunc.isEmpty()) { roleFuncName = appRoleFunc.get(0).getCode(); @@ -1034,10 +1115,10 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic boolean deleteFunctionResponse = false; try { final Map<String, String> params = new HashMap<>(); - params.put("functionCd", code); + params.put("functionCode", code); params.put(APP_ID, String.valueOf(app.getId())); CentralRoleFunction domainCentralRoleFunction = (CentralRoleFunction) dataAccessService - .executeNamedQuery("getAppFunctionDetails", params, null).get(0); + .executeNamedQuery("getRoleFunction", params, null).get(0); deleteRoleFunctionInExternalSystem(domainCentralRoleFunction, app); // Delete role function dependency records deleteAppRoleFunctions(code, app); @@ -1057,7 +1138,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic */ private void deleteAppRoleFunctions(String code, EPApp app) { dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, - APP_ID_EQUALS + app.getId() + " and function_cd = '" + code + "'", null); + APP_ID_EQUALS + app.getId() + FUNCTION_CD_LIKE_CLAUSE + code + "'", null); } /** @@ -1073,7 +1154,13 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic try { ObjectMapper mapper = new ObjectMapper(); ExternalAccessPerms extPerms = new ExternalAccessPerms(); - String checkType = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url"; + String instanceValue = ""; + if(domainCentralRoleFunction.getCode().contains(FUNCTION_PIPE)){ + instanceValue = domainCentralRoleFunction.getCode().substring(domainCentralRoleFunction.getCode().lastIndexOf(FUNCTION_PIPE)+1); + }else{ + instanceValue = domainCentralRoleFunction.getCode(); + } + String checkType = instanceValue.contains("menu") ? "menu" : "url"; HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); extPerms.setAction("*"); extPerms.setInstance(domainCentralRoleFunction.getCode()); @@ -1298,21 +1385,29 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic ExternalAccessPermsDetail permDetails = null; List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>(); for (int i = 0; i < extPerms.length(); i++) { + String description = null; + if(extPerms.getJSONObject(i).has("description")){ + description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION); + } else{ + description = extPerms.getJSONObject(i).getString("instance"); + } if (extPerms.getJSONObject(i).has("roles")) { ObjectMapper rolesListMapper = new ObjectMapper(); JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles"); List<String> list = rolesListMapper.readValue(resRoles.toString(), TypeFactory.defaultInstance().constructCollectionType(List.class, String.class)); permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"), - extPerms.getJSONObject(i).getString("instance"), - extPerms.getJSONObject(i).getString("action"), list, - extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION)); + extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1) + + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE + + extPerms.getJSONObject(i).getString("action"), + extPerms.getJSONObject(i).getString("action"), list, description); permsDetailList.add(permDetails); } else { permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"), - extPerms.getJSONObject(i).getString("instance"), - extPerms.getJSONObject(i).getString("action"), - extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION)); + extPerms.getJSONObject(i).getString("type").substring(app.getNameSpace().length() + 1) + + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE + + extPerms.getJSONObject(i).getString("action"), + extPerms.getJSONObject(i).getString("action"), description); permsDetailList.add(permDetails); } } @@ -1329,20 +1424,34 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } // delete all application role functions dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, APP_ID_EQUALS + app.getId(), null); - // Add if new functions and app role functions were added in external auth system for (ExternalAccessPermsDetail permsDetail : permsDetailList) { - if (!roleFuncMap.containsKey(permsDetail.getInstance())) { - try{ - CentralRoleFunction addFunction = new CentralRoleFunction(); - addFunction.setAppId(app.getId()); - addFunction.setCode(permsDetail.getInstance()); - addFunction.setName(permsDetail.getDescription()); - dataAccessService.saveDomainObject(addFunction, null); - } catch(Exception e){ - logger.error(EELFLoggerDelegate.errorLogger, "syncRoleFunctionFromExternalAccessSystem: Failed to add function", e); + String code = permsDetail.getInstance(); + CentralRoleFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance()); + if (null == getFunctionCodeKey) { + String finalFunctionCodeVal = ""; + if (permsDetail.getInstance().contains(FUNCTION_PIPE)) { + int count = StringUtils.countMatches(permsDetail.getInstance(), FUNCTION_PIPE); + if (count == 2) + finalFunctionCodeVal = permsDetail.getInstance().substring( + permsDetail.getInstance().indexOf(FUNCTION_PIPE) + 1, + permsDetail.getInstance().lastIndexOf(FUNCTION_PIPE)); + else + finalFunctionCodeVal = permsDetail.getInstance() + .substring(permsDetail.getInstance().lastIndexOf(FUNCTION_PIPE) + 1); + } else { + finalFunctionCodeVal = permsDetail.getInstance(); } - } + CentralRoleFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal); + if (null == checkIfCodeStillExits) { + logger.debug(EELFLoggerDelegate.debugLogger, + "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code); + addFunctionInEcompDB(app, permsDetail, code); + logger.debug(EELFLoggerDelegate.debugLogger, + "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code); + + } + } List<EPRole> epRolesList = null; List<String> roles = permsDetail.getRoles(); if (roles != null) { @@ -1372,17 +1481,53 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic + roleList.substring(app.getNameSpace().length() + 1) + "'", null, null); } + // Adding new role thats does not exits in Local but exists in external access system + if (epRolesList.isEmpty()) { + Role role = addRoleInDBIfDoesNotExists(app, roleList.substring(app.getNameSpace().length() + 1)); + addIfRoleDescriptionNotExitsInExtSystem(role, app); + epRolesList = dataAccessService.getList(EPRole.class, + WHERE_APP_ID_EQUALS + app.getId() + " and role_name = '" + + role.getName() + "'", + null, null); + } } // save all application role functions if (!epRolesList.isEmpty()) { - try{ - EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction(); - addAppRoleFunc.setAppId(app.getId()); - addAppRoleFunc.setCode(permsDetail.getInstance()); - addAppRoleFunc.setRoleId(epRolesList.get(0).getId()); - dataAccessService.saveDomainObject(addAppRoleFunc, null); - } catch(Exception e){ - logger.error(EELFLoggerDelegate.errorLogger, "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ", e); + try { + List<CentralRoleFunction> roleFunctionList = null; + String functionCode = ""; + if (permsDetail.getInstance().contains(FUNCTION_PIPE)) { + int count = StringUtils.countMatches(permsDetail.getInstance(), FUNCTION_PIPE); + String finalFunctionCodeVal; + if (count == 2) + finalFunctionCodeVal = permsDetail.getInstance().substring( + permsDetail.getInstance().indexOf(FUNCTION_PIPE) + 1, + permsDetail.getInstance().lastIndexOf(FUNCTION_PIPE)); + else + finalFunctionCodeVal = permsDetail.getInstance() + .substring(permsDetail.getInstance().lastIndexOf(FUNCTION_PIPE) + 1); + + functionCode = finalFunctionCodeVal; + } + roleFunctionList = dataAccessService.getList(CentralRoleFunction.class, + " where app_id = " + app.getId() + AND_FUNCTION_CD_EQUALS + functionCode + "'", + null, null); + if (roleFunctionList.isEmpty()) { + roleFunctionList = dataAccessService.getList(CentralRoleFunction.class, + " where app_id = " + app.getId() + AND_FUNCTION_CD_EQUALS + code + "'", + null, null); + } + if (!roleFunctionList.isEmpty()) { + EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction(); + addAppRoleFunc.setAppId(app.getId()); + addAppRoleFunc.setCode(roleFunctionList.get(0).getCode()); + addAppRoleFunc.setRoleId(epRolesList.get(0).getId()); + dataAccessService.saveDomainObject(addAppRoleFunc, null); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ", + e); } } } @@ -1394,6 +1539,97 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } } + + /** + * + * Add function into local DB + * + * @param app + * @param permsDetail + * @param code + */ + private void addFunctionInEcompDB(EPApp app, ExternalAccessPermsDetail permsDetail, String code) { + try{ + CentralRoleFunction addFunction = new CentralRoleFunction(); + addFunction.setAppId(app.getId()); + addFunction.setCode(code); + addFunction.setName(permsDetail.getDescription()); + dataAccessService.saveDomainObject(addFunction, null); + } catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e); + } + } + + /** + * + * It updates description of a role in external auth system + * + * @param role + * @param app + * @throws Exception + */ + private void addIfRoleDescriptionNotExitsInExtSystem(Role role, EPApp app) throws Exception { + String addRoleNew = updateExistingRoleInExternalSystem(role, app); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + try { + HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", + HttpMethod.PUT, entity, String.class); + } catch (HttpClientErrorException e) { + logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addIfRoleDescriptionNotExitsInExtSystem", + e); + EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "addIfRoleDescriptionNotExitsInExtSystem: Failed", + e); + } + } + + /** + * + * While sync functions form external auth system if new role found we should add in local and return Role.class object + * + * @param app + * @param role + * @return + */ + @SuppressWarnings("unchecked") + private Role addRoleInDBIfDoesNotExists(EPApp app, String role) { + Role setNewRole = new Role(); + EPRole epRoleNew = new EPRole(); + try { + epRoleNew.setActive(true); + epRoleNew.setName(role); + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + epRoleNew.setAppId(null); + } else { + epRoleNew.setAppId(app.getId()); + } + dataAccessService.saveDomainObject(epRoleNew, null); + List<EPRole> getRoleCreated = null; + if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + List<EPRole> roleCreated = dataAccessService.getList(EPRole.class, + WHERE_ROLE_NAME_EQUALS + role + "' and app_id = " + app.getId(), null, null); + EPRole epUpdateRole = roleCreated.get(0); + epUpdateRole.setAppRoleId(epUpdateRole.getId()); + dataAccessService.saveDomainObject(epUpdateRole, null); + getRoleCreated = dataAccessService.getList(EPRole.class, + WHERE_ROLE_NAME_EQUALS + role + "' and app_id = " + app.getId(), null, null); + } else { + getRoleCreated = dataAccessService.getList(EPRole.class, + WHERE_ROLE_NAME_EQUALS + role + "' and app_id is null", null, null); + } + EPRole roleObject = getRoleCreated.get(0); + setNewRole.setId(roleObject.getId()); + setNewRole.setName(roleObject.getName()); + setNewRole.setActive(roleObject.getActive()); + setNewRole.setPriority(roleObject.getPriority()); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e); + } + return setNewRole; + } @Override @SuppressWarnings("unchecked") @@ -1610,28 +1846,27 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic ObjectMapper mapper = new ObjectMapper(); HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); HttpEntity<String> entity = new HttpEntity<>(headers); - logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} " , CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); + logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ", + CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE); response = template .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class); String res = response.getBody(); - logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :", + logger.debug(EELFLoggerDelegate.debugLogger, + "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :", res); JSONObject jsonObj = new JSONObject(res); JSONArray extRole = jsonObj.getJSONArray("role"); for (int i = 0; i < extRole.length(); i++) { - if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ".admin") - || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ".owner")) { + if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ADMIN) + || extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + OWNER) + || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(app.getNameSpace() + ACCOUNT_ADMINISTRATOR) + && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) { extRole.remove(i); i--; - } - if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && extRole.getJSONObject(i).get(ROLE_NAME) - .equals(app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"))) { - extRole.remove(i); - i--; - } + } } - List<EPAppRoleFunction> applicationRoleFunctionList = new ArrayList<>(); + dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, APP_ID_EQUALS + app.getId(), null); for (int i = 0; i < extRole.length(); i++) { ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails(); EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction(); @@ -1664,7 +1899,7 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic if (ApplicationRole.getActive().equals(IS_NULL_STRING)) { externalRoleDetail.setActive(false); } else { - externalRoleDetail.setActive(Boolean.parseBoolean(ApplicationRole.getActive().toString())); + externalRoleDetail.setActive(Boolean.parseBoolean(ApplicationRole.getActive())); } externalRoleDetail.setName(ApplicationRole.getName()); @@ -1673,13 +1908,13 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } else if (ApplicationRole.getAppId().equals(IS_NULL_STRING)) { externalRoleDetail.setAppId(app.getId()); } else { - externalRoleDetail.setAppId(Long.parseLong(ApplicationRole.getAppId().toString())); + externalRoleDetail.setAppId(Long.parseLong(ApplicationRole.getAppId())); } if (ApplicationRole.getPriority().equals(IS_NULL_STRING)) { externalRoleDetail.setPriority(null); } else { - externalRoleDetail.setPriority(Integer.parseInt(ApplicationRole.getPriority().toString())); + externalRoleDetail.setPriority(Integer.parseInt(ApplicationRole.getPriority())); } if (ApplicationRole.getAppRoleId().equals(IS_NULL_STRING) && app.getId() == 1) { @@ -1687,17 +1922,40 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } if (!externalAccessPermsOfRole.isEmpty()) { + // Adding functions to roles for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) { - EPAppRoleFunction apRoleFunction = new EPAppRoleFunction(); - apRoleFunction.setAppId(app.getId()); - apRoleFunction.setRoleId(Long.parseLong(ApplicationRole.getId())); - apRoleFunction.setCode(externalpermission.getInstance()); - applicationRoleFunctionList.add(apRoleFunction); + try { + logger.debug(EELFLoggerDelegate.debugLogger, + "SyncApplicationRolesWithEcompDB: Adding function to the role: {}", + externalpermission.getInstance()); + List<CentralRoleFunction> roleFunction = null; + roleFunction = dataAccessService.getList( + CentralRoleFunction.class, " where function_cd = '" + + externalpermission.getInstance() + "' and " + APP_ID_EQUALS + app.getId(), + null, null); + if (roleFunction.isEmpty()) { + String funcCode = externalpermission.getType() + .substring(app.getNameSpace().length() + 1) + FUNCTION_PIPE + + externalAccessPerms.getInstance(); + roleFunction = dataAccessService.getList(CentralRoleFunction.class, + " where function_cd = '" + funcCode + "' and " + APP_ID_EQUALS + app.getId(), null, + null); + } + if(!roleFunction.isEmpty()){ + EPAppRoleFunction apRoleFunction = new EPAppRoleFunction(); + apRoleFunction.setAppId(app.getId()); + apRoleFunction.setRoleId(Long.parseLong(ApplicationRole.getId())); + apRoleFunction.setCode(roleFunction.get(0).getCode()); + dataAccessService.saveDomainObject(apRoleFunction, null); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "SyncApplicationRolesWithEcompDB: Failed to add role function", e); + } } } externalRoleDetailsList.add(externalRoleDetail); } - for (ExternalRoleDetails externalRole : externalRoleDetailsList) { EPRole ecompRole = convertExternalRoleDetailstoEpRole(externalRole); finalRoleList.add(ecompRole); @@ -1717,32 +1975,37 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } } - // Check if roles exits in external Access system and make it - // inactive + // Check if roles exits in external Access system and make it inactive final Map<String, EPRole> checkRolesInactive = new HashMap<>(); for (EPRole extrole : finalRoleList) { checkRolesInactive.put(extrole.getName(), extrole); } for (EPRole role : applicationRolesList) { - final Map<String, String> extRoleParams = new HashMap<>(); - List<EPRole> roleList = new ArrayList<>(); - extRoleParams.put("appRoleName", role.getName()); - if (!checkRolesInactive.containsKey(role.getName())) { - if (app.getId() == 1) { - roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", extRoleParams, null); - } else { - extRoleParams.put(APP_ID, app.getId().toString()); - roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", extRoleParams, null); + try { + final Map<String, String> extRoleParams = new HashMap<>(); + List<EPRole> roleList = null; + extRoleParams.put("appRoleName", role.getName()); + if (!checkRolesInactive.containsKey(role.getName())) { + if (app.getId() == 1) { + roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", extRoleParams, null); + } else { + extRoleParams.put(APP_ID, app.getId().toString()); + roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", extRoleParams, null); + } + EPRole updateRoleInactive = roleList.get(0); + updateRoleInactive.setActive(false); + dataAccessService.saveDomainObject(updateRoleInactive, null); } - EPRole updateRoleInactive = roleList.get(0); - updateRoleInactive.setActive(false); - dataAccessService.saveDomainObject(updateRoleInactive, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e); } } + // It checks properties in the external auth system app role description and updates role in local for (EPRole roleItem : finalRoleList) { final Map<String, String> roleParams = new HashMap<>(); - List<EPRole> currentList = new ArrayList<>(); + List<EPRole> currentList = null; roleParams.put("appRoleName", roleItem.getName()); if (app.getId() == 1) { currentList = dataAccessService.executeNamedQuery("getPortalAppRoles", roleParams, null); @@ -1752,65 +2015,71 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } if (!currentList.isEmpty()) { - Boolean aafRoleActive; - Boolean localRoleActive; - boolean result; - aafRoleActive = Boolean.valueOf(roleItem.getActive()); - localRoleActive = Boolean.valueOf(currentList.get(0).getActive()); - result = aafRoleActive.equals(localRoleActive); - EPRole updateRole = currentList.get(0); - - if (!result) { - updateRole.setActive(roleItem.getActive()); - dataAccessService.saveDomainObject(updateRole, null); - } - if (roleItem.getPriority() != null - && !currentList.get(0).getPriority().equals(roleItem.getPriority())) { - updateRole.setPriority(roleItem.getPriority()); - dataAccessService.saveDomainObject(updateRole, null); + try { + Boolean aafRoleActive; + Boolean localRoleActive; + boolean result; + aafRoleActive = Boolean.valueOf(roleItem.getActive()); + localRoleActive = Boolean.valueOf(currentList.get(0).getActive()); + result = aafRoleActive.equals(localRoleActive); + EPRole updateRole = currentList.get(0); + + if (!result) { + updateRole.setActive(roleItem.getActive()); + dataAccessService.saveDomainObject(updateRole, null); + } + if (roleItem.getPriority() != null + && !currentList.get(0).getPriority().equals(roleItem.getPriority())) { + updateRole.setPriority(roleItem.getPriority()); + dataAccessService.saveDomainObject(updateRole, null); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "syncApplicationRolesWithEcompDB: Failed to update role ", e); } } } EPRole roleToBeAddedInEcompDB = new EPRole(); for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) { - roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i); - if (app.getId() == 1) { - roleToBeAddedInEcompDB.setAppRoleId(null); - } - dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null); - List<EPRole> getRoleCreatedInSync = null; - if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { - getRoleCreatedInSync = dataAccessService.getList(EPRole.class, - WHERE_ROLE_NAME_EQUALS + roleToBeAddedInEcompDB.getName() + "'", null, null); - EPRole epUpdateRole = getRoleCreatedInSync.get(0); - epUpdateRole.setAppRoleId(epUpdateRole.getId()); - dataAccessService.saveDomainObject(epUpdateRole, null); - } - List<EPRole> roleList = new ArrayList<>(); - final Map<String, String> params = new HashMap<>(); + try { + roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i); + if (app.getId() == 1) { + roleToBeAddedInEcompDB.setAppRoleId(null); + } + dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null); + List<EPRole> getRoleCreatedInSync = null; + if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + getRoleCreatedInSync = dataAccessService.getList(EPRole.class, + WHERE_ROLE_NAME_EQUALS + roleToBeAddedInEcompDB.getName() + "' and app_id = "+app.getId(), null, null); + EPRole epUpdateRole = getRoleCreatedInSync.get(0); + epUpdateRole.setAppRoleId(epUpdateRole.getId()); + dataAccessService.saveDomainObject(epUpdateRole, null); + } + List<EPRole> roleList = new ArrayList<>(); + final Map<String, String> params = new HashMap<>(); - params.put("appRoleName", roleToBeAddedInEcompDB.getName()); - if (app.getId() == 1) { - roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", params, null); - } else { - params.put(APP_ID, app.getId().toString()); - roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", params, null); + params.put("appRoleName", roleToBeAddedInEcompDB.getName()); + if (app.getId() == 1) { + roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", params, null); + } else { + params.put(APP_ID, app.getId().toString()); + roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", params, null); + } + EPRole role = roleList.get(0); + Role aaFrole = new Role(); + aaFrole.setId(role.getId()); + aaFrole.setActive(role.getActive()); + aaFrole.setPriority(role.getPriority()); + aaFrole.setName(role.getName()); + updateRoleInExternalSystem(aaFrole, app); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e); } - EPRole role = roleList.get(0); - Role aaFrole = new Role(); - aaFrole.setId(role.getId()); - aaFrole.setActive(role.getActive()); - aaFrole.setPriority(role.getPriority()); - aaFrole.setName(role.getName()); - updateRoleInExternalSystem(aaFrole, app); - } - dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, APP_ID_EQUALS + app.getId(), null); - for (EPAppRoleFunction rolefun : applicationRoleFunctionList) { - dataAccessService.saveDomainObject(rolefun, null); } logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished"); - } catch(HttpClientErrorException e){ + } catch (HttpClientErrorException e) { logger.error(EELFLoggerDelegate.errorLogger, "Failed to SyncApplicationRolesWithEcompDB", e); EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode()); } catch (Exception e) { @@ -1966,4 +2235,67 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } return appMenuFunctionsList; } + + @SuppressWarnings({ "unchecked"}) + @Override + public List<EcompUser> getAllAppUsers(String uebkey) throws Exception { + List<String> usersList = new ArrayList<>(); + List<EcompUser> usersfinalList = new ArrayList<>(); + try { + EPApp app = getApp(uebkey).get(0); + final Map<String, Long> appParams = new HashMap<>(); + appParams.put("appId", app.getId()); + List<EcompUserRoles> userList = (List<EcompUserRoles>) dataAccessService + .executeNamedQuery("ApplicationUserRoles", appParams, null); + for (EcompUserRoles ecompUserRole : userList) { + boolean found = false; + Set<EcompRole> roles = null; + for (EcompUser user : usersfinalList) { + if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) { + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(ecompUserRole.getRoleId()); + ecompRole.setName(ecompUserRole.getRoleName()); + roles = user.getRoles(); + roles.add(ecompRole); + user.setRoles(roles); + found = true; + break; + } + } + + if (!found) { + EcompUser epUser = new EcompUser(); + epUser.setOrgId(ecompUserRole.getOrgId()); + epUser.setManagerId(ecompUserRole.getManagerId()); + epUser.setFirstName(ecompUserRole.getFirstName()); + epUser.setLastName(ecompUserRole.getLastName()); + epUser.setPhone(ecompUserRole.getPhone()); + epUser.setEmail(ecompUserRole.getEmail()); + epUser.setOrgUserId(ecompUserRole.getOrgUserId()); + epUser.setOrgCode(ecompUserRole.getOrgCode()); + epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId()); + epUser.setJobTitle(ecompUserRole.getJobTitle()); + epUser.setLoginId(ecompUserRole.getLoginId()); + epUser.setActive(true); + roles = new HashSet<>(); + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(ecompUserRole.getRoleId()); + ecompRole.setName(ecompUserRole.getRoleName()); + roles.add(ecompRole); + epUser.setRoles(roles); + usersfinalList.add(epUser); + } + } + ObjectMapper mapper = new ObjectMapper(); + + for (EcompUser u1 : usersfinalList) { + String str = mapper.writeValueAsString(u1); + usersList.add(str); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e); + throw e; + } + return usersfinalList; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/FunctionalMenuServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/FunctionalMenuServiceImpl.java index 6a71bc71..87143e85 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/FunctionalMenuServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/FunctionalMenuServiceImpl.java @@ -284,7 +284,7 @@ public class FunctionalMenuServiceImpl implements FunctionalMenuService { logQuery(sql); @SuppressWarnings("unchecked") List<FunctionalMenuRole> roleItems = dataAccessService.executeSQLQuery(sql, FunctionalMenuRole.class, null); - if (roleItems.size() > 0) { + if (roleItems.size() > 0 && menuItem != null) { Integer appid = roleItems.get(0).appId; menuItem.appid = appid; List<Integer> roles = new ArrayList<Integer>(); diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminServiceImpl.java index 5979fe82..10490e73 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminServiceImpl.java @@ -144,7 +144,10 @@ public class PortalAdminServiceImpl implements PortalAdminService { transaction.commit(); // Add role in the external central auth system - result = addPortalAdminInExternalCentralAuth(user.getOrgUserId(), PortalConstants.PORTAL_ADMIN_ROLE); + if(user != null) + result = addPortalAdminInExternalCentralAuth(user.getOrgUserId(), PortalConstants.PORTAL_ADMIN_ROLE); + else + logger.error(EELFLoggerDelegate.errorLogger, "PortalAdminServiceImpl createPortalAdmin: failed to Add role in the external central auth system since User obj is null" ); } catch (Exception e) { EcompPortalUtils.rollbackTransaction(transaction, "createPortalAdmin rollback, exception = " + e); logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/TicketEventService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/TicketEventService.java new file mode 100644 index 00000000..1c9a735a --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/TicketEventService.java @@ -0,0 +1,9 @@ +package org.openecomp.portalapp.portal.service; + +import com.fasterxml.jackson.databind.JsonNode; + +public interface TicketEventService { + + public String getNotificationHyperLink(JsonNode application, String ticket, String eventSource); + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesCommonServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesCommonServiceImpl.java index d7aac633..0751c72e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesCommonServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesCommonServiceImpl.java @@ -58,6 +58,7 @@ import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; import org.openecomp.portalapp.portal.transport.AppWithRolesForUser; +import org.openecomp.portalapp.portal.transport.CentralRole; import org.openecomp.portalapp.portal.transport.EPUserAppCurrentRoles; import org.openecomp.portalapp.portal.transport.EcompUserAppRoles; import org.openecomp.portalapp.portal.transport.ExternalAccessUser; @@ -537,6 +538,7 @@ public class UserRolesCommonServiceImpl { externalAccessRolesService.deleteRoleDependencyRecords(localSession, roleId, appId); logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: about to delete the role: " + role.toString()); localSession.delete(role); + localSession.flush(); logger.debug(EELFLoggerDelegate.debugLogger, "syncAppRoles: deleted the role"); } } @@ -1292,7 +1294,7 @@ public class UserRolesCommonServiceImpl { } // Check if list contains just account admin role boolean checkIfAdminRoleExists = false; - if (reqType.equals("DELETE")) { + if (reqType.equals("DELETE") && userRoleList!=null) { checkIfAdminRoleExists = userRoleList.stream() .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)); } else { @@ -1307,10 +1309,10 @@ public class UserRolesCommonServiceImpl { if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !(checkIfAdminRoleExists && reqType.equals("DELETE")) && roleInAppForUserList.size() > 1) { EPUser remoteAppUser = null; - remoteAppUser = checkIfRemoteUserExits(userId.getOrgUserId(), app, + remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService); if (remoteAppUser == null) { - addRemoteUser(roleInAppForUserList, userId.getOrgUserId(), app, mapper, searchService, + addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService, applicationsRestClientService); reqMessage = "Saved Successfully"; } @@ -1342,9 +1344,9 @@ public class UserRolesCommonServiceImpl { // If adding just account admin role don't do remote application user call if(!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)){ EPUser remoteAppUser = null; - remoteAppUser = checkIfRemoteUserExits(userId.getOrgUserId(), app, applicationsRestClientService); + remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService); if (remoteAppUser == null) { - remoteAppUser = addRemoteUser(roleInAppForUserList, userId.getOrgUserId(), app, mapper, searchService, applicationsRestClientService); + remoteAppUser = addRemoteUser(roleInAppForUserList, orgUserId, app, mapper, searchService, applicationsRestClientService); reqMessage = "Saved Successfully"; } if (remoteAppUser != null) { @@ -1396,7 +1398,7 @@ public class UserRolesCommonServiceImpl { logger.error(EELFLoggerDelegate.errorLogger, message, e); result = false; reqMessage = e.getMessage(); - if(epRequestIdSize > 0 && !userInfo.isEmpty()){ + if(epRequestIdSize > 0 && userInfo!=null && !userInfo.isEmpty()){ updateStatus = "F"; applyChangesToAppRolesRequest(app.getId(), userId.getId(), updateStatus, epRequestId.get(0)); @@ -1525,9 +1527,21 @@ public class UserRolesCommonServiceImpl { EPApp app = appsService.getApp(appId); try { // for ecomp portal app, no need to make a remote call + List<Role> roleList = new ArrayList<>(); if (appId == PortalConstants.PORTAL_APP_ID) { - - List<Role> roleList = roleService.getAvailableRoles(userId); + if(app.getCentralAuth()){ + List<CentralRole> cenRoleList = externalAccessRolesService.getRolesForApp(app.getUebKey()); + for(CentralRole cenRole : cenRoleList){ + Role role = new Role(); + role.setActive(cenRole.isActive()); + role.setId(cenRole.getId()); + role.setName(cenRole.getName()); + role.setPriority(cenRole.getPriority()); + roleList.add(role); + } + }else{ + roleList = roleService.getAvailableRoles(userId); + } List<Role> activeRoleList = new ArrayList<Role>(); for(Role role: roleList) { if(role.getActive()) { @@ -1554,8 +1568,8 @@ public class UserRolesCommonServiceImpl { EcompRole[] appRoles = null; List<EcompRole> roles = new ArrayList<>(); if(app.getCentralAuth()){ - //Sync application roles from External Access System - externalAccessRolesService.syncApplicationRolesWithEcompDB(app); + //Sync application functions from External Access System + externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app); List<EPRole> applicationRoles = dataAccessService.getList(EPRole.class, " where app_id = "+app.getId()+ " and active_yn = 'Y'", null, null);; for(EPRole role : applicationRoles){ EcompRole ecompRole = new EcompRole(); @@ -1625,12 +1639,14 @@ public class UserRolesCommonServiceImpl { HashMap<Long, EcompRole> appRolesActiveMap =hashMapFromEcompRoles(appRoles); ArrayList<EcompRole> activeRoles = new ArrayList<EcompRole>(); - for (int i = 0; i < userAppRoles.length; i++) { - if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) { - EcompRole role = new EcompRole(); - role.setId(userAppRoles[i].getId()); - role.setName(userAppRoles[i].getName()); - activeRoles.add(role); + if(userAppRoles != null){ + for (int i = 0; i < userAppRoles.length; i++) { + if (appRolesActiveMap.containsKey(userAppRoles[i].getId())) { + EcompRole role = new EcompRole(); + role.setId(userAppRoles[i].getId()); + role.setName(userAppRoles[i].getName()); + activeRoles.add(role); + } } } EcompRole[] userAppRolesActive = activeRoles.toArray(new EcompRole[activeRoles.size()]); diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/Analytics.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/Analytics.java index 059999a4..b6e6c24f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/Analytics.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/Analytics.java @@ -27,7 +27,7 @@ public class Analytics { private String action; private String page; private String function; - private String userId; + private String userid; private String type; public String getType() { @@ -54,11 +54,11 @@ public class Analytics { public void setFunction(String function) { this.function = function; } - public String getUserId() { - return userId; + public String getUserid() { + return userid; } - public void setUserId(String userId) { - this.userId = userId; + public void setUserid(String userId) { + this.userid = userId; } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralApp.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralApp.java index 97907422..5a03bf56 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralApp.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralApp.java @@ -1,5 +1,6 @@ package org.openecomp.portalapp.portal.transport; +import java.util.Arrays; import java.util.Date; public class CentralApp { @@ -205,6 +206,166 @@ public class CentralApp { public void setUebTopicName(String uebTopicName) { this.uebTopicName = uebTopicName; } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((alternateUrl == null) ? 0 : alternateUrl.hashCode()); + result = prime * result + ((appPassword == null) ? 0 : appPassword.hashCode()); + result = prime * result + ((created == null) ? 0 : created.hashCode()); + result = prime * result + ((createdId == null) ? 0 : createdId.hashCode()); + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((enabled == null) ? 0 : enabled.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((imageUrl == null) ? 0 : imageUrl.hashCode()); + result = prime * result + ((mlAppAdminId == null) ? 0 : mlAppAdminId.hashCode()); + result = prime * result + ((mlAppName == null) ? 0 : mlAppName.hashCode()); + result = prime * result + ((modified == null) ? 0 : modified.hashCode()); + result = prime * result + ((modifiedId == null) ? 0 : modifiedId.hashCode()); + result = prime * result + ((motsId == null) ? 0 : motsId.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((notes == null) ? 0 : notes.hashCode()); + result = prime * result + ((open == null) ? 0 : open.hashCode()); + result = prime * result + ((restEndpoint == null) ? 0 : restEndpoint.hashCode()); + result = prime * result + ((rowNum == null) ? 0 : rowNum.hashCode()); + result = prime * result + Arrays.hashCode(thumbnail); + result = prime * result + ((uebKey == null) ? 0 : uebKey.hashCode()); + result = prime * result + ((uebSecret == null) ? 0 : uebSecret.hashCode()); + result = prime * result + ((uebTopicName == null) ? 0 : uebTopicName.hashCode()); + result = prime * result + ((url == null) ? 0 : url.hashCode()); + result = prime * result + ((username == null) ? 0 : username.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + CentralApp other = (CentralApp) obj; + if (alternateUrl == null) { + if (other.alternateUrl != null) + return false; + } else if (!alternateUrl.equals(other.alternateUrl)) + return false; + if (appPassword == null) { + if (other.appPassword != null) + return false; + } else if (!appPassword.equals(other.appPassword)) + return false; + if (created == null) { + if (other.created != null) + return false; + } else if (!created.equals(other.created)) + return false; + if (createdId == null) { + if (other.createdId != null) + return false; + } else if (!createdId.equals(other.createdId)) + return false; + if (description == null) { + if (other.description != null) + return false; + } else if (!description.equals(other.description)) + return false; + if (enabled == null) { + if (other.enabled != null) + return false; + } else if (!enabled.equals(other.enabled)) + return false; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (imageUrl == null) { + if (other.imageUrl != null) + return false; + } else if (!imageUrl.equals(other.imageUrl)) + return false; + if (mlAppAdminId == null) { + if (other.mlAppAdminId != null) + return false; + } else if (!mlAppAdminId.equals(other.mlAppAdminId)) + return false; + if (mlAppName == null) { + if (other.mlAppName != null) + return false; + } else if (!mlAppName.equals(other.mlAppName)) + return false; + if (modified == null) { + if (other.modified != null) + return false; + } else if (!modified.equals(other.modified)) + return false; + if (modifiedId == null) { + if (other.modifiedId != null) + return false; + } else if (!modifiedId.equals(other.modifiedId)) + return false; + if (motsId == null) { + if (other.motsId != null) + return false; + } else if (!motsId.equals(other.motsId)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (notes == null) { + if (other.notes != null) + return false; + } else if (!notes.equals(other.notes)) + return false; + if (open == null) { + if (other.open != null) + return false; + } else if (!open.equals(other.open)) + return false; + if (restEndpoint == null) { + if (other.restEndpoint != null) + return false; + } else if (!restEndpoint.equals(other.restEndpoint)) + return false; + if (rowNum == null) { + if (other.rowNum != null) + return false; + } else if (!rowNum.equals(other.rowNum)) + return false; + if (!Arrays.equals(thumbnail, other.thumbnail)) + return false; + if (uebKey == null) { + if (other.uebKey != null) + return false; + } else if (!uebKey.equals(other.uebKey)) + return false; + if (uebSecret == null) { + if (other.uebSecret != null) + return false; + } else if (!uebSecret.equals(other.uebSecret)) + return false; + if (uebTopicName == null) { + if (other.uebTopicName != null) + return false; + } else if (!uebTopicName.equals(other.uebTopicName)) + return false; + if (url == null) { + if (other.url != null) + return false; + } else if (!url.equals(other.url)) + return false; + if (username == null) { + if (other.username != null) + return false; + } else if (!username.equals(other.username)) + return false; + return true; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralRole.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralRole.java index a3c3c9d5..de576ad7 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralRole.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralRole.java @@ -156,4 +156,92 @@ public class CentralRole implements Comparable{ return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (active ? 1231 : 1237); + result = prime * result + ((childRoles == null) ? 0 : childRoles.hashCode()); + result = prime * result + ((created == null) ? 0 : created.hashCode()); + result = prime * result + ((createdId == null) ? 0 : createdId.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((modified == null) ? 0 : modified.hashCode()); + result = prime * result + ((modifiedId == null) ? 0 : modifiedId.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((parentRoles == null) ? 0 : parentRoles.hashCode()); + result = prime * result + ((priority == null) ? 0 : priority.hashCode()); + result = prime * result + ((roleFunctions == null) ? 0 : roleFunctions.hashCode()); + result = prime * result + ((rowNum == null) ? 0 : rowNum.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + CentralRole other = (CentralRole) obj; + if (active != other.active) + return false; + if (childRoles == null) { + if (other.childRoles != null) + return false; + } else if (!childRoles.equals(other.childRoles)) + return false; + if (created == null) { + if (other.created != null) + return false; + } else if (!created.equals(other.created)) + return false; + if (createdId == null) { + if (other.createdId != null) + return false; + } else if (!createdId.equals(other.createdId)) + return false; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (modified == null) { + if (other.modified != null) + return false; + } else if (!modified.equals(other.modified)) + return false; + if (modifiedId == null) { + if (other.modifiedId != null) + return false; + } else if (!modifiedId.equals(other.modifiedId)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (parentRoles == null) { + if (other.parentRoles != null) + return false; + } else if (!parentRoles.equals(other.parentRoles)) + return false; + if (priority == null) { + if (other.priority != null) + return false; + } else if (!priority.equals(other.priority)) + return false; + if (roleFunctions == null) { + if (other.roleFunctions != null) + return false; + } else if (!roleFunctions.equals(other.roleFunctions)) + return false; + if (rowNum == null) { + if (other.rowNum != null) + return false; + } else if (!rowNum.equals(other.rowNum)) + return false; + return true; + } + } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralUser.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralUser.java index f8174825..b44e25d3 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralUser.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralUser.java @@ -132,6 +132,334 @@ public class CentralUser { this.userApps = userApps; this.pseudoRoles = pseudoRoles; } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (active ? 1231 : 1237); + result = prime * result + ((address1 == null) ? 0 : address1.hashCode()); + result = prime * result + ((address2 == null) ? 0 : address2.hashCode()); + result = prime * result + ((addressId == null) ? 0 : addressId.hashCode()); + result = prime * result + ((alertMethodCd == null) ? 0 : alertMethodCd.hashCode()); + result = prime * result + ((businessCountryCode == null) ? 0 : businessCountryCode.hashCode()); + result = prime * result + ((businessCountryName == null) ? 0 : businessCountryName.hashCode()); + result = prime * result + ((businessUnit == null) ? 0 : businessUnit.hashCode()); + result = prime * result + ((businessUnitName == null) ? 0 : businessUnitName.hashCode()); + result = prime * result + ((cellular == null) ? 0 : cellular.hashCode()); + result = prime * result + ((chatId == null) ? 0 : chatId.hashCode()); + result = prime * result + ((city == null) ? 0 : city.hashCode()); + result = prime * result + ((commandChain == null) ? 0 : commandChain.hashCode()); + result = prime * result + ((company == null) ? 0 : company.hashCode()); + result = prime * result + ((companyCode == null) ? 0 : companyCode.hashCode()); + result = prime * result + ((costCenter == null) ? 0 : costCenter.hashCode()); + result = prime * result + ((country == null) ? 0 : country.hashCode()); + result = prime * result + ((created == null) ? 0 : created.hashCode()); + result = prime * result + ((createdId == null) ? 0 : createdId.hashCode()); + result = prime * result + ((department == null) ? 0 : department.hashCode()); + result = prime * result + ((departmentName == null) ? 0 : departmentName.hashCode()); + result = prime * result + ((email == null) ? 0 : email.hashCode()); + result = prime * result + ((fax == null) ? 0 : fax.hashCode()); + result = prime * result + ((financialLocCode == null) ? 0 : financialLocCode.hashCode()); + result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); + result = prime * result + ((hrid == null) ? 0 : hrid.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + (internal ? 1231 : 1237); + result = prime * result + ((jobTitle == null) ? 0 : jobTitle.hashCode()); + result = prime * result + ((lastLoginDate == null) ? 0 : lastLoginDate.hashCode()); + result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); + result = prime * result + ((locationClli == null) ? 0 : locationClli.hashCode()); + result = prime * result + ((loginId == null) ? 0 : loginId.hashCode()); + result = prime * result + ((loginPwd == null) ? 0 : loginPwd.hashCode()); + result = prime * result + ((managerId == null) ? 0 : managerId.hashCode()); + result = prime * result + ((middleInitial == null) ? 0 : middleInitial.hashCode()); + result = prime * result + ((modified == null) ? 0 : modified.hashCode()); + result = prime * result + ((modifiedId == null) ? 0 : modifiedId.hashCode()); + result = prime * result + (online ? 1231 : 1237); + result = prime * result + ((orgCode == null) ? 0 : orgCode.hashCode()); + result = prime * result + ((orgId == null) ? 0 : orgId.hashCode()); + result = prime * result + ((orgManagerUserId == null) ? 0 : orgManagerUserId.hashCode()); + result = prime * result + ((orgUserId == null) ? 0 : orgUserId.hashCode()); + result = prime * result + ((phone == null) ? 0 : phone.hashCode()); + result = prime * result + ((pseudoRoles == null) ? 0 : pseudoRoles.hashCode()); + result = prime * result + ((rowNum == null) ? 0 : rowNum.hashCode()); + result = prime * result + ((selectedProfileId == null) ? 0 : selectedProfileId.hashCode()); + result = prime * result + ((siloStatus == null) ? 0 : siloStatus.hashCode()); + result = prime * result + ((state == null) ? 0 : state.hashCode()); + result = prime * result + ((timeZoneId == null) ? 0 : timeZoneId.hashCode()); + result = prime * result + ((userApps == null) ? 0 : userApps.hashCode()); + result = prime * result + ((zipCode == null) ? 0 : zipCode.hashCode()); + result = prime * result + ((zipCodeSuffix == null) ? 0 : zipCodeSuffix.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + CentralUser other = (CentralUser) obj; + if (active != other.active) + return false; + if (address1 == null) { + if (other.address1 != null) + return false; + } else if (!address1.equals(other.address1)) + return false; + if (address2 == null) { + if (other.address2 != null) + return false; + } else if (!address2.equals(other.address2)) + return false; + if (addressId == null) { + if (other.addressId != null) + return false; + } else if (!addressId.equals(other.addressId)) + return false; + if (alertMethodCd == null) { + if (other.alertMethodCd != null) + return false; + } else if (!alertMethodCd.equals(other.alertMethodCd)) + return false; + if (businessCountryCode == null) { + if (other.businessCountryCode != null) + return false; + } else if (!businessCountryCode.equals(other.businessCountryCode)) + return false; + if (businessCountryName == null) { + if (other.businessCountryName != null) + return false; + } else if (!businessCountryName.equals(other.businessCountryName)) + return false; + if (businessUnit == null) { + if (other.businessUnit != null) + return false; + } else if (!businessUnit.equals(other.businessUnit)) + return false; + if (businessUnitName == null) { + if (other.businessUnitName != null) + return false; + } else if (!businessUnitName.equals(other.businessUnitName)) + return false; + if (cellular == null) { + if (other.cellular != null) + return false; + } else if (!cellular.equals(other.cellular)) + return false; + if (chatId == null) { + if (other.chatId != null) + return false; + } else if (!chatId.equals(other.chatId)) + return false; + if (city == null) { + if (other.city != null) + return false; + } else if (!city.equals(other.city)) + return false; + if (commandChain == null) { + if (other.commandChain != null) + return false; + } else if (!commandChain.equals(other.commandChain)) + return false; + if (company == null) { + if (other.company != null) + return false; + } else if (!company.equals(other.company)) + return false; + if (companyCode == null) { + if (other.companyCode != null) + return false; + } else if (!companyCode.equals(other.companyCode)) + return false; + if (costCenter == null) { + if (other.costCenter != null) + return false; + } else if (!costCenter.equals(other.costCenter)) + return false; + if (country == null) { + if (other.country != null) + return false; + } else if (!country.equals(other.country)) + return false; + if (created == null) { + if (other.created != null) + return false; + } else if (!created.equals(other.created)) + return false; + if (createdId == null) { + if (other.createdId != null) + return false; + } else if (!createdId.equals(other.createdId)) + return false; + if (department == null) { + if (other.department != null) + return false; + } else if (!department.equals(other.department)) + return false; + if (departmentName == null) { + if (other.departmentName != null) + return false; + } else if (!departmentName.equals(other.departmentName)) + return false; + if (email == null) { + if (other.email != null) + return false; + } else if (!email.equals(other.email)) + return false; + if (fax == null) { + if (other.fax != null) + return false; + } else if (!fax.equals(other.fax)) + return false; + if (financialLocCode == null) { + if (other.financialLocCode != null) + return false; + } else if (!financialLocCode.equals(other.financialLocCode)) + return false; + if (firstName == null) { + if (other.firstName != null) + return false; + } else if (!firstName.equals(other.firstName)) + return false; + if (hrid == null) { + if (other.hrid != null) + return false; + } else if (!hrid.equals(other.hrid)) + return false; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (internal != other.internal) + return false; + if (jobTitle == null) { + if (other.jobTitle != null) + return false; + } else if (!jobTitle.equals(other.jobTitle)) + return false; + if (lastLoginDate == null) { + if (other.lastLoginDate != null) + return false; + } else if (!lastLoginDate.equals(other.lastLoginDate)) + return false; + if (lastName == null) { + if (other.lastName != null) + return false; + } else if (!lastName.equals(other.lastName)) + return false; + if (locationClli == null) { + if (other.locationClli != null) + return false; + } else if (!locationClli.equals(other.locationClli)) + return false; + if (loginId == null) { + if (other.loginId != null) + return false; + } else if (!loginId.equals(other.loginId)) + return false; + if (loginPwd == null) { + if (other.loginPwd != null) + return false; + } else if (!loginPwd.equals(other.loginPwd)) + return false; + if (managerId == null) { + if (other.managerId != null) + return false; + } else if (!managerId.equals(other.managerId)) + return false; + if (middleInitial == null) { + if (other.middleInitial != null) + return false; + } else if (!middleInitial.equals(other.middleInitial)) + return false; + if (modified == null) { + if (other.modified != null) + return false; + } else if (!modified.equals(other.modified)) + return false; + if (modifiedId == null) { + if (other.modifiedId != null) + return false; + } else if (!modifiedId.equals(other.modifiedId)) + return false; + if (online != other.online) + return false; + if (orgCode == null) { + if (other.orgCode != null) + return false; + } else if (!orgCode.equals(other.orgCode)) + return false; + if (orgId == null) { + if (other.orgId != null) + return false; + } else if (!orgId.equals(other.orgId)) + return false; + if (orgManagerUserId == null) { + if (other.orgManagerUserId != null) + return false; + } else if (!orgManagerUserId.equals(other.orgManagerUserId)) + return false; + if (orgUserId == null) { + if (other.orgUserId != null) + return false; + } else if (!orgUserId.equals(other.orgUserId)) + return false; + if (phone == null) { + if (other.phone != null) + return false; + } else if (!phone.equals(other.phone)) + return false; + if (pseudoRoles == null) { + if (other.pseudoRoles != null) + return false; + } else if (!pseudoRoles.equals(other.pseudoRoles)) + return false; + if (rowNum == null) { + if (other.rowNum != null) + return false; + } else if (!rowNum.equals(other.rowNum)) + return false; + if (selectedProfileId == null) { + if (other.selectedProfileId != null) + return false; + } else if (!selectedProfileId.equals(other.selectedProfileId)) + return false; + if (siloStatus == null) { + if (other.siloStatus != null) + return false; + } else if (!siloStatus.equals(other.siloStatus)) + return false; + if (state == null) { + if (other.state != null) + return false; + } else if (!state.equals(other.state)) + return false; + if (timeZoneId == null) { + if (other.timeZoneId != null) + return false; + } else if (!timeZoneId.equals(other.timeZoneId)) + return false; + if (userApps == null) { + if (other.userApps != null) + return false; + } else if (!userApps.equals(other.userApps)) + return false; + if (zipCode == null) { + if (other.zipCode != null) + return false; + } else if (!zipCode.equals(other.zipCode)) + return false; + if (zipCodeSuffix == null) { + if (other.zipCodeSuffix != null) + return false; + } else if (!zipCodeSuffix.equals(other.zipCodeSuffix)) + return false; + return true; + } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CommonWidget.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CommonWidget.java index ceb5d46d..5be1fb70 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CommonWidget.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CommonWidget.java @@ -31,7 +31,6 @@ import com.fasterxml.jackson.annotation.JsonInclude; /** * This is to handle portal admins - * @author aw3218 */ @Entity @Table(name="fn_common_widget_data") diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EcompUserRoles.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EcompUserRoles.java new file mode 100644 index 00000000..50c14ca8 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EcompUserRoles.java @@ -0,0 +1,172 @@ +package org.openecomp.portalapp.portal.transport; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class EcompUserRoles implements Serializable{ + + private static final long serialVersionUID = 1L; + + @Id + @Column(name = "org_id") + private Long orgId; + @Id + @Column(name = "manager_id") + private String managerId; + @Id + @Column(name = "first_name") + private String firstName; + @Id + @Column(name = "middle_name") + private String middleInitial; + @Id + @Column(name = "last_name") + private String lastName; + @Id + @Column(name = "phone") + private String phone; + @Id + @Column(name = "email") + private String email; + @Id + @Column(name = "hrid") + private String hrid; + @Id + @Column(name = "org_user_id") + private String orgUserId; + @Id + @Column(name = "org_code") + private String orgCode; + @Id + @Column(name = "org_manager_userid") + private String orgManagerUserId; + @Id + @Column(name = "job_title") + private String jobTitle; + @Id + @Column(name = "login_id") + private String loginId; + + @Id + @Column(name = "app_role_id") + private Long roleId; + @Id + @Column(name = "role_name") + private String roleName; + @Id + @Column(name = "active_yn") + private boolean active; + + public Long getOrgId() { + return orgId; + } + public void setOrgId(Long orgId) { + this.orgId = orgId; + } + public String getManagerId() { + return managerId; + } + public void setManagerId(String managerId) { + this.managerId = managerId; + } + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + public String getMiddleInitial() { + return middleInitial; + } + public void setMiddleInitial(String middleInitial) { + this.middleInitial = middleInitial; + } + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + public String getHrid() { + return hrid; + } + public void setHrid(String hrid) { + this.hrid = hrid; + } + public String getOrgUserId() { + return orgUserId; + } + public void setOrgUserId(String orgUserId) { + this.orgUserId = orgUserId; + } + public String getOrgCode() { + return orgCode; + } + public void setOrgCode(String orgCode) { + this.orgCode = orgCode; + } + public String getOrgManagerUserId() { + return orgManagerUserId; + } + public void setOrgManagerUserId(String orgManagerUserId) { + this.orgManagerUserId = orgManagerUserId; + } + public String getJobTitle() { + return jobTitle; + } + public void setJobTitle(String jobTitle) { + this.jobTitle = jobTitle; + } + public String getLoginId() { + return loginId; + } + public void setLoginId(String loginId) { + this.loginId = loginId; + } + + public Long getRoleId() { + return roleId; + } + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + public String getRoleName() { + return roleName; + } + public void setRoleName(String roleName) { + this.roleName = roleName; + } + + public boolean isActive() { + return active; + } + public void setActive(boolean active) { + this.active = active; + } + @Override + public String toString() { + return "EcompUserRoles [orgId=" + orgId + ", managerId=" + managerId + ", firstName=" + firstName + + ", middleInitial=" + middleInitial + ", lastName=" + lastName + ", phone=" + phone + ", email=" + + email + ", hrid=" + hrid + ", orgUserId=" + orgUserId + ", orgCode=" + orgCode + ", orgManagerUserId=" + + orgManagerUserId + ", jobTitle=" + jobTitle + ", loginId=" + loginId + ", active=" + active + + ", roleId=" + roleId + ", roleName=" + roleName + "]"; + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessPerms.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessPerms.java index 60f9f63a..27d0dd0b 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessPerms.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessPerms.java @@ -91,6 +91,53 @@ public class ExternalAccessPerms implements Serializable, Comparable{ return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); } + + + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((action == null) ? 0 : action.hashCode()); + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((instance == null) ? 0 : instance.hashCode()); + result = prime * result + ((type == null) ? 0 : type.hashCode()); + return result; + } + + + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ExternalAccessPerms other = (ExternalAccessPerms) obj; + if (action == null) { + if (other.action != null) + return false; + } else if (!action.equals(other.action)) + return false; + if (description == null) { + if (other.description != null) + return false; + } else if (!description.equals(other.description)) + return false; + if (instance == null) { + if (other.instance != null) + return false; + } else if (!instance.equals(other.instance)) + return false; + if (type == null) { + if (other.type != null) + return false; + } else if (!type.equals(other.type)) + return false; + return true; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessUserRoleDetail.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessUserRoleDetail.java index e5d89e22..1a8aeb64 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessUserRoleDetail.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessUserRoleDetail.java @@ -31,6 +31,37 @@ public class ExternalAccessUserRoleDetail { public void setDescription(ExternalRoleDescription description) { this.description = description; } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ExternalAccessUserRoleDetail other = (ExternalAccessUserRoleDetail) obj; + if (description == null) { + if (other.description != null) + return false; + } else if (!description.equals(other.description)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalRoleDescription.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalRoleDescription.java index d6eba633..824dc5b2 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalRoleDescription.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalRoleDescription.java @@ -45,6 +45,59 @@ public class ExternalRoleDescription { public void setAppRoleId(String appRoleId) { this.appRoleId = appRoleId; } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((active == null) ? 0 : active.hashCode()); + result = prime * result + ((appId == null) ? 0 : appId.hashCode()); + result = prime * result + ((appRoleId == null) ? 0 : appRoleId.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((priority == null) ? 0 : priority.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ExternalRoleDescription other = (ExternalRoleDescription) obj; + if (active == null) { + if (other.active != null) + return false; + } else if (!active.equals(other.active)) + return false; + if (appId == null) { + if (other.appId != null) + return false; + } else if (!appId.equals(other.appId)) + return false; + if (appRoleId == null) { + if (other.appRoleId != null) + return false; + } else if (!appRoleId.equals(other.appRoleId)) + return false; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (priority == null) { + if (other.priority != null) + return false; + } else if (!priority.equals(other.priority)) + return false; + return true; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/RemoteRole.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/RemoteRole.java index 8a2d6232..74dbd1ab 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/RemoteRole.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/RemoteRole.java @@ -41,4 +41,33 @@ public class RemoteRole { public String toString() { return "RemoteRole [id=" + id + ", name=" + name + "]"; } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + RemoteRole other = (RemoteRole) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/UserWithNameSurnameTitle.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/UserWithNameSurnameTitle.java index ba411e65..bcd6595c 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/UserWithNameSurnameTitle.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/UserWithNameSurnameTitle.java @@ -36,4 +36,47 @@ public class UserWithNameSurnameTitle { this.jobTitle = jobTitle; } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); + result = prime * result + ((jobTitle == null) ? 0 : jobTitle.hashCode()); + result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); + result = prime * result + ((orgUserId == null) ? 0 : orgUserId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + UserWithNameSurnameTitle other = (UserWithNameSurnameTitle) obj; + if (firstName == null) { + if (other.firstName != null) + return false; + } else if (!firstName.equals(other.firstName)) + return false; + if (jobTitle == null) { + if (other.jobTitle != null) + return false; + } else if (!jobTitle.equals(other.jobTitle)) + return false; + if (lastName == null) { + if (other.lastName != null) + return false; + } else if (!lastName.equals(other.lastName)) + return false; + if (orgUserId == null) { + if (other.orgUserId != null) + return false; + } else if (!orgUserId.equals(other.orgUserId)) + return false; + return true; + } + } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java index a80517d2..55137cbf 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java @@ -134,9 +134,8 @@ public class EPUebHelper { refreshPublisherList(); } }; - if (thread != null) { - thread.start(); - } + thread.start(); + } @EPMetricsLog diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/service/sessionmgt/SessionCommunication.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/service/sessionmgt/SessionCommunication.java index 11c0890e..2bdd0ca8 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/service/sessionmgt/SessionCommunication.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/service/sessionmgt/SessionCommunication.java @@ -54,56 +54,57 @@ public class SessionCommunication { String appResponse = ""; String appName = "Unknwon"; int responseCode = 0; - - try { - if (app != null && app.name != null && app.name != "") { - appName = app.name; - } - String url = app.restUrl + "/sessionTimeOuts"; - String encriptedPwdDB = app.appPassword; - String appUserName = app.username; - - setLocalMDCContext(app, "/sessionTimeOuts", url); - - URL obj = new URL(url); - - HttpURLConnection con = (HttpURLConnection) obj.openConnection(); - - // optional default is GET - con.setRequestMethod("GET"); - con.setConnectTimeout(3000); - con.setReadTimeout(8000); - // add request header - con.setRequestProperty("username", appUserName); - con.setRequestProperty("password", encriptedPwdDB); - - // con.set - responseCode = con.getResponseCode(); - logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode); - - BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); - String inputLine; - StringBuffer response = new StringBuffer(); - - while ((inputLine = in.readLine()) != null) { - response.append(inputLine); + if (app != null && app.name != null && app.name != "") { + try { + appName = app.name; + String url = app.restUrl + "/sessionTimeOuts"; + String encriptedPwdDB = app.appPassword; + String appUserName = app.username; + + setLocalMDCContext(app, "/sessionTimeOuts", url); + + URL obj = new URL(url); + + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + // optional default is GET + con.setRequestMethod("GET"); + con.setConnectTimeout(3000); + con.setReadTimeout(8000); + // add request header + con.setRequestProperty("username", appUserName); + con.setRequestProperty("password", encriptedPwdDB); + + // con.set + responseCode = con.getResponseCode(); + logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode); + + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + StringBuffer response = new StringBuffer(); + + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + + in.close(); + appResponse = response.toString(); + } catch (UrlAccessRestrictedException e) { + responseCode = HttpServletResponse.SC_UNAUTHORIZED; + logger.error(EELFLoggerDelegate.errorLogger, String.format("SessionCommunication.sendGet received an un-authorized exception. AppName: %s", appName)); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e); + } catch (Exception e) { + responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; + String message = String.format( + "SessionCommunication.sendGet encountered an Exception. AppName: %s, Details: %s", appName, + EcompPortalUtils.getStackTrace(e)); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e); + logger.error(EELFLoggerDelegate.errorLogger, message); + } finally { + EcompPortalUtils.setExternalAppResponseCode(responseCode); } - - in.close(); - appResponse = response.toString(); - } catch (UrlAccessRestrictedException e) { - responseCode = HttpServletResponse.SC_UNAUTHORIZED; - logger.error(EELFLoggerDelegate.errorLogger, String.format("SessionCommunication.sendGet received an un-authorized exception. AppName: %s", appName)); - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e); - } catch (Exception e) { - responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; - String message = String.format( - "SessionCommunication.sendGet encountered an Exception. AppName: %s, Details: %s", appName, - EcompPortalUtils.getStackTrace(e)); - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e); - logger.error(EELFLoggerDelegate.errorLogger, message); - } finally { - EcompPortalUtils.setExternalAppResponseCode(responseCode); + }else{ + logger.error(EELFLoggerDelegate.errorLogger, "SessionCommunication sendGet: app is null"); } return appResponse; } @@ -113,10 +114,11 @@ public class SessionCommunication { String appName = "Unknwon"; int responseCode = 0; try { + if(app==null) + throw new Exception("SessionCommunication.pingSession app is null"); if (app != null && app.name != null && app.name != "") { appName = app.name; } - String url = app.restUrl + "/updateSessionTimeOuts"; String encriptedPwdDB = app.appPassword; String appUserName = app.username; @@ -171,55 +173,56 @@ public class SessionCommunication { public Boolean timeoutSession(OnboardingApp app, String portalJSessionId) throws Exception { String appName = "Unknwon"; int responseCode = 0; - try { - if (app != null && app.name != null && app.name != "") { + if (app != null && app.name != null && app.name != "") { + try { appName = app.name; + String url = app.restUrl + "/timeoutSession" + "?portalJSessionId=" + portalJSessionId; + + String encriptedPwdDB = app.appPassword; + String appUserName = app.username; + // String decreptedPwd = CipherUtil.decrypt(encriptedPwdDB, + // SystemProperties.getProperty(SystemProperties.Decryption_Key)); + + setLocalMDCContext(app, "/timeoutSession", url); + + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + // optional default is GET + con.setRequestMethod("POST"); + con.setConnectTimeout(3000); + con.setReadTimeout(15000); + + // add request header + con.setRequestProperty("username", appUserName); + con.setRequestProperty("password", encriptedPwdDB); + + // con.setRequestProperty("portalJSessionId", portalJSessionId); + con.setDoInput(true); + con.setDoOutput(true); + con.getOutputStream().flush(); + con.getOutputStream().close(); + + responseCode = con.getResponseCode(); + logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode); + } catch (UrlAccessRestrictedException e) { + responseCode = HttpServletResponse.SC_UNAUTHORIZED; + String message = String.format( + "SessionCommunication.timeoutSession received an un-authorized exception. AppName: %s", appName); + logger.error(EELFLoggerDelegate.errorLogger, message); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e); + } catch (Exception e) { + responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; + String message = String.format( + "SessionCommunication.timeoutSession encountered an Exception. AppName: %s, Details: %s", appName, + EcompPortalUtils.getStackTrace(e)); + EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e); + logger.error(EELFLoggerDelegate.errorLogger, message); + } finally { + EcompPortalUtils.setExternalAppResponseCode(responseCode); } - - String url = app.restUrl + "/timeoutSession" + "?portalJSessionId=" + portalJSessionId; - - String encriptedPwdDB = app.appPassword; - String appUserName = app.username; - // String decreptedPwd = CipherUtil.decrypt(encriptedPwdDB, - // SystemProperties.getProperty(SystemProperties.Decryption_Key)); - - setLocalMDCContext(app, "/timeoutSession", url); - - URL obj = new URL(url); - HttpURLConnection con = (HttpURLConnection) obj.openConnection(); - - // optional default is GET - con.setRequestMethod("POST"); - con.setConnectTimeout(3000); - con.setReadTimeout(15000); - - // add request header - con.setRequestProperty("username", appUserName); - con.setRequestProperty("password", encriptedPwdDB); - - // con.setRequestProperty("portalJSessionId", portalJSessionId); - con.setDoInput(true); - con.setDoOutput(true); - con.getOutputStream().flush(); - con.getOutputStream().close(); - - responseCode = con.getResponseCode(); - logger.debug(EELFLoggerDelegate.debugLogger, "Response Code : " + responseCode); - } catch (UrlAccessRestrictedException e) { - responseCode = HttpServletResponse.SC_UNAUTHORIZED; - String message = String.format( - "SessionCommunication.timeoutSession received an un-authorized exception. AppName: %s", appName); - logger.error(EELFLoggerDelegate.errorLogger, message); - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e); - } catch (Exception e) { - responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; - String message = String.format( - "SessionCommunication.timeoutSession encountered an Exception. AppName: %s, Details: %s", appName, - EcompPortalUtils.getStackTrace(e)); - EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeHttpConnectionError, e); - logger.error(EELFLoggerDelegate.errorLogger, message); - } finally { - EcompPortalUtils.setExternalAppResponseCode(responseCode); + }else{ + logger.error(EELFLoggerDelegate.errorLogger, "SessionCommunication pingSession: app is null"); } return true; } diff --git a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml index 1574a9a2..5526670a 100644 --- a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml +++ b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml @@ -371,7 +371,7 @@ </class> <!-- User Role class mapping details --> - <class name="EPRole" table="FN_ROLE"> + <class name="EPRole" table="FN_ROLE" > <id name="id" column="role_id"> <generator class="native"> <param name="sequence">seq_fn_role</param> @@ -1800,22 +1800,11 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' and fn_role.active_y class="org.openecomp.portalapp.portal.domain.CentralRoleFunction" /> <![CDATA[ - SELECT * from ep_app_function where function_cd = :functionCode and app_id =:appId + SELECT * from ep_app_function where function_cd like CONCAT('%', :functionCode,'%') and app_id =:appId ; ]]> </sql-query> - - <!-- Gets the record from ep_app_function table and requires two parameters --> - <sql-query name="getAppFunctionDetails"> - <return alias="appFunctionDetails" - class="org.openecomp.portalapp.portal.domain.CentralRoleFunction" /> - <![CDATA[ - - select * from ep_app_function where app_id =:appId and function_cd =:functionCd - ; - ]]> - </sql-query> <!-- Gets the current user app roles records and requires two parameters --> <sql-query name="getUserAppCurrentRoles"> @@ -1940,4 +1929,18 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' and fn_role.active_y ]]> </sql-query> + <sql-query name="ApplicationUserRoles"> + <return alias="ApplicationUserRoles" class="org.openecomp.portalapp.portal.transport.EcompUserRoles" /> + <![CDATA[ + select distinct fu.org_id, fu.manager_id, fu.first_name, fu.middle_name, fu.last_name, fu.phone, fu.email, fu.hrid, fu.org_user_id, fu.org_code, fu.org_manager_userid, fu.job_title, fu.login_id, + fu.active_yn , fr.app_role_id, fr.role_name + from fn_user fu, fn_role fr, fn_user_role fur + where fu.user_id = fur.user_id and fu.active_yn='Y' and fur.role_id = fr.role_id and fr.app_id =:appId and fr.active_yn='Y' + union + select distinct fu.org_id, fu.manager_id, fu.first_name, fu.middle_name, fu.last_name, fu.phone, fu.email, fu.hrid, fu.org_user_id, fu.org_code, fu.org_manager_userid, fu.job_title, fu.login_id, fu.active_yn , fr.role_id, fr.role_name + from fn_user fu, fn_role fr, fn_user_role fur + where fu.user_id = fur.user_id and fu.active_yn='Y' and fur.app_id=:appId and fr.role_name like 'global%' and fr.active_yn='Y' + ; + ]]> + </sql-query> </hibernate-mapping> |