diff options
Diffstat (limited to 'ecomp-portal-BE-common')
196 files changed, 16610 insertions, 335 deletions
diff --git a/ecomp-portal-BE-common/pom.xml b/ecomp-portal-BE-common/pom.xml index 79968b3a..6e5e5ee0 100644 --- a/ecomp-portal-BE-common/pom.xml +++ b/ecomp-portal-BE-common/pom.xml @@ -15,7 +15,7 @@ <epsdk.version>1.3.0</epsdk.version> <encoding>UTF-8</encoding> <!-- Tests usually require some setup that maven cannot do, so skip. --> - <skipTests>true</skipTests> + <skipTests>false</skipTests> <nexusproxy>https://nexus.onap.org</nexusproxy> <snapshotNexusPath>/content/repositories/snapshots/</snapshotNexusPath> <stagingNexusPath>content/repositories/staging/</stagingNexusPath> @@ -67,7 +67,59 @@ <finalName>${project.artifactId}</finalName> <plugins> - + <plugin> + <groupId>org.jacoco</groupId> + <artifactId>jacoco-maven-plugin</artifactId> + <version>0.7.6.201602180812</version> + <inherited>True</inherited> + <executions> + <!-- Unit-Tests --> + <execution> + <id>prepare-agent</id> + <goals> + <goal>prepare-agent</goal> + </goals> + <configuration> + <destFile>${sonar.jacoco.reportPath}</destFile> + </configuration> + </execution> + <execution> + <id>report</id> + <goals> + <goal>report</goal> + </goals> + <configuration> + <dataFile>${sonar.jacoco.reportPath}</dataFile> + <outputDirectory>${project.basedir}/target/site/jacoco</outputDirectory> + </configuration> + </execution> + <!-- Will see build errors while running the test cases because of dual + instrumentation --> + <execution> + <id>default-instrument</id> + <goals> + <goal>instrument</goal> + </goals> + </execution> + <execution> + <id>default-restore-instrumented-classes</id> + <goals> + <goal>restore-instrumented-classes</goal> + </goals> + </execution> + <!-- Integration Tests (Only report goal) --> + <execution> + <id>report-integration</id> + <goals> + <goal>report-integration</goal> + </goals> + <configuration> + <dataFile>${sonar.jacoco.itReportPath}</dataFile> + <outputDirectory>${project.basedir}/target/site/it-jacoco</outputDirectory> + </configuration> + </execution> + </executions> + </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> @@ -223,6 +275,7 @@ </exclusion> </exclusions> </dependency> + <!-- Hibernate --> <dependency> @@ -574,6 +627,31 @@ <version>4.11</version> <scope>test</scope> </dependency> + <dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-api-mockito</artifactId> + <version>1.6.1</version> + </dependency> + <dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-core</artifactId> + <version>1.6.1</version> + </dependency> + <dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-module-junit4</artifactId> + <version>1.6.1</version> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <version>1.8.5</version> + </dependency> + <dependency> + <groupId>org.jacoco</groupId> + <artifactId>jacoco-maven-plugin</artifactId> + <version>0.7.6.201602180812</version> + </dependency> <dependency> <groupId>commons-beanutils</groupId> @@ -604,14 +682,36 @@ <artifactId>springfox-swagger2</artifactId> <version>2.5.0</version> </dependency> - <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.5.0</version> </dependency> - + + <!-- Schedulers required Libraries --> + + <dependency> + <groupId>com.googlecode.json-simple</groupId> + <artifactId>json-simple</artifactId> + <version>1.1.1</version> + </dependency> + <dependency> + <groupId>org.glassfish.jersey.core</groupId> + <artifactId>jersey-client</artifactId> + <version>2.23.1</version> + </dependency> + <dependency> + <groupId>com.fasterxml.jackson.jaxrs</groupId> + <artifactId>jackson-jaxrs-json-provider</artifactId> + <version>2.6.3</version> + </dependency> + <dependency> + <groupId>org.glassfish.jersey.connectors</groupId> + <artifactId>jersey-jetty-connector</artifactId> + <version>2.23.1</version> + </dependency> </dependencies> + <!-- No deployment descriptor. --> 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> diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/AppCatalogControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/AppCatalogControllerTest.java new file mode 100644 index 00000000..16d2c8d5 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/AppCatalogControllerTest.java @@ -0,0 +1,263 @@ +/*- + * ================================================================================ + * 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 static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.AppCatalogController; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.ecomp.model.AppCatalogItem; +import org.openecomp.portalapp.portal.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.AdminRolesServiceImpl; +import org.openecomp.portalapp.portal.service.EPAppCommonServiceImpl; +import org.openecomp.portalapp.portal.service.EPAppService; +import org.openecomp.portalapp.portal.service.PersUserAppService; +import org.openecomp.portalapp.portal.service.PersUserAppServiceImpl; +import org.openecomp.portalapp.portal.transport.AppCatalogPersonalization; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.FieldsValidator.FieldName; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.util.SystemProperties; + +public class AppCatalogControllerTest extends MockitoTestSuite { + + @Mock + AdminRolesService adminRolesService = new AdminRolesServiceImpl(); + + @Mock + EPAppService appService = new EPAppCommonServiceImpl(); + + @InjectMocks + AppCatalogController appCatalogController = new AppCatalogController(); + + PersUserAppService persUserAppService = Mockito.spy(new PersUserAppServiceImpl()); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + + @Mock + EPUserUtils ePUserUtils = new EPUserUtils(); + + @Mock + EPUser epuser; + + NullPointerException nullPointerException = new NullPointerException(); + + MockEPUser mockUser = new MockEPUser(); + + public AppCatalogItem mockAppCatalogItem() { + AppCatalogItem appCatalogItem = new AppCatalogItem(); + appCatalogItem.setId((long) 1); + appCatalogItem.setName("Ecomp Portal"); + appCatalogItem.setImageUrl("Test_URL"); + appCatalogItem.setDescription("Testing"); + appCatalogItem.setNotes("Test"); + appCatalogItem.setUrl("test"); + appCatalogItem.setAlternateUrl("test"); + appCatalogItem.setRestricted(false); + appCatalogItem.setOpen(false); + appCatalogItem.setAccess(true); + appCatalogItem.setSelect(true); + appCatalogItem.setPending(false); + + return appCatalogItem; + } + + @Test + public void getAppCatalogTestIfUserNotAdmin() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<AppCatalogItem> actualAppCatalogList = null; + + List<AppCatalogItem> expectedAppCatalog = new ArrayList<>(); + + AppCatalogItem appCatalogItem = mockAppCatalogItem(); + expectedAppCatalog.add(appCatalogItem); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + Mockito.when(appService.getUserAppCatalog(user)).thenReturn(expectedAppCatalog); + actualAppCatalogList = appCatalogController.getAppCatalog(mockedRequest, mockedResponse); + + assertTrue(actualAppCatalogList.contains(appCatalogItem)); + + } + + @Test + public void getAppCatalogTestIfUserIsAdmin() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<AppCatalogItem> actualAppCatalogList = null; + + List<AppCatalogItem> expectedAppCatalog = new ArrayList<>(); + + AppCatalogItem appCatalogItem = mockAppCatalogItem(); + + expectedAppCatalog.add(appCatalogItem); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(appService.getAdminAppCatalog(user)).thenReturn(expectedAppCatalog); + actualAppCatalogList = appCatalogController.getAppCatalog(mockedRequest, mockedResponse); + + assertTrue(actualAppCatalogList.contains(appCatalogItem)); + + } + + @Test + public void getAppCatalogTestIfUserisNull() throws IOException { + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(null); + List<AppCatalogItem> actualAppCatalogList = new ArrayList<>(); + ; + actualAppCatalogList = appCatalogController.getAppCatalog(mockedRequest, mockedResponse); + assertNull(actualAppCatalogList); + + } + + @Test + public void getAppCatalogTestIfUserThrowsExceptionTest() throws IOException { + EPUser user = new EPUser(); + user.setFirstName("test"); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<AppCatalogItem> actualAppCatalogList = new ArrayList<>(); + ; + + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + + Mockito.when(appCatalogController.getAppCatalog(mockedRequest, mockedResponse)).thenThrow(nullPointerException); + + actualAppCatalogList = appCatalogController.getAppCatalog(mockedRequest, mockedResponse); + assertNull(actualAppCatalogList); + + } + + @Test + public void putAppCatalogSelectionTestWhenAppIsNull() throws IOException { + + AppCatalogPersonalization persRequest = new AppCatalogPersonalization(); + persRequest.setAppId((long) 1); + persRequest.setPending(false); + persRequest.setSelect(false); + + EPUser user = mockUser.mockEPUser(); + + FieldsValidator expectedFieldValidator = new FieldsValidator(); + + FieldsValidator actualFieldValidator = new FieldsValidator(); + List<FieldName> fields = new ArrayList<>(); + ; + + expectedFieldValidator.setHttpStatusCode((long) 200); + expectedFieldValidator.setFields(fields); + expectedFieldValidator.setErrorCode(null); + + EPApp app = null; + + Mockito.when(appService.getApp(persRequest.getAppId())).thenReturn(app); + + HttpSession session = mockedRequest.getSession(); + session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user); + + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + actualFieldValidator = appCatalogController.putAppCatalogSelection(mockedRequest, persRequest, mockedResponse); + assertEquals(expectedFieldValidator, actualFieldValidator); + + } + + @Test + public void putAppCatalogSelectionTest() throws IOException { + + AppCatalogPersonalization persRequest = new AppCatalogPersonalization(); + persRequest.setAppId((long) 1); + persRequest.setPending(false); + persRequest.setSelect(false); + + EPUser user = mockUser.mockEPUser(); + + FieldsValidator expectedFieldValidator = new FieldsValidator(); + + FieldsValidator actualFieldValidator = new FieldsValidator(); + List<FieldName> fields = new ArrayList<>(); + ; + + expectedFieldValidator.setHttpStatusCode((long) 200); + expectedFieldValidator.setFields(fields); + expectedFieldValidator.setErrorCode(null); + + EPApp app = new EPApp(); + + app.setName("Test"); + app.setImageUrl("test"); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 1); + app.setAppRestEndpoint("test"); + app.setAlternateUrl("test"); + app.setName("test"); + app.setMlAppName("test"); + app.setMlAppAdminId("test"); + app.setUsername("test"); + app.setAppPassword("test"); + app.setOpen(false); + app.setEnabled(false); + app.setUebKey("test"); + app.setUebSecret("test"); + app.setUebTopicName("test"); + app.setAppType(1); + + Mockito.when(appService.getApp(persRequest.getAppId())).thenReturn(app); + + HttpSession session = mockedRequest.getSession(); + session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user); + + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.doNothing().when(persUserAppService).setPersUserAppValue(user, app, persRequest.getSelect(), + persRequest.getPending()); + + actualFieldValidator = appCatalogController.putAppCatalogSelection(mockedRequest, persRequest, mockedResponse); + + assertEquals(expectedFieldValidator, actualFieldValidator); + + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/AppContactUsControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/AppContactUsControllerTest.java new file mode 100644 index 00000000..01cf27e0 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/AppContactUsControllerTest.java @@ -0,0 +1,274 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.AppContactUsController; +import org.openecomp.portalapp.portal.ecomp.model.AppCategoryFunctionsItem; +import org.openecomp.portalapp.portal.ecomp.model.AppContactUsItem; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.service.AppContactUsService; +import org.openecomp.portalapp.portal.service.AppContactUsServiceImpl; +import org.openecomp.portalapp.util.EPUserUtils; + +public class AppContactUsControllerTest extends MockitoTestSuite{ + + @Mock + AppContactUsService contactUsService = new AppContactUsServiceImpl(); + + @InjectMocks + AppContactUsController appContactUsController = new AppContactUsController(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + + @Mock + EPUserUtils ePUserUtils = new EPUserUtils(); + + public List<AppContactUsItem> mockResponse() { + List<AppContactUsItem> appContactUsItemList = new ArrayList<AppContactUsItem>(); + AppContactUsItem appContactUsItem = new AppContactUsItem(); + appContactUsItem.setAppId((long) 1); + appContactUsItem.setAppName("ECOMP Portal"); + appContactUsItem.setDescription("Test"); + appContactUsItem.setContactName("Test"); + appContactUsItem.setContactEmail("person@onap.org"); + appContactUsItem.setUrl("Test_URL"); + appContactUsItem.setActiveYN("Y"); + appContactUsItemList.add(appContactUsItem); + + return appContactUsItemList; + + } + + public PortalRestResponse<List<AppContactUsItem>> successPortalRestResponse() { + PortalRestResponse<List<AppContactUsItem>> expectedportalRestResponse = new PortalRestResponse<List<AppContactUsItem>>(); + List<AppContactUsItem> appContactUsItemList = mockResponse(); + expectedportalRestResponse.setMessage("success"); + expectedportalRestResponse.setResponse(appContactUsItemList); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK); + return expectedportalRestResponse; + + } + + public PortalRestResponse<List<AppContactUsItem>> exceptionPortalRestResponse() { + PortalRestResponse<List<AppContactUsItem>> expectedportalRestResponse = new PortalRestResponse<List<AppContactUsItem>>(); + expectedportalRestResponse.setMessage(null); + expectedportalRestResponse.setResponse(null); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + return expectedportalRestResponse; + + } + + @Test + public void getAppContactUsList() throws Exception { + PortalRestResponse<List<AppContactUsItem>> expectedportalRestResponse = successPortalRestResponse(); + List<AppContactUsItem> appContactUsItemList = mockResponse(); + PortalRestResponse<List<AppContactUsItem>> actualPortalRestResponse = new PortalRestResponse<List<AppContactUsItem>>(); + Mockito.when(contactUsService.getAppContactUs()).thenReturn(appContactUsItemList); + actualPortalRestResponse = appContactUsController.getAppContactUsList(mockedRequest); + assertEquals(actualPortalRestResponse, expectedportalRestResponse); + } + + @Test + public void getAppContactUsListCatchesExeptionTest() throws Exception { + + PortalRestResponse<List<AppContactUsItem>> expectedportalRestResponse = exceptionPortalRestResponse(); + PortalRestResponse<List<AppContactUsItem>> actualPortalRestResponse = new PortalRestResponse<List<AppContactUsItem>>(); + Mockito.when(contactUsService.getAppContactUs()).thenThrow(nullPointerException); + actualPortalRestResponse = appContactUsController.getAppContactUsList(mockedRequest); + assertEquals(actualPortalRestResponse, expectedportalRestResponse); + } + + @Test + public void getAppsAndContactsTest() throws Exception { + PortalRestResponse<List<AppContactUsItem>> expectedportalRestResponse = successPortalRestResponse(); + List<AppContactUsItem> appContactUsItemList = mockResponse(); + PortalRestResponse<List<AppContactUsItem>> actualPortalRestResponse = new PortalRestResponse<List<AppContactUsItem>>(); + Mockito.when(contactUsService.getAppsAndContacts()).thenReturn(appContactUsItemList); + actualPortalRestResponse = appContactUsController.getAppsAndContacts(mockedRequest); + assertEquals(actualPortalRestResponse, expectedportalRestResponse); + + } + + @Test + public void getAppsAndContactsCatchesExceptionTest() throws Exception { + PortalRestResponse<List<AppContactUsItem>> expectedportalRestResponse = exceptionPortalRestResponse(); + PortalRestResponse<List<AppContactUsItem>> actualPortalRestResponse = new PortalRestResponse<List<AppContactUsItem>>(); + Mockito.when(contactUsService.getAppsAndContacts()).thenThrow(nullPointerException); + actualPortalRestResponse = appContactUsController.getAppsAndContacts(mockedRequest); + assertEquals(actualPortalRestResponse, expectedportalRestResponse); + + } + + @Test + public void getAppCategoryFunctionsTest() throws Exception { + PortalRestResponse<List<AppCategoryFunctionsItem>> actualportalRestResponse = null; + + List<AppCategoryFunctionsItem> contents = new ArrayList<AppCategoryFunctionsItem>(); + + AppCategoryFunctionsItem appCategoryFunctionsItem = new AppCategoryFunctionsItem(); + AppCategoryFunctionsItem appCategoryFunctionsItem1 = new AppCategoryFunctionsItem(); + + appCategoryFunctionsItem.setRowId("1"); + appCategoryFunctionsItem.setAppId("1"); + appCategoryFunctionsItem.setApplication("Ecomp-portal"); + appCategoryFunctionsItem.setCategory("test"); + appCategoryFunctionsItem.setFunctions("test"); + + appCategoryFunctionsItem1.setRowId("2"); + appCategoryFunctionsItem1.setAppId("2"); + appCategoryFunctionsItem1.setApplication("Ecomp-portal-test"); + appCategoryFunctionsItem1.setCategory("test"); + appCategoryFunctionsItem1.setFunctions("test"); + contents.add(appCategoryFunctionsItem); + contents.add(appCategoryFunctionsItem1); + + PortalRestResponse<List<AppCategoryFunctionsItem>> expectedportalRestResponse = new PortalRestResponse<List<AppCategoryFunctionsItem>>(); + expectedportalRestResponse.setMessage("success"); + expectedportalRestResponse.setResponse(contents); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK); + + Mockito.when(contactUsService.getAppCategoryFunctions()).thenReturn(contents); + actualportalRestResponse = appContactUsController.getAppCategoryFunctions(mockedRequest); + assertEquals(actualportalRestResponse, expectedportalRestResponse); + + } + + @Test + public void getAppCategoryFunctionsCatchesExceptionTest() throws Exception { + PortalRestResponse<List<AppCategoryFunctionsItem>> actualportalRestResponse = null; + PortalRestResponse<List<AppContactUsItem>> expectedportalRestResponse = exceptionPortalRestResponse(); + Mockito.when(contactUsService.getAppCategoryFunctions()).thenThrow(nullPointerException); + actualportalRestResponse = appContactUsController.getAppCategoryFunctions(mockedRequest); + assertEquals(actualportalRestResponse, expectedportalRestResponse); + + } + + @Test + public void saveTest() throws Exception { + PortalRestResponse<String> actualSaveAppContactUS = null; + + AppContactUsItem contactUs = new AppContactUsItem(); + contactUs.setAppId((long) 1); + contactUs.setAppName("Ecomp Portal"); + contactUs.setDescription("Test"); + contactUs.setContactName("Test"); + contactUs.setContactEmail("person@onap.org"); + contactUs.setUrl("Test_URL"); + contactUs.setActiveYN("Y"); + + Mockito.when(contactUsService.saveAppContactUs(contactUs)).thenReturn("SUCCESS"); + actualSaveAppContactUS = appContactUsController.save(contactUs); + assertEquals(actualSaveAppContactUS.getMessage(), "SUCCESS"); + } + + @Test + public void saveExceptionTest() throws Exception { + PortalRestResponse<String> actualSaveAppContactUS = null; + + AppContactUsItem contactUs = new AppContactUsItem(); + contactUs.setAppId((long) 1); + contactUs.setAppName("Ecomp Portal"); + contactUs.setDescription("Test"); + contactUs.setContactName("Test"); + contactUs.setContactEmail("person@onap.org"); + contactUs.setUrl("Test_URL"); + contactUs.setActiveYN("Y"); + + Mockito.when(contactUsService.saveAppContactUs(contactUs)).thenThrow(new Exception()); + actualSaveAppContactUS = appContactUsController.save(contactUs); + assertEquals(actualSaveAppContactUS.getMessage(), "failure"); + } + + @Test + public void saveWhenAppContactUsItemNullTest() throws Exception { + PortalRestResponse<String> actualSaveAppContactUS = null; + AppContactUsItem contactUs = null; + actualSaveAppContactUS = appContactUsController.save(contactUs); + assertEquals(actualSaveAppContactUS.getMessage(), "failure"); + + } + + @Test + public void saveAllTest() throws Exception { + + List<AppContactUsItem> contactUs = mockResponse(); + PortalRestResponse<String> actualSaveAppContactUS = null; + Mockito.when(contactUsService.saveAppContactUs(contactUs)).thenReturn("SUCCESS"); + actualSaveAppContactUS = appContactUsController.save(contactUs); + assertEquals(actualSaveAppContactUS.getMessage(), "SUCCESS"); + } + + @Test + public void saveAllExceptionTest() throws Exception { + + List<AppContactUsItem> contactUs = mockResponse(); + PortalRestResponse<String> actualSaveAppContactUS = null; + Mockito.when(contactUsService.saveAppContactUs(contactUs)).thenThrow(new Exception()); + actualSaveAppContactUS = appContactUsController.save(contactUs); + assertEquals(actualSaveAppContactUS.getMessage(), "failure"); + } + + @Test + public void deleteTest() throws Exception { + + PortalRestResponse<String> actualSaveAppContactUS = null; + Long id = (long) 1; + String saveAppContactUs = "SUCCESS"; + Mockito.when(contactUsService.deleteContactUs(id)).thenReturn(saveAppContactUs); + actualSaveAppContactUS = appContactUsController.delete(id); + assertEquals(actualSaveAppContactUS.getMessage(), "SUCCESS"); + } + + @Test + public void deleteExceptionTest() throws Exception { + + PortalRestResponse<String> actualSaveAppContactUS = null; + Long id = (long) 1; + Mockito.when(contactUsService.deleteContactUs(id)).thenThrow(new Exception()); + actualSaveAppContactUS = appContactUsController.delete(id); + assertEquals(actualSaveAppContactUS.getMessage(), "failure"); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/AppsControllerExternalRequestTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/AppsControllerExternalRequestTest.java new file mode 100644 index 00000000..e62a940c --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/AppsControllerExternalRequestTest.java @@ -0,0 +1,273 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.AppsControllerExternalRequest; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.portal.domain.EPApp; +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.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.EPAppService; +import org.openecomp.portalapp.portal.service.PortalAdminService; +import org.openecomp.portalapp.portal.service.UserService; +import org.openecomp.portalapp.portal.service.UserServiceImpl; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.OnboardingApp; +import org.openecomp.portalapp.util.EPUserUtils; + +public class AppsControllerExternalRequestTest extends MockitoTestSuite { + + @Mock + AdminRolesService adminRolesService; + + @Mock + EPAppService appService; + + @Mock + PortalAdminService portalAdminService; + + @Mock + UserService userService = new UserServiceImpl(); + + @InjectMocks + AppsControllerExternalRequest appsControllerExternalRequest = new AppsControllerExternalRequest(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + + MockEPUser mockUser = new MockEPUser(); + @Mock + EPUserUtils ePUserUtils = new EPUserUtils(); + + @Test + public void postPortalAdminIfUSerNullTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Missing required field: email, loginId, or loginPwd"); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + EPUser user = mockUser.mockEPUser(); + user.setEmail("guestT@test.portal.onap.org"); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + PortalRestResponse<String> actualPortalRestResponse = appsControllerExternalRequest + .postPortalAdmin(mockedRequest, mockedResponse, user); + assertEquals(actualPortalRestResponse, expectedportalRestResponse); + } + + @Test + public void postPortalAdminTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("java.lang.NullPointerException"); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + EPUser user = mockUser.mockEPUser(); + user.setEmail("guestT@test.portal.onap.org"); + user.setLoginPwd("pwd"); + user.setLoginId("Test"); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(userService.getUserByUserId(user.getOrgUserId())).thenThrow(nullPointerException); + PortalRestResponse<String> actualPortalRestResponse = appsControllerExternalRequest + .postPortalAdmin(mockedRequest, mockedResponse, user); + assertEquals(actualPortalRestResponse, expectedportalRestResponse); + } + + @Test + public void postPortalAdminCreateUserIfNotFoundTest() throws Exception { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage(null); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + EPUser user = mockUser.mockEPUser(); + user.setEmail("guestT@test.portal.onap.org"); + user.setLoginPwd("pwd"); + user.setLoginId("Test"); + List<EPUser> expectedList = null; + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(userService.getUserByUserId(user.getOrgUserId())).thenReturn(expectedList); + Mockito.when(userService.saveNewUser(user, "Yes")).thenReturn(null); + PortalRestResponse<String> actualPortalRestResponse = appsControllerExternalRequest + .postPortalAdmin(mockedRequest, mockedResponse, user); + assertEquals(actualPortalRestResponse, expectedportalRestResponse); + } + + @Test + public void postPortalAdminCreateUserIfFoundTest() throws Exception { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage(null); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + EPUser user = mockUser.mockEPUser(); + user.setEmail("guestT@test.portal.onap.org"); + user.setLoginPwd("pwd"); + user.setLoginId("Test"); + List<EPUser> expectedList = new ArrayList<EPUser>(); + expectedList.add(user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(userService.getUserByUserId(user.getOrgUserId())).thenReturn(expectedList); + Mockito.when(userService.saveNewUser(user, "Yes")).thenReturn(null); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + PortalRestResponse<String> actualPortalRestResponse = appsControllerExternalRequest + .postPortalAdmin(mockedRequest, mockedResponse, user); + assertEquals(actualPortalRestResponse, expectedportalRestResponse); + } + + @Test + public void postPortalAdminCreateUserIfNotSuperAdminTest() throws Exception { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage(null); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + EPUser user = mockUser.mockEPUser(); + user.setEmail("guestT@test.portal.onap.org"); + user.setLoginPwd("pwd"); + user.setLoginId("Test"); + List<EPUser> expectedList = new ArrayList<EPUser>(); + expectedList.add(user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(userService.getUserByUserId(user.getOrgUserId())).thenReturn(expectedList); + Mockito.when(userService.saveNewUser(user, "Yes")).thenReturn(null); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + + FieldsValidator expectedFieldValidator = new FieldsValidator(); + expectedFieldValidator.setHttpStatusCode((long) 200); + expectedFieldValidator.setFields(null); + expectedFieldValidator.setErrorCode(null); + Mockito.when(portalAdminService.createPortalAdmin(user.getOrgUserId())).thenReturn(expectedFieldValidator); + + PortalRestResponse<String> actualPortalRestResponse = appsControllerExternalRequest + .postPortalAdmin(mockedRequest, mockedResponse, user); + assertEquals(actualPortalRestResponse, expectedportalRestResponse); + } + + @Test + public void postPortalAdminCreateUserIfFieldValidatorErrorTest() throws Exception { + FieldsValidator expectedFieldValidator = new FieldsValidator(); + expectedFieldValidator.setHttpStatusCode((long) 500); + expectedFieldValidator.setFields(null); + expectedFieldValidator.setErrorCode(null); + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("FieldsValidator [httpStatusCode=500, errorCode=null, fields=null]"); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + EPUser user = mockUser.mockEPUser(); + user.setEmail("guestT@test.portal.onap.org"); + user.setLoginPwd("pwd"); + user.setLoginId("Test"); + List<EPUser> expectedList = new ArrayList<EPUser>(); + expectedList.add(user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(userService.getUserByUserId(user.getOrgUserId())).thenReturn(expectedList); + Mockito.when(userService.saveNewUser(user, "Yes")).thenReturn(null); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + Mockito.when(portalAdminService.createPortalAdmin(user.getOrgUserId())).thenReturn(expectedFieldValidator); + PortalRestResponse<String> actualPortalRestResponse = appsControllerExternalRequest + .postPortalAdmin(mockedRequest, mockedResponse, user); + assertEquals(actualPortalRestResponse, expectedportalRestResponse); + } + + @Test + public void getOnboardAppExternalTest() { + EPApp epApp = new EPApp(); + Long appId = (long) 1; + Mockito.when(appService.getApp(appId)).thenReturn(epApp); + OnboardingApp expectedApp = new OnboardingApp(); + Mockito.doNothing().when(appService).createOnboardingFromApp(epApp, expectedApp); + OnboardingApp actualApp = appsControllerExternalRequest.getOnboardAppExternal(mockedRequest, mockedResponse, + appId); + assertEquals(expectedApp.getClass(), actualApp.getClass()); + } + + @Test + public void postOnboardAppExternalExceptionTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Unexpected field: id"); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + + OnboardingApp expectedOnboardingApp = new OnboardingApp(); + expectedOnboardingApp.id = (long) 1; + + PortalRestResponse<String> actualPortalRestResponse = appsControllerExternalRequest + .postOnboardAppExternal(mockedRequest, mockedResponse, expectedOnboardingApp); + assertEquals(actualPortalRestResponse, expectedportalRestResponse); + } + + @Test + public void postOnboardAppExternalTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage( + "Missing required field: name, url, restUrl, restrictedApp, isOpen, isEnabled, myLoginsAppOwner"); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + + OnboardingApp expectedOnboardingApp = new OnboardingApp(); + expectedOnboardingApp.id = null; + + PortalRestResponse<String> actualPortalRestResponse = appsControllerExternalRequest + .postOnboardAppExternal(mockedRequest, mockedResponse, expectedOnboardingApp); + assertEquals(actualPortalRestResponse, expectedportalRestResponse); + + } + + @Test + public void putOnboardAppExternalifAppNullTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Unexpected value for field: id"); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + Long appId = null; + OnboardingApp expectedOnboardingApp = new OnboardingApp(); + expectedOnboardingApp.id = null; + + PortalRestResponse<String> actualPortalRestResponse = appsControllerExternalRequest + .putOnboardAppExternal(mockedRequest, mockedResponse, appId, expectedOnboardingApp); + assertEquals(actualPortalRestResponse, expectedportalRestResponse); + } + + @Test + public void putOnboardAppExternalIfOnboardingAppDetailsNullTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage( + "Missing required field: name, url, restUrl, restrictedApp, isOpen, isEnabled, myLoginsAppOwner"); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + Long appId = (long) 1; + OnboardingApp expectedOnboardingApp = new OnboardingApp(); + expectedOnboardingApp.id = (long) 1; + PortalRestResponse<String> actualPortalRestResponse = appsControllerExternalRequest + .putOnboardAppExternal(mockedRequest, mockedResponse, appId, expectedOnboardingApp); + assertEquals(actualPortalRestResponse, expectedportalRestResponse); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/AppsControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/AppsControllerTest.java new file mode 100644 index 00000000..d4181a62 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/AppsControllerTest.java @@ -0,0 +1,914 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.AppsController; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.portal.domain.AdminUserApplications; +import org.openecomp.portalapp.portal.domain.AppIdAndNameTransportModel; +import org.openecomp.portalapp.portal.domain.AppsResponse; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EcompApp; +import org.openecomp.portalapp.portal.domain.UserRole; +import org.openecomp.portalapp.portal.domain.UserRoles; +import org.openecomp.portalapp.portal.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.AdminRolesServiceImpl; +import org.openecomp.portalapp.portal.service.EPAppCommonServiceImpl; +import org.openecomp.portalapp.portal.service.EPAppService; +import org.openecomp.portalapp.portal.service.EPLeftMenuService; +import org.openecomp.portalapp.portal.service.EPLeftMenuServiceImpl; +import org.openecomp.portalapp.portal.transport.EPAppsManualPreference; +import org.openecomp.portalapp.portal.transport.EPAppsSortPreference; +import org.openecomp.portalapp.portal.transport.EPDeleteAppsManualSortPref; +import org.openecomp.portalapp.portal.transport.EPWidgetsSortPreference; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.LocalRole; +import org.openecomp.portalapp.portal.transport.OnboardingApp; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.AppUtils; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.http.HttpEntity; +import org.springframework.http.MediaType; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({SystemProperties.class,AppUtils.class, EPUserUtils.class, MediaType.class}) +public class AppsControllerTest extends MockitoTestSuite{ + + @InjectMocks + AppsController appsController = new AppsController(); + + @Mock + AdminRolesService adminRolesService = new AdminRolesServiceImpl(); + + @Mock + EPAppService appService = new EPAppCommonServiceImpl(); + + @Mock + EPLeftMenuService leftMenuService = new EPLeftMenuServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + + @Mock + EPUserUtils ePUserUtils = new EPUserUtils(); + + @Mock + AppUtils appUtils = new AppUtils(); + + MockEPUser mockUser = new MockEPUser(); + + @Test + public void getUserAppsTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<EcompApp> expectedEcompApps = new ArrayList<EcompApp>(); + + EcompApp ecompApp = new EcompApp(); + ecompApp.setId((long) 1); + ecompApp.setName("Test_app"); + ecompApp.setUrl("Test_URL"); + ecompApp.setUebKey("Test_key"); + ecompApp.setAlternateUrl("Test_alt_URL"); + expectedEcompApps.add(ecompApp); + List<EcompApp> actualEcompApps = new ArrayList<EcompApp>(); + Mockito.when(appService.transformAppsToEcompApps(appService.getUserApps(user))).thenReturn(expectedEcompApps); + actualEcompApps = appsController.getUserApps(mockedRequest, mockedResponse); + assertEquals(expectedEcompApps, actualEcompApps); + } + + @Test + public void getUserAppsNoUserTest() { + EPUser user = null; + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.transformAppsToEcompApps(appService.getUserApps(user))).thenReturn(null); + assertNull(appsController.getUserApps(mockedRequest, mockedResponse)); + + } + + @Test + public void getUserAppsExceptionTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.transformAppsToEcompApps(appService.getUserApps(user))).thenThrow(nullPointerException); + assertNull(appsController.getUserApps(mockedRequest, mockedResponse)); + + } + + @Test + public void getPersUserAppsIfUserIsAdminTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<EcompApp> expectedEcompApps = new ArrayList<EcompApp>(); + + EcompApp ecompApp = new EcompApp(); + ecompApp.setId((long) 1); + ecompApp.setName("Test_app"); + ecompApp.setUrl("Test_URL"); + ecompApp.setUebKey("Test_key"); + ecompApp.setAlternateUrl("Test_alt_URL"); + expectedEcompApps.add(ecompApp); + List<EcompApp> actualEcompApps = new ArrayList<EcompApp>(); + + List<EPApp> expectedApps = new ArrayList<EPApp>(); + + EPApp app = new EPApp(); + + app.setName("Test"); + app.setImageUrl("test"); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 1); + app.setAppRestEndpoint("test"); + app.setAlternateUrl("test"); + app.setName("test"); + app.setMlAppName("test"); + app.setMlAppAdminId("test"); + app.setUsername("test"); + app.setAppPassword("test"); + app.setOpen(false); + app.setEnabled(false); + app.setUebKey("test"); + app.setUebSecret("test"); + app.setUebTopicName("test"); + app.setAppType(1); + + expectedApps.add(app); + + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(appService.getPersAdminApps(user)).thenReturn(expectedApps); + + Mockito.when(appService.transformAppsToEcompApps(expectedApps)).thenReturn(expectedEcompApps); + actualEcompApps = appsController.getPersUserApps(mockedRequest, mockedResponse); + assertEquals(expectedEcompApps, actualEcompApps); + } + + @Test + public void getPersUserAppsIfUserNotAdminTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<EcompApp> expectedEcompApps = new ArrayList<EcompApp>(); + + EcompApp ecompApp = new EcompApp(); + ecompApp.setId((long) 1); + ecompApp.setName("Test_app"); + ecompApp.setUrl("Test_URL"); + ecompApp.setUebKey("Test_key"); + ecompApp.setAlternateUrl("Test_alt_URL"); + expectedEcompApps.add(ecompApp); + List<EcompApp> actualEcompApps = new ArrayList<EcompApp>(); + + List<EPApp> expectedApps = new ArrayList<EPApp>(); + + EPApp app = new EPApp(); + + app.setName("Test"); + app.setImageUrl("test"); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 1); + app.setAppRestEndpoint("test"); + app.setAlternateUrl("test"); + app.setName("test"); + app.setMlAppName("test"); + app.setMlAppAdminId("test"); + app.setUsername("test"); + app.setAppPassword("test"); + app.setOpen(false); + app.setEnabled(false); + app.setUebKey("test"); + app.setUebSecret("test"); + app.setUebTopicName("test"); + app.setAppType(1); + + expectedApps.add(app); + + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + Mockito.when(appService.getPersUserApps(user)).thenReturn(expectedApps); + Mockito.when(appService.transformAppsToEcompApps(expectedApps)).thenReturn(expectedEcompApps); + actualEcompApps = appsController.getPersUserApps(mockedRequest, mockedResponse); + assertEquals(expectedEcompApps, actualEcompApps); + } + + @Test + public void getPersUserAppsIfUserNullTest() throws IOException { + EPUser user = null; + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + assertNull(appsController.getPersUserApps(mockedRequest, mockedResponse)); + } + + @Test + public void getPersUserAppsExceptionTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(appService.getPersAdminApps(user)).thenThrow(nullPointerException); + assertNull(appsController.getPersUserApps(mockedRequest, mockedResponse)); + } + + @Test + public void getAdminAppsIfNotAdminTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isAccountAdmin(user)).thenReturn(false); + assertNull(appsController.getAdminApps(mockedRequest, mockedResponse)); + } + + @Test + public void getAdminAppsTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<AppIdAndNameTransportModel> expectedAdminApps = new ArrayList<AppIdAndNameTransportModel>(); + AppIdAndNameTransportModel appIdAndNameTransportModel = new AppIdAndNameTransportModel(); + appIdAndNameTransportModel.setId((long) 1); + appIdAndNameTransportModel.setName("Test_app"); + expectedAdminApps.add(appIdAndNameTransportModel); + List<AppIdAndNameTransportModel> actualAdminApps = new ArrayList<AppIdAndNameTransportModel>(); + Mockito.when(adminRolesService.isAccountAdmin(user)).thenReturn(true); + Mockito.when(appService.getAdminApps(user)).thenReturn(expectedAdminApps); + actualAdminApps = appsController.getAdminApps(mockedRequest, mockedResponse); + assertEquals(actualAdminApps, expectedAdminApps); + + } + + @Test + public void getAdminAppsExceptionTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isAccountAdmin(user)).thenReturn(true); + Mockito.when(appService.getAdminApps(user)).thenThrow(nullPointerException); + assertNull(appsController.getAdminApps(mockedRequest, mockedResponse)); + } + + @Test + public void getAppsForSuperAdminAndAccountAdminifOnlyAccountAdminTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + Mockito.when(adminRolesService.isAccountAdmin(user)).thenReturn(false); + assertNull(appsController.getAppsForSuperAdminAndAccountAdmin(mockedRequest, mockedResponse)); + } + + @Test + public void getAppsForSuperAdminAndAccountAdminTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<AppIdAndNameTransportModel> expectedAdminApps = new ArrayList<AppIdAndNameTransportModel>(); + AppIdAndNameTransportModel appIdAndNameTransportModel = new AppIdAndNameTransportModel(); + appIdAndNameTransportModel.setId((long) 1); + appIdAndNameTransportModel.setName("Test_app"); + expectedAdminApps.add(appIdAndNameTransportModel); + List<AppIdAndNameTransportModel> actualAdminApps = new ArrayList<AppIdAndNameTransportModel>(); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(adminRolesService.isAccountAdmin(user)).thenReturn(true); + Mockito.when(appService.getAppsForSuperAdminAndAccountAdmin(user)).thenReturn(expectedAdminApps); + actualAdminApps = appsController.getAppsForSuperAdminAndAccountAdmin(mockedRequest, mockedResponse); + assertEquals(actualAdminApps, expectedAdminApps); + + } + + @Test + public void getAppsForSuperAdminExceptionTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(adminRolesService.isAccountAdmin(user)).thenReturn(false); + Mockito.when(appService.getAppsForSuperAdminAndAccountAdmin(user)).thenThrow(nullPointerException); + assertNull(appsController.getAppsForSuperAdminAndAccountAdmin(mockedRequest, mockedResponse)); + } + + @Test + public void putUserAppsSortingManualTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<EPAppsManualPreference> ePAppsManualPreference = new ArrayList<EPAppsManualPreference>(); + FieldsValidator expectedFieldValidator = new FieldsValidator(); + expectedFieldValidator.setHttpStatusCode((long) 200); + expectedFieldValidator.setFields(null); + expectedFieldValidator.setErrorCode(null); + FieldsValidator actualFieldValidator = new FieldsValidator(); + Mockito.when(appService.saveAppsSortManual(ePAppsManualPreference, user)).thenReturn(expectedFieldValidator); + actualFieldValidator = appsController.putUserAppsSortingManual(mockedRequest, ePAppsManualPreference, + mockedResponse); + assertEquals(actualFieldValidator, expectedFieldValidator); + } + + @Test + public void putUserAppsSortingManualExceptionTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<EPAppsManualPreference> ePAppsManualPreference = new ArrayList<EPAppsManualPreference>(); + Mockito.when(appService.saveAppsSortManual(ePAppsManualPreference, user)).thenThrow(nullPointerException); + assertNull(appsController.putUserAppsSortingManual(mockedRequest, ePAppsManualPreference, mockedResponse)); + } + + @Test + public void putUserWidgetsSortManualTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<EPWidgetsSortPreference> ePWidgetsSortPreference = new ArrayList<EPWidgetsSortPreference>(); + FieldsValidator expectedFieldValidator = new FieldsValidator(); + expectedFieldValidator.setHttpStatusCode((long) 200); + expectedFieldValidator.setFields(null); + expectedFieldValidator.setErrorCode(null); + FieldsValidator actualFieldValidator = new FieldsValidator(); + Mockito.when(appService.saveWidgetsSortManual(ePWidgetsSortPreference, user)) + .thenReturn(expectedFieldValidator); + actualFieldValidator = appsController.putUserWidgetsSortManual(mockedRequest, ePWidgetsSortPreference, + mockedResponse); + assertEquals(actualFieldValidator, expectedFieldValidator); + } + + @Test + public void putUserWidgetsSortManualExceptionTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<EPAppsManualPreference> ePAppsManualPreference = new ArrayList<EPAppsManualPreference>(); + Mockito.when(appService.saveAppsSortManual(ePAppsManualPreference, user)).thenThrow(nullPointerException); + assertNull(appsController.putUserAppsSortingManual(mockedRequest, ePAppsManualPreference, mockedResponse)); + } + + @Test + public void putUserWidgetsSortPrefTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<EPWidgetsSortPreference> ePWidgetsSortPreference = new ArrayList<EPWidgetsSortPreference>(); + FieldsValidator expectedFieldValidator = new FieldsValidator(); + expectedFieldValidator.setHttpStatusCode((long) 200); + expectedFieldValidator.setFields(null); + expectedFieldValidator.setErrorCode(null); + FieldsValidator actualFieldValidator = new FieldsValidator(); + Mockito.when(appService.deleteUserWidgetSortPref(ePWidgetsSortPreference, user)) + .thenReturn(expectedFieldValidator); + actualFieldValidator = appsController.putUserWidgetsSortPref(mockedRequest, ePWidgetsSortPreference, + mockedResponse); + assertEquals(actualFieldValidator, expectedFieldValidator); + } + + @Test + public void putUserWidgetsSortPrefExceptionTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<EPWidgetsSortPreference> ePWidgetsSortPreference = new ArrayList<EPWidgetsSortPreference>(); + Mockito.when(appService.deleteUserWidgetSortPref(ePWidgetsSortPreference, user)) + .thenThrow(nullPointerException); + assertNull(appsController.putUserWidgetsSortPref(mockedRequest, ePWidgetsSortPreference, mockedResponse)); + } + + @Test + public void deleteUserAppSortManualTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + EPDeleteAppsManualSortPref epDeleteAppsManualSortPref = new EPDeleteAppsManualSortPref(); + + FieldsValidator expectedFieldValidator = new FieldsValidator(); + expectedFieldValidator.setHttpStatusCode((long) 200); + expectedFieldValidator.setFields(null); + expectedFieldValidator.setErrorCode(null); + FieldsValidator actualFieldValidator = new FieldsValidator(); + Mockito.when(appService.deleteUserAppSortManual(epDeleteAppsManualSortPref, user)) + .thenReturn(expectedFieldValidator); + actualFieldValidator = appsController.deleteUserAppSortManual(mockedRequest, epDeleteAppsManualSortPref, + mockedResponse); + assertEquals(actualFieldValidator, expectedFieldValidator); + } + + @Test + public void deleteUserAppSortManualExceptionTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + EPDeleteAppsManualSortPref epDeleteAppsManualSortPref = new EPDeleteAppsManualSortPref(); + Mockito.when(appService.deleteUserAppSortManual(epDeleteAppsManualSortPref, user)) + .thenThrow(nullPointerException); + assertNull(appsController.deleteUserAppSortManual(mockedRequest, epDeleteAppsManualSortPref, mockedResponse)); + } + + @Test + public void putUserAppsSortingPreferenceTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + EPAppsSortPreference userAppsValue = new EPAppsSortPreference(); + + FieldsValidator expectedFieldValidator = new FieldsValidator(); + expectedFieldValidator.setHttpStatusCode((long) 200); + expectedFieldValidator.setFields(null); + expectedFieldValidator.setErrorCode(null); + FieldsValidator actualFieldValidator = new FieldsValidator(); + Mockito.when(appService.saveAppsSortPreference(userAppsValue, user)).thenReturn(expectedFieldValidator); + actualFieldValidator = appsController.putUserAppsSortingPreference(mockedRequest, userAppsValue, + mockedResponse); + assertEquals(actualFieldValidator, expectedFieldValidator); + } + + @Test + public void putUserAppsSortingPreferenceExceptionTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + EPAppsSortPreference userAppsValue = new EPAppsSortPreference(); + Mockito.when(appService.saveAppsSortPreference(userAppsValue, user)).thenThrow(nullPointerException); + assertNull(appsController.putUserAppsSortingPreference(mockedRequest, userAppsValue, mockedResponse)); + } + + @Test + public void getUserAppsSortTypePreferenceTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + String expectedUserSortPreference = "TEST_DECE"; + String actualUserSortPreference = new String(); + Mockito.when(appService.getUserAppsSortTypePreference(user)).thenReturn(expectedUserSortPreference); + actualUserSortPreference = appsController.getUserAppsSortTypePreference(mockedRequest, mockedResponse); + assertEquals(actualUserSortPreference, expectedUserSortPreference); + } + + @Test + public void getUserAppsSortTypePreferenceExceptionTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getUserAppsSortTypePreference(user)).thenThrow(nullPointerException); + assertNull(appsController.getUserAppsSortTypePreference(mockedRequest, mockedResponse)); + } + + @Test + public void getUserAppsSortTypePreferenceIfUserNullTest() throws IOException { + EPUser user = null; + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getUserAppsSortTypePreference(user)).thenThrow(nullPointerException); + assertNull(appsController.getUserAppsSortTypePreference(mockedRequest, mockedResponse)); + } + + @Test + public void getAppsAdministratorsTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<AdminUserApplications> expecteAdminUserApplications = new ArrayList<AdminUserApplications>(); + List<AdminUserApplications> actualAdminUserApplications = new ArrayList<AdminUserApplications>(); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(appService.getAppsAdmins()).thenReturn(expecteAdminUserApplications); + actualAdminUserApplications = appsController.getAppsAdministrators(mockedRequest, mockedResponse); + assertEquals(expecteAdminUserApplications, actualAdminUserApplications); + } + + @Test + public void getAppsAdministratorsIfUserNotSuperAdminTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + assertNull(appsController.getUserAppsSortTypePreference(mockedRequest, mockedResponse)); + } + + @Test + public void getAppsAdministratorsExceptionTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(appService.getAppsAdmins()).thenThrow(nullPointerException); + assertNull(appsController.getUserAppsSortTypePreference(mockedRequest, mockedResponse)); + } + + @Test + public void getAppsTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<AppsResponse> expectedApps = new ArrayList<AppsResponse>(); + AppsResponse apps = new AppsResponse((long) 1, "test", true, true); + expectedApps.add(apps); + + List<AppsResponse> atualApps = new ArrayList<AppsResponse>(); + + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(appService.getAllApps(false)).thenReturn(expectedApps); + atualApps = appsController.getApps(mockedRequest, mockedResponse); + assertEquals(expectedApps, atualApps); + } + + @Test + public void getAppsExceptionTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + assertNull(appsController.getApps(mockedRequest, mockedResponse)); + } + + @Test + public void getAppsIfUserNotSuperAdminTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(appService.getAllApps(false)).thenThrow(nullPointerException); + assertNull(appsController.getApps(mockedRequest, mockedResponse)); + } + + @Test + public void getAllAppsTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<AppsResponse> expectedApps = new ArrayList<AppsResponse>(); + AppsResponse apps = new AppsResponse((long) 1, "test", true, true); + expectedApps.add(apps); + List<AppsResponse> atualApps = new ArrayList<AppsResponse>(); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(appService.getAllApps(true)).thenReturn(expectedApps); + atualApps = appsController.getAllApps(mockedRequest, mockedResponse); + assertEquals(expectedApps, atualApps); + } + + @Test + public void getAllAppsExceptionTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + assertNull(appsController.getAllApps(mockedRequest, mockedResponse)); + } + + @Test + public void getAllAppsIfUserNotSuperAdminTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(appService.getAllApps(true)).thenThrow(nullPointerException); + assertNull(appsController.getAllApps(mockedRequest, mockedResponse)); + } + + @Test + public void getAppsFullListTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<EcompApp> expectedEcompApps = new ArrayList<EcompApp>(); + + EcompApp ecompApp = new EcompApp(); + ecompApp.setId((long) 1); + ecompApp.setName("Test_app"); + ecompApp.setUrl("Test_URL"); + ecompApp.setUebKey("Test_key"); + ecompApp.setAlternateUrl("Test_alt_URL"); + expectedEcompApps.add(ecompApp); + List<EcompApp> actualEcompApps = new ArrayList<EcompApp>(); + Mockito.when(appService.getEcompAppAppsFullList()).thenReturn(expectedEcompApps); + actualEcompApps = appsController.getAppsFullList(mockedRequest, mockedResponse); + assertEquals(expectedEcompApps, actualEcompApps); + } + +// @Test +// public void getAppsFullListNoUserTest() { +// EPUser user = null; +// Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); +// Mockito.when(appService.getEcompAppAppsFullList()).thenReturn(null); +// assertNull(appsController.getAppsFullList(mockedRequest, mockedResponse)); +// +// } + + @Test + public void getUserProfileTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + + UserRole userRole = new UserRole(); + userRole.setUser_Id((long) 1); + userRole.setOrgUserId("guest"); + userRole.setFirstName("Test_User_FirstName"); + userRole.setLastName("Test_User_LastName"); + userRole.setRoleId((long) 1); + userRole.setRoleName("test"); + + UserRoles unexpectedserAndRoles = new UserRoles(userRole); + unexpectedserAndRoles.setFirstName("Test_User_FirstName"); + unexpectedserAndRoles.setLastName("Test_User_LastName"); + unexpectedserAndRoles.setGuestSession(false); + unexpectedserAndRoles.setOrgUserId("guest"); + List<String> roles = new ArrayList<String>(); + roles.add("Test"); + unexpectedserAndRoles.setRoles(roles); + Mockito.when(appService.getUserProfileNormalized(user)).thenReturn(unexpectedserAndRoles); + UserRoles actualUserAndRoles = appsController.getUserProfile(mockedRequest, mockedResponse); + assertEquals(unexpectedserAndRoles, actualUserAndRoles); + } + + @Test + public void getUserProfileIfUserNullTest() throws IOException { + EPUser user = null; + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getUserProfileNormalized(user)).thenReturn(null); + assertNull(appsController.getUserAppsSortTypePreference(mockedRequest, mockedResponse)); + } + + @Test + public void getUserProfileExcpetionTest() throws IOException { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getUserProfileNormalized(user)).thenThrow(nullPointerException); + assertNull(appsController.getUserAppsSortTypePreference(mockedRequest, mockedResponse)); + } + + @Test + public void getAppRolesTest() { + List<LocalRole> expectedRoleList = new ArrayList<LocalRole>(); + LocalRole localRole = new LocalRole(); + localRole.setRoleId(1); + localRole.setRolename("test"); + expectedRoleList.add(localRole); + long appId = 1; + Mockito.when(appService.getAppRoles(appId)).thenReturn(expectedRoleList); + List<LocalRole> actualRoleList = appsController.getAppRoles(mockedRequest, appId); + assertEquals(actualRoleList, expectedRoleList); + } + + @Test + public void getAppRolesExceptionTest() { + long appId = 1; + Mockito.when(appService.getAppRoles(appId)).thenThrow(nullPointerException); + assertNull(appsController.getAppRoles(mockedRequest, appId)); + } + + @Test + public void getOnboardingAppsTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<OnboardingApp> expectedOnboardingApps = new ArrayList<OnboardingApp>(); + OnboardingApp onboardingApp = new OnboardingApp(); + onboardingApp.setUebKey("test"); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(appService.getOnboardingApps()).thenReturn(expectedOnboardingApps); + List<OnboardingApp> actualOnboardingApps = appsController.getOnboardingApps(mockedRequest, mockedResponse); + assertEquals(expectedOnboardingApps, actualOnboardingApps); + } + + @Test + public void getOnboardingAppsifSuperAdiminTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + assertNull(appsController.getOnboardingApps(mockedRequest, mockedResponse)); + } + + @Test + public void getOnboardingAppsExceptionTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(!adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(appService.getOnboardingApps()).thenThrow(nullPointerException); + assertNull(appsController.getOnboardingApps(mockedRequest, mockedResponse)); + } + + @Test + public void putOnboardingAppTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + OnboardingApp OnboardingApp = new OnboardingApp(); + FieldsValidator expectedFieldValidator = new FieldsValidator(); + expectedFieldValidator.setHttpStatusCode((long) 200); + expectedFieldValidator.setFields(null); + expectedFieldValidator.setErrorCode(null); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(appService.modifyOnboardingApp(OnboardingApp, user)).thenReturn(expectedFieldValidator); + FieldsValidator actualFieldValidator = appsController.putOnboardingApp(mockedRequest, OnboardingApp, + mockedResponse); + assertEquals(expectedFieldValidator, actualFieldValidator); + } + + @Test + public void putOnboardingAppIfSuperAdminTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + FieldsValidator expectedFieldValidator = null; + OnboardingApp OnboardingApp = new OnboardingApp(); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + Mockito.when(appService.modifyOnboardingApp(OnboardingApp, user)).thenReturn(expectedFieldValidator); + assertNull(appsController.putOnboardingApp(mockedRequest, OnboardingApp, mockedResponse)); + } + + @Test + public void putOnboardingAppExceptionTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + OnboardingApp OnboardingApp = new OnboardingApp(); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(appService.modifyOnboardingApp(OnboardingApp, user)).thenThrow(nullPointerException); + assertNull(appsController.putOnboardingApp(mockedRequest, OnboardingApp, mockedResponse)); + } + + @Test + public void postOnboardingAppTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + OnboardingApp OnboardingApp = new OnboardingApp(); + FieldsValidator expectedFieldValidator = new FieldsValidator(); + expectedFieldValidator.setHttpStatusCode((long) 200); + expectedFieldValidator.setFields(null); + expectedFieldValidator.setErrorCode(null); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(appService.addOnboardingApp(OnboardingApp, user)).thenReturn(expectedFieldValidator); + FieldsValidator actualFieldValidator = appsController.postOnboardingApp(mockedRequest, OnboardingApp, + mockedResponse); + assertEquals(expectedFieldValidator, actualFieldValidator); + } + + @Test + public void postOnboardingAppIfSuperAdminTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + FieldsValidator expectedFieldValidator = null; + OnboardingApp OnboardingApp = new OnboardingApp(); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + Mockito.when(appService.addOnboardingApp(OnboardingApp, user)).thenReturn(expectedFieldValidator); + assertNull(appsController.postOnboardingApp(mockedRequest, OnboardingApp, mockedResponse)); + } + + @Test + public void postOnboardingAppExceptionTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + OnboardingApp OnboardingApp = new OnboardingApp(); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(appService.addOnboardingApp(OnboardingApp, user)).thenThrow(nullPointerException); + assertNull(appsController.postOnboardingApp(mockedRequest, OnboardingApp, mockedResponse)); + } + + @Test + public void deleteOnboardingAppTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + FieldsValidator expectedFieldValidator = new FieldsValidator(); + expectedFieldValidator.setHttpStatusCode((long) 200); + expectedFieldValidator.setFields(null); + expectedFieldValidator.setErrorCode(null); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + long appId = 1; + Mockito.when(appService.deleteOnboardingApp(user,appId )).thenReturn(expectedFieldValidator); + FieldsValidator actualFieldValidator = appsController.deleteOnboardingApp(mockedRequest,appId, + mockedResponse); + assertEquals(expectedFieldValidator, actualFieldValidator); + } + + @Test + public void deleteOnboardingAppIfSuperAdminTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + FieldsValidator expectedFieldValidator = null; + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + long appId = 1; + Mockito.when(appService.deleteOnboardingApp(user,appId)).thenReturn(expectedFieldValidator); + assertNull(appsController.deleteOnboardingApp(mockedRequest,appId,mockedResponse)); + } + + @Test + public void deleteOnboardingAppExceptionTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + long appId = 1; + Mockito.when(appService.deleteOnboardingApp(user,appId)).thenThrow(nullPointerException); + assertNull(appsController.deleteOnboardingApp(mockedRequest,appId,mockedResponse)); + } + + @Test + public void getLeftMenuItemsTest() + { + EPUser user = mockUser.mockEPUser(); + String menuList = "Test"; + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Set menuSet = new HashSet<>(); + menuSet.add(1); + Mockito.when(AppUtils.getSession(mockedRequest) + .getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME))).thenReturn(menuSet); + Mockito.when(AppUtils.getSession(mockedRequest) + .getAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME))).thenReturn(menuSet); + Mockito.when(leftMenuService.getLeftMenuItems(user, menuSet, menuSet)).thenReturn(menuList); + String response = appsController.getLeftMenuItems(mockedRequest, mockedResponse); + assertTrue(response.equals("Test")); + } + + @Test + public void getLeftMenuItemsExceptionTest() + { + EPUser user = mockUser.mockEPUser(); + String menuList = "Test"; + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Set menuSet = new HashSet<>(); + menuSet.add(1); + Mockito.when(AppUtils.getSession(mockedRequest) + .getAttribute(SystemProperties.getProperty(SystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME))).thenReturn(menuSet); + Mockito.when(AppUtils.getSession(mockedRequest) + .getAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME))).thenReturn(menuSet); + Mockito.when(leftMenuService.getLeftMenuItems(user, menuSet, menuSet)).thenThrow(nullPointerException); + assertNull(appsController.getLeftMenuItems(mockedRequest, mockedResponse)); + } + + @Test + public void getAppThumbnailExceptionTest() + { + EPApp app = null; + assertNull(appsController.getAppThumbnail(mockedRequest, (long) 1, mockedResponse)); + } + + @Test + public void getAppThumbnailTest() + { + EPApp app = new EPApp(); + app.setName("Test"); + app.setImageUrl("test"); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 1); + app.setAppType(1); + app.setImageUrl("www.ecomp.com"); + app.setThumbnail(new byte[] {1, 6, 3}); + Mockito.when(appService.getApp((long) 1)).thenReturn(app); + HttpEntity<byte[]> response = appsController.getAppThumbnail(mockedRequest, (long) 1, mockedResponse); + assertEquals(response.getHeaders().getContentLength(), 3); + } + + @Test + public void getAppThumbnailForMediaTypePngTest() + { + + EPApp app = new EPApp(); + app.setName("Test"); + app.setImageUrl("test"); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 1); + app.setAppType(1); + app.setImageUrl("www.ecomp.png"); + app.setThumbnail(new byte[] {1, 6, 3}); + Mockito.when(appService.getApp((long) 1)).thenReturn(app); + PowerMockito.mockStatic(MediaType.class); + HttpEntity<byte[]> response = appsController.getAppThumbnail(mockedRequest, (long) 1, mockedResponse); + assertEquals(response.getHeaders().getContentLength(), 3); + } + + @Test + public void getUserAppsOrderBySortPrefIfUSerNullTest(){ + List<EcompApp> listOfApps = new ArrayList<EcompApp>(); + + EcompApp app = new EcompApp(); + listOfApps.add(app); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(null); + assertNull(appsController.getUserAppsOrderBySortPref(mockedRequest, mockedResponse)); + } + + @Test + public void getUserAppsOrderBySortPrefTest(){ + List<EcompApp> listOfApps = new ArrayList<EcompApp>(); + + EcompApp app = new EcompApp(); + listOfApps.add(app); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(mockedRequest.getParameter("mparams")).thenReturn(""); + Mockito.when(appService.transformAppsToEcompApps(appService.getAppsOrderByName(user))).thenReturn(listOfApps); + List<EcompApp> listOfActualApps = appsController.getUserAppsOrderBySortPref(mockedRequest, mockedResponse); + assertEquals(listOfActualApps.size(), 1); + } + + @Test + public void getUserAppsOrderBySortPrefIfusrSortPrefIsMTest(){ + List<EcompApp> listOfApps = new ArrayList<EcompApp>(); + + EcompApp app = new EcompApp(); + listOfApps.add(app); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(mockedRequest.getParameter("mparams")).thenReturn("M"); + Mockito.when(appService.transformAppsToEcompApps(appService.getAppsOrderByName(user))).thenReturn(listOfApps); + List<EcompApp> listOfActualApps = appsController.getUserAppsOrderBySortPref(mockedRequest, mockedResponse); + assertEquals(listOfActualApps.size(), 1); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/AuditLogControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/AuditLogControllerTest.java new file mode 100644 index 00000000..971089ee --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/AuditLogControllerTest.java @@ -0,0 +1,102 @@ +package org.openecomp.portalapp.portal.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.AuditLogController; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.service.AuditService; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(EPUserUtils.class) +public class AuditLogControllerTest { + + + @Mock + AuditService auditService; + + @InjectMocks + AuditLogController auditLogController = new AuditLogController(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + MockEPUser mockUser = new MockEPUser(); + @Test + public void auditLogTest() + { + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EPUserUtils.getUserId(mockedRequest)).thenReturn((int)1); + auditLogController.auditLog(mockedRequest, "1", "app", "test"); + } + + @Test + public void auditLogTabTest() + { + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EPUserUtils.getUserId(mockedRequest)).thenReturn((int)1); + auditLogController.auditLog(mockedRequest, "1", "tab", "test"); + } + + @Test + public void auditLogfunctionalTest() + { + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EPUserUtils.getUserId(mockedRequest)).thenReturn((int)1); + auditLogController.auditLog(mockedRequest, "1", "functional", "test"); + } + + @Test + public void auditLogleftMenuTest() + { + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EPUserUtils.getUserId(mockedRequest)).thenReturn((int)1); + auditLogController.auditLog(mockedRequest, "1", "leftMenu", "test"); + } + + @Test(expected = NumberFormatException.class) + public void auditLogExceptionTest() + { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EPUserUtils.getUserId(mockedRequest)).thenReturn((int)1); + auditLogController.auditLog(mockedRequest, "1", "app", "test"); + } + + @Test + public void auditLogerrorTest() + { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenThrow(nullPointerException); + auditLogController.auditLog(mockedRequest, "1", "app", "test"); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/BEPropertyReaderControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/BEPropertyReaderControllerTest.java new file mode 100644 index 00000000..ec8d0e79 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/BEPropertyReaderControllerTest.java @@ -0,0 +1,72 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.assertTrue; + +import javax.servlet.http.HttpServletRequest; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.BEPropertyReaderController; +import org.openecomp.portalapp.portal.domain.BEProperty; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(SystemProperties.class) +public class BEPropertyReaderControllerTest extends MockitoTestSuite { + + @InjectMocks + BEPropertyReaderController bEPropertyReaderController = new BEPropertyReaderController(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + + NullPointerException nullPointerException = new NullPointerException(); + + @Test + public void readPropertyTest() { + String key = "DOMAIN_CLASS_LOCATION"; + BEProperty beProperty = new BEProperty("DOMAIN_CLASS_LOCATION", "domain_class_location"); + PortalRestResponse<BEProperty> ecpectedPortalRestResponse = new PortalRestResponse<BEProperty>(); + ecpectedPortalRestResponse.setMessage("success"); + ecpectedPortalRestResponse.setResponse(beProperty); + ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); + PortalRestResponse<BEProperty> actualPortalRestResponse = null; + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.getProperty("DOMAIN_CLASS_LOCATION")).thenReturn("domain_class_location"); + actualPortalRestResponse = bEPropertyReaderController.readProperty(mockedRequest, key); + assertTrue(actualPortalRestResponse.equals(ecpectedPortalRestResponse)); + + } + + @Test + public void readPropertyExceptionTest() { + String key =null; + //BEProperty beProperty = new BEProperty("DOMAIN_CLASS_LOCATION", "domain_class_location"); + PortalRestResponse<BEProperty> ecpectedPortalRestResponse = new PortalRestResponse<BEProperty>(); + ecpectedPortalRestResponse.setMessage("java.lang.NullPointerException"); + ecpectedPortalRestResponse.setResponse(null); + ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + PortalRestResponse<BEProperty> actualPortalRestResponse = null; + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(new BEProperty(key, SystemProperties.getProperty(key))).thenThrow(nullPointerException); + actualPortalRestResponse = bEPropertyReaderController.readProperty(mockedRequest, key); + assertTrue(actualPortalRestResponse.equals(ecpectedPortalRestResponse)); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/BasicAuthAccountControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/BasicAuthAccountControllerTest.java new file mode 100644 index 00000000..793d6878 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/BasicAuthAccountControllerTest.java @@ -0,0 +1,264 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.BasicAuthAccountController; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.portal.domain.BasicAuthCredentials; +import org.openecomp.portalapp.portal.domain.EPEndpoint; +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.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.AdminRolesServiceImpl; +import org.openecomp.portalapp.portal.service.BasicAuthAccountService; +import org.openecomp.portalapp.portal.service.BasicAuthAccountServiceImpl; +import org.openecomp.portalapp.util.EPUserUtils; + +public class BasicAuthAccountControllerTest extends MockitoTestSuite { + + @Mock + BasicAuthAccountService basicAuthAccountService = new BasicAuthAccountServiceImpl(); + + @Mock + AdminRolesService adminRolesService = new AdminRolesServiceImpl(); + + @InjectMocks + BasicAuthAccountController basicAuthAccountController = new BasicAuthAccountController(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + + @Mock + EPUserUtils ePUserUtils = new EPUserUtils(); + + MockEPUser mockUser = new MockEPUser(); + + public BasicAuthCredentials basicAuthCredentials() { + BasicAuthCredentials basicAuthCredentials = new BasicAuthCredentials(); + + basicAuthCredentials.setId((long) 1); + basicAuthCredentials.setApplicationName("test"); + basicAuthCredentials.setUsername("Test"); + basicAuthCredentials.setPassword("Password"); + basicAuthCredentials.setIsActive("YES"); + + List<EPEndpoint> endpoints = new ArrayList<EPEndpoint>(); + + EPEndpoint ePEndpoint = new EPEndpoint(); + ePEndpoint.setId((long) 1); + ePEndpoint.setName("Test"); + endpoints.add(ePEndpoint); + basicAuthCredentials.setEndpoints(endpoints); + + return basicAuthCredentials; + + } + + @Test + public void createBasicAuthAccountTest() throws Exception { + BasicAuthCredentials basicAuthCredentials = basicAuthCredentials(); + + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + PortalRestResponse<String> expectedResponse = new PortalRestResponse<String>(); + expectedResponse.setMessage("SUCCESS"); + expectedResponse.setResponse(""); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedResponse.setStatus(portalRestStatusEnum.OK); + long accountd = 1; + + Mockito.when(basicAuthAccountService.saveBasicAuthAccount(basicAuthCredentials)).thenReturn(accountd); + + PortalRestResponse<String> actualResponse = basicAuthAccountController.createBasicAuthAccount(mockedRequest, + mockedResponse, basicAuthCredentials); + assertEquals(actualResponse, expectedResponse); + } + + @Test + public void createBasicAuthAccountAdminTest() throws Exception { + BasicAuthCredentials basicAuthCredentials = basicAuthCredentials(); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + PortalRestResponse<String> expectedResponse = new PortalRestResponse<String>(); + expectedResponse.setMessage("Authorization Required"); + expectedResponse.setResponse("Admin Only Operation! "); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedResponse.setStatus(portalRestStatusEnum.ERROR); + + PortalRestResponse<String> actualResponse = basicAuthAccountController.createBasicAuthAccount(mockedRequest, + mockedResponse, basicAuthCredentials); + assertEquals(actualResponse, expectedResponse); + } + + @Test + public void createBasicAuthAccountIfInputNullTest() throws Exception { + BasicAuthCredentials basicAuthCredentials = null; + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + PortalRestResponse<String> expectedResponse = new PortalRestResponse<String>(); + expectedResponse.setMessage("FAILURE"); + expectedResponse.setResponse("newBasicAuthAccount cannot be null or empty"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedResponse.setStatus(portalRestStatusEnum.ERROR); + PortalRestResponse<String> actualResponse = basicAuthAccountController.createBasicAuthAccount(mockedRequest, + mockedResponse, basicAuthCredentials); + assertEquals(actualResponse, expectedResponse); + } + + @Test + public void getBasicAuthAccountTest() throws Exception { + PortalRestResponse<List<BasicAuthCredentials>> expectedPortalResponse = new PortalRestResponse<List<BasicAuthCredentials>>(); + List<BasicAuthCredentials> basicAuthCredentialsList = new ArrayList<BasicAuthCredentials>(); + BasicAuthCredentials basicAuthCredentials = basicAuthCredentials(); + basicAuthCredentialsList.add(basicAuthCredentials); + + expectedPortalResponse.setMessage("Success"); + expectedPortalResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedPortalResponse.setStatus(portalRestStatusEnum.OK); + + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(basicAuthAccountService.getAccountData()).thenReturn(null); + PortalRestResponse<List<BasicAuthCredentials>> actualResponse = basicAuthAccountController + .getBasicAuthAccount(mockedRequest, mockedResponse); + assertEquals(expectedPortalResponse, actualResponse); + } + + @Test + public void getBasicAuthAccountIfSuperAdminTest() throws Exception { + PortalRestResponse<List<BasicAuthCredentials>> expectedPortalResponse = new PortalRestResponse<List<BasicAuthCredentials>>(); + List<BasicAuthCredentials> basicAuthCredentialsList = new ArrayList<BasicAuthCredentials>(); + BasicAuthCredentials basicAuthCredentials = basicAuthCredentials(); + basicAuthCredentialsList.add(basicAuthCredentials); + + expectedPortalResponse.setMessage("UnAuthorized! Admin Only Operation"); + expectedPortalResponse.setResponse(new ArrayList<>()); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedPortalResponse.setStatus(portalRestStatusEnum.ERROR); + + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + Mockito.when(basicAuthAccountService.getAccountData()).thenReturn(null); + PortalRestResponse<List<BasicAuthCredentials>> actualResponse = basicAuthAccountController + .getBasicAuthAccount(mockedRequest, mockedResponse); + assertEquals(expectedPortalResponse, actualResponse); + } + + @Test + public void updateAccountTest() throws Exception { + BasicAuthCredentials basicAuthCredentials = basicAuthCredentials(); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + PortalRestResponse<String> expectedResponse = new PortalRestResponse<String>(); + expectedResponse.setMessage("SUCCESS"); + expectedResponse.setResponse(""); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedResponse.setStatus(portalRestStatusEnum.OK); + long accountd = 1; + PortalRestResponse<String> actualResponse = basicAuthAccountController.updateAccount(mockedRequest, + mockedResponse, accountd, basicAuthCredentials); + assertEquals(actualResponse, expectedResponse); + } + + @Test + public void updateAccountIfSuperAdminTest() throws Exception { + BasicAuthCredentials basicAuthCredentials = basicAuthCredentials(); + + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + PortalRestResponse<String> expectedResponse = new PortalRestResponse<String>(); + expectedResponse.setMessage("Authorization Required"); + expectedResponse.setResponse("Admin Only Operation! "); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedResponse.setStatus(portalRestStatusEnum.ERROR); + long accountd = 1; + PortalRestResponse<String> actualResponse = basicAuthAccountController.updateAccount(mockedRequest, + mockedResponse, accountd, basicAuthCredentials); + assertEquals(actualResponse, expectedResponse); + } + + @Test + public void updateAccountIfInputNullTest() throws Exception { + BasicAuthCredentials basicAuthCredentials = null; + + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + PortalRestResponse<String> expectedResponse = new PortalRestResponse<String>(); + expectedResponse.setMessage("FAILURE"); + expectedResponse.setResponse("BasicAuthCredentials cannot be null or empty"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedResponse.setStatus(portalRestStatusEnum.ERROR); + long accountd = 1; + PortalRestResponse<String> actualResponse = basicAuthAccountController.updateAccount(mockedRequest, + mockedResponse, accountd, basicAuthCredentials); + assertEquals(actualResponse, expectedResponse); + } + + @Test + public void deleteAccountTest() throws Exception { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + + PortalRestResponse<String> expectedResponse = new PortalRestResponse<String>(); + expectedResponse.setMessage("SUCCESS"); + expectedResponse.setResponse(""); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedResponse.setStatus(portalRestStatusEnum.OK); + long accountd = 1; + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + PortalRestResponse<String> actualResponse = basicAuthAccountController.deleteAccount(mockedRequest, + mockedResponse, accountd); + assertEquals(actualResponse, expectedResponse); + } + + @Test + public void deleteAccountIfNotSuperAdminTest() throws Exception { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + + PortalRestResponse<String> expectedResponse = new PortalRestResponse<String>(); + expectedResponse.setMessage("Authorization Required"); + expectedResponse.setResponse("Admin Only Operation! "); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedResponse.setStatus(portalRestStatusEnum.ERROR); + long accountd = 1; + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + PortalRestResponse<String> actualResponse = basicAuthAccountController.deleteAccount(mockedRequest, + mockedResponse, accountd); + System.out.println(actualResponse); + assertEquals(actualResponse, expectedResponse); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/CommonWidgetControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/CommonWidgetControllerTest.java new file mode 100644 index 00000000..d6d149a4 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/CommonWidgetControllerTest.java @@ -0,0 +1,84 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.assertTrue; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.CommonWidgetController; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.service.DashboardSearchService; +import org.openecomp.portalapp.portal.service.DashboardSearchServiceImpl; +import org.openecomp.portalapp.portal.transport.CommonWidgetMeta; + +public class CommonWidgetControllerTest { + + @Mock + DashboardSearchService dashboardSearchService = new DashboardSearchServiceImpl(); + + @InjectMocks + CommonWidgetController commonWidgetController = new CommonWidgetController(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + + @SuppressWarnings("unchecked") + @Test + public void getWidgetDataTest() { + String resourceType = "Test"; + PortalRestResponse<CommonWidgetMeta> acutualPoratlRestResponse = null; + @SuppressWarnings("rawtypes") + PortalRestResponse ecpectedPortalRestResponse = new PortalRestResponse(); + ecpectedPortalRestResponse.setMessage("Unexpected resource type Test"); + ecpectedPortalRestResponse.setResponse(null); + ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + acutualPoratlRestResponse = commonWidgetController.getWidgetData(mockedRequest, resourceType); + assertTrue(acutualPoratlRestResponse.equals(ecpectedPortalRestResponse)); + + } + + @SuppressWarnings("unchecked") + @Test + public void getWidgetDataTestNew() { + String resourceType = "EVENTS"; + PortalRestResponse<CommonWidgetMeta> acutualPoratlRestResponse = null; + @SuppressWarnings("rawtypes") + PortalRestResponse ecpectedPortalRestResponse = new PortalRestResponse(); + ecpectedPortalRestResponse.setMessage("success"); + ecpectedPortalRestResponse.setResponse(null); + ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); + acutualPoratlRestResponse = commonWidgetController.getWidgetData(mockedRequest, resourceType); + assertTrue(acutualPoratlRestResponse.equals(ecpectedPortalRestResponse)); + + } + + @SuppressWarnings("unchecked") + @Test + public void getWidgetDataExceptionTest() { + String resourceType = "null"; + PortalRestResponse<CommonWidgetMeta> acutualPoratlRestResponse = null; + @SuppressWarnings("rawtypes") + PortalRestResponse ecpectedPortalRestResponse = new PortalRestResponse(); + ecpectedPortalRestResponse.setMessage("Unexpected resource type null"); + ecpectedPortalRestResponse.setResponse(null); + ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + acutualPoratlRestResponse = commonWidgetController.getWidgetData(mockedRequest, resourceType); + assertTrue(acutualPoratlRestResponse.equals(ecpectedPortalRestResponse)); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/ConsulClientControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/ConsulClientControllerTest.java new file mode 100644 index 00000000..672f4212 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/ConsulClientControllerTest.java @@ -0,0 +1,142 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.ConsulClientController; +import org.openecomp.portalapp.portal.domain.BEProperty; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.service.ConsulHealthService; +import org.openecomp.portalapp.portal.service.ConsulHealthServiceImpl; + +import com.orbitz.consul.ConsulException; +import com.orbitz.consul.model.health.ServiceHealth; + +import io.searchbox.client.config.exception.NoServerConfiguredException; + +public class ConsulClientControllerTest { + + @Mock + ConsulHealthService consulHealthService = new ConsulHealthServiceImpl(); + + @InjectMocks + ConsulClientController consulClientController = new ConsulClientController(); + + NoServerConfiguredException noServerConfiguredException = new NoServerConfiguredException(null); + + String service = "Test"; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + ConsulException consulException = new ConsulException(nullPointerException); + + @Test + public void getServiceLocationTest() { + PortalRestResponse<BEProperty> ecpectedPortalRestResponse = new PortalRestResponse<BEProperty>(); + ecpectedPortalRestResponse.setMessage("Success!"); + ecpectedPortalRestResponse.setResponse(null); + ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); + PortalRestResponse<String> actualPortalRestRespone = new PortalRestResponse<String>(); + actualPortalRestRespone = consulClientController.getServiceLocation(mockedRequest, mockedResponse, service); + assertTrue(actualPortalRestRespone.equals(ecpectedPortalRestResponse)); + } + + @Test + public void getServiceLocationExceptionTest() { + PortalRestResponse<BEProperty> ecpectedPortalRestResponse = new PortalRestResponse<BEProperty>(); + ecpectedPortalRestResponse.setMessage("Warning!"); + ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.WARN); + PortalRestResponse<String> actualPortalRestRespone = new PortalRestResponse<String>(); + Mockito.when(consulHealthService.getServiceLocation(service, null)).thenThrow(noServerConfiguredException); + actualPortalRestRespone = consulClientController.getServiceLocation(mockedRequest, mockedResponse, service); + assertTrue(actualPortalRestRespone.getMessage().equals(ecpectedPortalRestResponse.getMessage())); + assertTrue(actualPortalRestRespone.getStatus().equals(ecpectedPortalRestResponse.getStatus())); + + } + + @Test + public void getServiceLocationExceptionConsulExceptionTest() { + PortalRestResponse<BEProperty> ecpectedPortalRestResponse = new PortalRestResponse<BEProperty>(); + ecpectedPortalRestResponse.setMessage("Error!"); + ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + PortalRestResponse<String> actualPortalRestRespone = new PortalRestResponse<String>(); + Mockito.when(consulHealthService.getServiceLocation(service, null)).thenThrow(consulException); + actualPortalRestRespone = consulClientController.getServiceLocation(mockedRequest, mockedResponse, service); + assertTrue(actualPortalRestRespone.getMessage().equals(ecpectedPortalRestResponse.getMessage())); + assertTrue(actualPortalRestRespone.getStatus().equals(ecpectedPortalRestResponse.getStatus())); + } + + public PortalRestResponse<List<ServiceHealth>> successResponse() { + PortalRestResponse<List<ServiceHealth>> ecpectedPortalRestResponse = new PortalRestResponse<List<ServiceHealth>>(); + List<ServiceHealth> healths = new ArrayList<ServiceHealth>(); + ecpectedPortalRestResponse.setMessage("Success!"); + ecpectedPortalRestResponse.setResponse(healths); + ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); + return ecpectedPortalRestResponse; + } + + public PortalRestResponse<List<ServiceHealth>> errorResponse() { + PortalRestResponse<List<ServiceHealth>> ecpectedPortalRestResponse = new PortalRestResponse<List<ServiceHealth>>(); + List<ServiceHealth> healths = new ArrayList<ServiceHealth>(); + ecpectedPortalRestResponse.setMessage("Error!"); + ecpectedPortalRestResponse.setResponse(healths); + ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + return ecpectedPortalRestResponse; + } + + @Test + public void getAllHealthyNodesTest() { + PortalRestResponse<List<ServiceHealth>> ecpectedPortalRestResponse = successResponse(); + PortalRestResponse<List<ServiceHealth>> actualPortalRestRespone = new PortalRestResponse<List<ServiceHealth>>(); + actualPortalRestRespone = consulClientController.getAllHealthyNodes(mockedRequest, mockedResponse, service); + assertTrue(actualPortalRestRespone.equals(ecpectedPortalRestResponse)); + + } + + @Test + public void getAllHealthyNodesExceptionTest() { + PortalRestResponse<List<ServiceHealth>> ecpectedPortalRestResponse = errorResponse(); + PortalRestResponse<List<ServiceHealth>> actualPortalRestRespone = new PortalRestResponse<List<ServiceHealth>>(); + Mockito.when(consulHealthService.getAllHealthyNodes(service)).thenThrow(consulException); + actualPortalRestRespone = consulClientController.getAllHealthyNodes(mockedRequest, mockedResponse, service); + assertTrue(actualPortalRestRespone.equals(ecpectedPortalRestResponse)); + } + + @Test + public void getAllNodesTest() { + PortalRestResponse<List<ServiceHealth>> ecpectedPortalRestResponse = successResponse(); + PortalRestResponse<List<ServiceHealth>> actualPortalRestRespone = new PortalRestResponse<List<ServiceHealth>>(); + actualPortalRestRespone = consulClientController.getAllNodes(mockedRequest, mockedResponse, service); + assertTrue(actualPortalRestRespone.equals(ecpectedPortalRestResponse)); + } + + @Test + public void getAllNodesExceptionTest() { + PortalRestResponse<List<ServiceHealth>> ecpectedPortalRestResponse = errorResponse(); + PortalRestResponse<List<ServiceHealth>> actualPortalRestRespone = new PortalRestResponse<List<ServiceHealth>>(); + Mockito.when(consulHealthService.getAllNodes(service)).thenThrow(consulException); + actualPortalRestRespone = consulClientController.getAllNodes(mockedRequest, mockedResponse, service); + assertTrue(actualPortalRestRespone.equals(ecpectedPortalRestResponse)); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/DashboardControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/DashboardControllerTest.java new file mode 100644 index 00000000..d861955c --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/DashboardControllerTest.java @@ -0,0 +1,427 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.DashboardController; +import org.openecomp.portalapp.portal.core.MockEPUser; +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.service.DashboardSearchService; +import org.openecomp.portalapp.portal.service.DashboardSearchServiceImpl; +import org.openecomp.portalapp.portal.transport.CommonWidget; +import org.openecomp.portalapp.portal.transport.CommonWidgetMeta; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.domain.support.CollaborateList; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({EPUserUtils.class, CollaborateList.class, SystemProperties.class, EPCommonSystemProperties.class}) +public class DashboardControllerTest { + + @Mock + DashboardSearchService searchService = new DashboardSearchServiceImpl(); + + @InjectMocks + DashboardController dashboardController = new DashboardController(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + + NullPointerException nullPointerException = new NullPointerException(); + + MockEPUser mockUser = new MockEPUser(); + + public CommonWidgetMeta mockCommonWidgetMeta() { + CommonWidgetMeta commonWidgetMeta= new CommonWidgetMeta(); + List<CommonWidget> widgetList = new ArrayList<>(); + CommonWidget commonWidget = new CommonWidget(); + commonWidget.setId((long) 1); + commonWidget.setCategory("test"); + commonWidget.setHref("testhref"); + commonWidget.setTitle("testTitle"); + commonWidget.setContent("testcontent"); + commonWidget.setEventDate("testDate"); + commonWidget.setSortOrder(1); + widgetList.add(commonWidget); + commonWidgetMeta.setItems(widgetList); + + return commonWidgetMeta; + } + + public CommonWidget mockCommonWidget() { + + CommonWidget commonWidget = new CommonWidget(); + commonWidget.setId((long) 1); + commonWidget.setCategory("test"); + commonWidget.setHref("testhref"); + commonWidget.setTitle("testTitle"); + commonWidget.setContent("testcontent"); + commonWidget.setEventDate("testDate"); + commonWidget.setSortOrder(1); + + return commonWidget; + } + + + @Test + public void getWidgetDataTest() throws IOException { + + String resourceType = null; + PortalRestResponse<CommonWidgetMeta> expectedData = new PortalRestResponse<CommonWidgetMeta>(); + expectedData.setStatus(PortalRestStatusEnum.ERROR); + expectedData.setMessage("Unexpected resource type null"); + expectedData.setResponse(null); + + PortalRestResponse<CommonWidgetMeta> actualResponse = dashboardController.getWidgetData(mockedRequest, resourceType); + assertEquals(expectedData,actualResponse); + } + + @Test + public void getWidgetDataWithValidResourceTest() throws IOException { + String resourceType = "EVENTS"; + CommonWidgetMeta commonWidgetMeta= mockCommonWidgetMeta(); + commonWidgetMeta.setCategory(null); + + Mockito.when(searchService.getWidgetData(resourceType)).thenReturn(commonWidgetMeta); + PortalRestResponse<CommonWidgetMeta> expectedData = new PortalRestResponse<CommonWidgetMeta>(); + expectedData.setStatus(PortalRestStatusEnum.OK); + expectedData.setMessage("success"); + expectedData.setResponse(commonWidgetMeta); + + PortalRestResponse<CommonWidgetMeta> actualResponse = dashboardController.getWidgetData(mockedRequest, resourceType); + System.out.println(actualResponse); + assertEquals(expectedData,actualResponse); + } + + @Test + public void saveWidgetDataBulkNullTest() throws IOException { + CommonWidgetMeta commonWidgetMeta= mockCommonWidgetMeta(); + commonWidgetMeta.setCategory(null); + + PortalRestResponse<String> expectedData = new PortalRestResponse<String>(); + expectedData.setStatus(PortalRestStatusEnum.ERROR); + expectedData.setMessage("ERROR"); + expectedData.setResponse("Category cannot be null or empty"); + + PortalRestResponse<String> actualResponse = dashboardController.saveWidgetDataBulk(commonWidgetMeta); + assertEquals(expectedData,actualResponse); + } + + @Test + public void saveWidgetUnexpectedDataBulkTest() throws IOException { + CommonWidgetMeta commonWidgetMeta= mockCommonWidgetMeta(); + commonWidgetMeta.setCategory("Unexpected Data"); + + PortalRestResponse<String> expectedData = new PortalRestResponse<String>(); + expectedData.setStatus(PortalRestStatusEnum.ERROR); + expectedData.setMessage("Unexpected resource type Unexpected Data"); + expectedData.setResponse(null); + + PortalRestResponse<String> actualResponse = dashboardController.saveWidgetDataBulk(commonWidgetMeta); + assertEquals(expectedData,actualResponse); + + } + + @Test + public void saveWidgetInvalidDataBulkTest() throws IOException { + CommonWidgetMeta commonWidgetMeta= mockCommonWidgetMeta(); + commonWidgetMeta.setCategory("EVENTS"); + + PortalRestResponse<String> expectedData = new PortalRestResponse<String>(); + expectedData.setStatus(PortalRestStatusEnum.ERROR); + expectedData.setMessage("Invalid category: test"); + expectedData.setResponse(null); + + PortalRestResponse<String> actualResponse = dashboardController.saveWidgetDataBulk(commonWidgetMeta); + assertEquals(expectedData,actualResponse); + } + + @Test + public void saveWidgetDataBulkTest() throws IOException { + + List<CommonWidget> widgetList = new ArrayList<>(); + CommonWidget commonWidget = new CommonWidget("EVENTS", "http://test.com", "testTitle", "testcontent", "2017-07-01", 1); + widgetList.add(commonWidget); + CommonWidgetMeta commonWidgetMeta= new CommonWidgetMeta("EVENTS", widgetList); + + + + /* commonWidgetMeta.setItems(widgetList); + + commonWidgetMeta.setCategory("EVENTS");*/ + + PortalRestResponse<String> expectedData = new PortalRestResponse<String>(); + expectedData.setStatus(PortalRestStatusEnum.OK); + expectedData.setMessage("success"); + expectedData.setResponse("success"); + + Mockito.when(searchService.saveWidgetDataBulk(commonWidgetMeta)).thenReturn("success"); + + PortalRestResponse<String> actualResponse = dashboardController.saveWidgetDataBulk(commonWidgetMeta); + assertEquals(expectedData,actualResponse); + } + + @Test + public void saveWidgetDataNullTest() throws IOException { + + CommonWidget commonWidget = mockCommonWidget(); + commonWidget.setId((long)1); + commonWidget.setContent("test"); + commonWidget.setCategory(null); + PortalRestResponse<String> expectedData = new PortalRestResponse<String>(); + expectedData.setStatus(PortalRestStatusEnum.ERROR); + expectedData.setMessage("ERROR"); + expectedData.setResponse("Category cannot be null or empty"); + + PortalRestResponse<String> actualResponse = dashboardController.saveWidgetData(commonWidget); + assertEquals(expectedData,actualResponse); + + } + + @Test + public void saveWidgetDataErrorTest() throws IOException { + + CommonWidget commonWidget = mockCommonWidget(); + PortalRestResponse<String> expectedData = new PortalRestResponse<String>(); + expectedData.setStatus(PortalRestStatusEnum.ERROR); + expectedData.setMessage("Invalid category: test"); + expectedData.setResponse(null); + + PortalRestResponse<String> actualResponse = dashboardController.saveWidgetData(commonWidget); + assertEquals(expectedData,actualResponse); + } + + @Test + public void saveWidgetDataTest() throws IOException { + + CommonWidgetMeta commonWidgetMeta= new CommonWidgetMeta(); + List<CommonWidget> widgetList = new ArrayList<>(); + CommonWidget commonWidget = new CommonWidget(); + commonWidget.setId((long) 1); + commonWidget.setCategory("EVENTS"); + commonWidget.setHref("http://test.com"); + commonWidget.setTitle("testTitle"); + commonWidget.setContent("testcontent"); + commonWidget.setEventDate("2017-07-01"); + commonWidget.setSortOrder(1); + widgetList.add(commonWidget); + commonWidgetMeta.setItems(widgetList); + + commonWidgetMeta.setCategory("EVENTS"); + + PortalRestResponse<String> expectedData = new PortalRestResponse<String>(); + expectedData.setStatus(PortalRestStatusEnum.OK); + expectedData.setMessage("success"); + expectedData.setResponse("success"); + + Mockito.when(searchService.saveWidgetData(commonWidget)).thenReturn("success"); + + PortalRestResponse<String> actualResponse = dashboardController.saveWidgetData(commonWidget); + assertEquals(expectedData,actualResponse); + + } + + @Test + public void deleteWidgetDataTest() throws IOException { + + CommonWidget commonWidget = mockCommonWidget(); + + PortalRestResponse<String> expectedData = new PortalRestResponse<String>(); + expectedData.setStatus(PortalRestStatusEnum.OK); + expectedData.setMessage("success"); + expectedData.setResponse(null); + + Mockito.when(searchService.saveWidgetData(commonWidget)).thenReturn("success"); + + PortalRestResponse<String> actualResponse = dashboardController.deleteWidgetData(commonWidget); + assertEquals(expectedData,actualResponse); + + } + + @Test + public void getActiveUsersTest(){ + List<String> activeUsers = new ArrayList<>(); + List<String> expectedUsersList = new ArrayList<>(); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + String userId = user.getOrgUserId(); + Mockito.when(searchService.getRelatedUsers(userId)).thenReturn(activeUsers); + expectedUsersList= dashboardController.getActiveUsers(mockedRequest); + assertEquals(expectedUsersList, activeUsers); + } + + + @Test + public void getActiveUsersExceptionTest(){ + List<String> activeUsers = new ArrayList<>(); + List<String> expectedUsersList = new ArrayList<>(); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + String userId = user.getOrgUserId(); + Mockito.when(searchService.getRelatedUsers(userId)).thenThrow(nullPointerException); + expectedUsersList = dashboardController.getActiveUsers(mockedRequest); + assertEquals(expectedUsersList, activeUsers); + } + + @Test + public void getOnlineUserUpdateRateTest(){ + PortalRestResponse<String> expectedData = new PortalRestResponse<String>(); + expectedData.setStatus(PortalRestStatusEnum.OK); + expectedData.setMessage("success"); + expectedData.setResponse("{onlineUserUpdateRate=1400000, onlineUserUpdateDuration=1400000}"); + + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_RATE)).thenReturn("1400"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_DURATION)).thenReturn("1400"); + + PortalRestResponse<Map<String, String>> actualResponse = dashboardController.getOnlineUserUpdateRate(mockedRequest); + assertEquals(expectedData.getStatus(),actualResponse.getStatus()); + } + + @Test + public void getOnlineUserUpdateRateExceptionTest(){ + PortalRestResponse<String> expectedData = new PortalRestResponse<String>(); + expectedData.setStatus(PortalRestStatusEnum.ERROR); + expectedData.setMessage("java.lang.NullPointerException"); + expectedData.setResponse(null); + + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_RATE)).thenThrow(nullPointerException); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.ONLINE_USER_UPDATE_DURATION)).thenThrow(nullPointerException); + + PortalRestResponse<Map<String, String>> actualResponse = dashboardController.getOnlineUserUpdateRate(mockedRequest); + assertEquals(expectedData,actualResponse); + } + + @Test + public void getWindowWidthThresholdForRightMenuTest(){ + PortalRestResponse<String> expectedData = new PortalRestResponse<String>(); + expectedData.setStatus(PortalRestStatusEnum.OK); + expectedData.setMessage("success"); + expectedData.setResponse("{windowWidth=1400}"); + + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_RIGHT_MENU)).thenReturn("1400"); + + PortalRestResponse<Map<String, String>> actualResponse = dashboardController.getWindowWidthThresholdForRightMenu(mockedRequest); + assertEquals(expectedData.getStatus(),actualResponse.getStatus()); + } + + @Test + public void getWindowWidthThresholdForRightMenuExceptionTest(){ + PortalRestResponse<String> expectedData = new PortalRestResponse<String>(); + expectedData.setStatus(PortalRestStatusEnum.ERROR); + expectedData.setMessage("java.lang.NullPointerException"); + expectedData.setResponse(null); + + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_RIGHT_MENU)).thenThrow(nullPointerException); + + PortalRestResponse<Map<String, String>> actualResponse = dashboardController.getWindowWidthThresholdForRightMenu(mockedRequest); + assertEquals(expectedData,actualResponse); + } + + @Test + public void getWindowWidthThresholdForLeftMenuTest(){ + PortalRestResponse<String> expectedData = new PortalRestResponse<String>(); + expectedData.setStatus(PortalRestStatusEnum.OK); + expectedData.setMessage("success"); + expectedData.setResponse("{windowWidth=1400}"); + + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_LEFT_MENU)).thenReturn("1400"); + + PortalRestResponse<Map<String, String>> actualResponse = dashboardController.getWindowWidthThresholdForLeftMenu(mockedRequest); + assertEquals(expectedData.getStatus(),actualResponse.getStatus()); + } + + @Test + public void getWindowWidthThresholdForLeftMenuExceptionTest(){ + PortalRestResponse<String> expectedData = new PortalRestResponse<String>(); + expectedData.setStatus(PortalRestStatusEnum.ERROR); + expectedData.setMessage("java.lang.NullPointerException"); + expectedData.setResponse(null); + + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WINDOW_WIDTH_THRESHOLD_LEFT_MENU)).thenThrow(nullPointerException); + + PortalRestResponse<Map<String, String>> actualResponse = dashboardController.getWindowWidthThresholdForLeftMenu(mockedRequest); + assertEquals(expectedData,actualResponse); + } + + @Test + public void getActiveUsersNullTest(){ + PortalRestResponse<List<String>> expectedData = new PortalRestResponse<List<String>>(); + expectedData.setStatus(PortalRestStatusEnum.ERROR); + expectedData.setMessage("User object is null? - check logs"); + expectedData.setResponse(new ArrayList<>()); + + PortalRestResponse<List<String>> actualResponse = dashboardController.activeUsers(mockedRequest); + assertEquals(expectedData,actualResponse); + } + + @Test + public void activeUsersTest(){ + EPUser user = mockUser.mockEPUser(); + PortalRestResponse<List<String>> expectedData = new PortalRestResponse<List<String>>(); + expectedData.setStatus(PortalRestStatusEnum.OK); + expectedData.setMessage("success"); + expectedData.setResponse(new ArrayList<>()); + PowerMockito.mockStatic(EPUserUtils.class); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + PortalRestResponse<List<String>> actualResponse = dashboardController.activeUsers(mockedRequest); + assertEquals(expectedData,actualResponse); + } + +// @Test +// public void activeUsersExceptionTest(){ +// EPUser user = mockUser.mockEPUser(); +// user.setLoginId("test"); +// String loginId = "abc"; +// PortalRestResponse<List<String>> expectedData = new PortalRestResponse<List<String>>(); +// expectedData.setStatus(PortalRestStatusEnum.ERROR); +// expectedData.setMessage("java.lang.NullPointerException"); +// expectedData.setResponse(null); +// +//// PowerMockito.mockStatic(EPUserUtils.class); +// Mockito.when(searchService.getRelatedUsers(user.getLoginId(user.getLoginId()))).thenReturn(nullPointerException); +// PortalRestResponse<List<String>> actualResponse = dashboardController.activeUsers(mockedRequest); +// System.out.println(actualResponse); +// //assertEquals(expectedData,actualResponse); +// } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/DashboardSearchResultControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/DashboardSearchResultControllerTest.java new file mode 100644 index 00000000..7f87c151 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/DashboardSearchResultControllerTest.java @@ -0,0 +1,366 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.DashboardSearchResultController; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem; +import org.openecomp.portalapp.portal.service.DashboardSearchService; +import org.openecomp.portalapp.portal.service.DashboardSearchServiceImpl; +import org.openecomp.portalapp.portal.transport.CommonWidget; +import org.openecomp.portalapp.portal.transport.CommonWidgetMeta; +import org.openecomp.portalapp.util.EPUserUtils; + +public class DashboardSearchResultControllerTest { + + @Mock + DashboardSearchService searchService = new DashboardSearchServiceImpl(); + + @InjectMocks + DashboardSearchResultController dashboardSearchResultController = new DashboardSearchResultController(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + + @Mock + EPUserUtils ePUserUtils = new EPUserUtils(); + + MockEPUser mockUser = new MockEPUser(); + + @Test + public void getWidgetDataTest() { + String resourceType = "test"; + PortalRestResponse<CommonWidgetMeta> ecpectedPortalRestResponse = new PortalRestResponse<CommonWidgetMeta>(); + ecpectedPortalRestResponse.setMessage("success"); + ecpectedPortalRestResponse.setResponse(null); + ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); + Mockito.when(searchService.getWidgetData(resourceType)).thenReturn(null); + PortalRestResponse<CommonWidgetMeta> acutualPoratlRestResponse = dashboardSearchResultController + .getWidgetData(mockedRequest, resourceType); + assertEquals(acutualPoratlRestResponse, ecpectedPortalRestResponse); + + } + + @Test + public void saveWidgetDataBulkTest() { + PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<String>(); + ecpectedPortalRestResponse.setMessage("success"); + ecpectedPortalRestResponse.setResponse(null); + ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); + + CommonWidgetMeta commonWidgetMeta = new CommonWidgetMeta(); + commonWidgetMeta.setCategory("test"); + + List<CommonWidget> commonWidgetList = new ArrayList<CommonWidget>(); + CommonWidget commonWidget = new CommonWidget(); + commonWidget.setId((long) 1); + commonWidget.setCategory("test"); + commonWidget.setHref("test_href"); + commonWidget.setTitle("test_title"); + commonWidget.setContent("test_content"); + commonWidget.setEventDate(null); + commonWidget.setSortOrder(1); + + commonWidgetList.add(commonWidget); + + commonWidgetMeta.setItems(commonWidgetList); + + Mockito.when(searchService.saveWidgetDataBulk(commonWidgetMeta)).thenReturn(null); + + PortalRestResponse<String> actualPortalRestResponse = dashboardSearchResultController + .saveWidgetDataBulk(commonWidgetMeta); + assertEquals(actualPortalRestResponse, ecpectedPortalRestResponse); + } + + @Test + public void saveWidgetDataBulkIfCategoryNullTest() { + PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<String>(); + ecpectedPortalRestResponse.setMessage("java.text.ParseException: Unparseable date: \"1\""); + ecpectedPortalRestResponse.setResponse(null); + ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + + CommonWidgetMeta commonWidgetMeta = new CommonWidgetMeta(); + commonWidgetMeta.setCategory("test"); + + List<CommonWidget> commonWidgetList = new ArrayList<CommonWidget>(); + CommonWidget commonWidget = new CommonWidget(); + commonWidget.setId(null); + commonWidget.setCategory(null); + commonWidget.setHref(null); + commonWidget.setTitle(null); + commonWidget.setContent("test_content"); + commonWidget.setEventDate("1"); + commonWidget.setSortOrder(1); + commonWidgetList.add(commonWidget); + commonWidgetMeta.setItems(commonWidgetList); + + Mockito.when(searchService.saveWidgetDataBulk(commonWidgetMeta)).thenReturn(null); + + PortalRestResponse<String> actualPortalRestResponse = dashboardSearchResultController + .saveWidgetDataBulk(commonWidgetMeta); + assertEquals(actualPortalRestResponse, ecpectedPortalRestResponse); + } + + @Test + public void saveWidgetDataTest() { + PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<String>(); + ecpectedPortalRestResponse.setMessage("success"); + ecpectedPortalRestResponse.setResponse(null); + ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); + CommonWidget commonWidget = new CommonWidget(); + commonWidget.setId((long) 1); + commonWidget.setCategory("test"); + commonWidget.setHref("test_href"); + commonWidget.setTitle("test_title"); + commonWidget.setContent("test_content"); + commonWidget.setEventDate(null); + commonWidget.setSortOrder(1); + + Mockito.when(searchService.saveWidgetData(commonWidget)).thenReturn(null); + + PortalRestResponse<String> actualPortalRestResponse = dashboardSearchResultController + .saveWidgetData(commonWidget); + assertEquals(actualPortalRestResponse, ecpectedPortalRestResponse); + + } + + @Test + public void saveWidgetDataExceptionTest() { + PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<String>(); + ecpectedPortalRestResponse.setMessage("ERROR"); + ecpectedPortalRestResponse.setResponse("Cateogry cannot be null or empty"); + ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + CommonWidget commonWidget = new CommonWidget(); + commonWidget.setId((long) 1); + commonWidget.setCategory(""); + commonWidget.setHref("test_href"); + commonWidget.setTitle("test_title"); + commonWidget.setContent("test_content"); + commonWidget.setEventDate(null); + commonWidget.setSortOrder(1); + + Mockito.when(searchService.saveWidgetData(commonWidget)).thenReturn(null); + + PortalRestResponse<String> actualPortalRestResponse = dashboardSearchResultController + .saveWidgetData(commonWidget); + assertEquals(actualPortalRestResponse, ecpectedPortalRestResponse); + + } + + @Test + public void saveWidgetDataDateErrorTest() { + PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<String>(); + ecpectedPortalRestResponse.setMessage("java.text.ParseException: Unparseable date: \"1\""); + ecpectedPortalRestResponse.setResponse(null); + ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + CommonWidget commonWidget = new CommonWidget(); + commonWidget.setId((long) 1); + commonWidget.setCategory("test"); + commonWidget.setHref("test_href"); + commonWidget.setTitle("test_title"); + commonWidget.setContent("test_content"); + commonWidget.setEventDate("1"); + commonWidget.setSortOrder(1); + + Mockito.when(searchService.saveWidgetData(commonWidget)).thenReturn(null); + + PortalRestResponse<String> actualPortalRestResponse = dashboardSearchResultController + .saveWidgetData(commonWidget); + assertEquals(actualPortalRestResponse, ecpectedPortalRestResponse); + + } + + public void deleteWidgetDataTest() { + PortalRestResponse<String> ecpectedPortalRestResponse = new PortalRestResponse<String>(); + ecpectedPortalRestResponse.setMessage("success"); + ecpectedPortalRestResponse.setResponse(null); + ecpectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); + CommonWidget commonWidget = new CommonWidget(); + commonWidget.setId((long) 1); + commonWidget.setCategory("test"); + commonWidget.setHref("test_href"); + commonWidget.setTitle("test_title"); + commonWidget.setContent("test_content"); + commonWidget.setEventDate(null); + commonWidget.setSortOrder(1); + Mockito.when(searchService.deleteWidgetData(commonWidget)).thenReturn(null); + + PortalRestResponse<String> actualPortalRestResponse = dashboardSearchResultController + .deleteWidgetData(commonWidget); + System.out.println(actualPortalRestResponse); + assertEquals(actualPortalRestResponse, ecpectedPortalRestResponse); + } + + @Test + public void searchPortalIfUserIsNull() { + EPUser user = null; + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + String searchString = "test"; + + PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<Map<String, List<SearchResultItem>>>(); + expectedResult.setMessage("searchPortal: User object is null? - check logs"); + expectedResult.setResponse(new HashMap<String, List<SearchResultItem>>()); + expectedResult.setStatus(PortalRestStatusEnum.ERROR); + PortalRestResponse<Map<String, List<SearchResultItem>>> actualResult = dashboardSearchResultController + .searchPortal(mockedRequest, searchString); + assertEquals(expectedResult, actualResult); + } + + @Test + public void searchPortalIfSearchStringNullTest() { + EPUser user = mockUser.mockEPUser(); + ; + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + String searchString = null; + + PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<Map<String, List<SearchResultItem>>>(); + expectedResult.setMessage("searchPortal: String string is null"); + expectedResult.setResponse(new HashMap<String, List<SearchResultItem>>()); + expectedResult.setStatus(PortalRestStatusEnum.ERROR); + + PortalRestResponse<Map<String, List<SearchResultItem>>> actualResult = dashboardSearchResultController + .searchPortal(mockedRequest, searchString); + assertEquals(expectedResult, actualResult); + } + + @Test + public void searchPortalIfSearchTest() { + EPUser user = mockUser.mockEPUser(); + ; + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + String searchString = "test"; + List<SearchResultItem> searchResultItemList = new ArrayList<SearchResultItem>(); + SearchResultItem searchResultItem = new SearchResultItem(); + + searchResultItem.setId((long) 1); + searchResultItem.setCategory("test"); + searchResultItem.setName("test_name"); + searchResultItem.setTarget("test_target"); + searchResultItem.setUuid("test_UUId"); + searchResultItemList.add(searchResultItem); + Map<String, List<SearchResultItem>> expectedResultMap = new HashMap<String, List<SearchResultItem>>(); + expectedResultMap.put(searchString, searchResultItemList); + + PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<Map<String, List<SearchResultItem>>>(); + expectedResult.setMessage("success"); + expectedResult.setResponse(expectedResultMap); + expectedResult.setStatus(PortalRestStatusEnum.OK); + + Mockito.when(searchService.searchResults(user.getLoginId(), searchString)).thenReturn(expectedResultMap); + PortalRestResponse<Map<String, List<SearchResultItem>>> actualResult = dashboardSearchResultController + .searchPortal(mockedRequest, searchString); + assertEquals(expectedResult, actualResult); + + } + + @Test + public void searchPortalIfSearchExcptionTest() { + EPUser user = mockUser.mockEPUser(); + ; + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + String searchString = "test"; + + PortalRestResponse<Map<String, List<SearchResultItem>>> expectedResult = new PortalRestResponse<Map<String, List<SearchResultItem>>>(); + expectedResult.setMessage("null - check logs."); + expectedResult.setResponse(new HashMap<String, List<SearchResultItem>>()); + expectedResult.setStatus(PortalRestStatusEnum.ERROR); + + Mockito.when(searchService.searchResults(user.getLoginId(), searchString)).thenThrow(nullPointerException); + PortalRestResponse<Map<String, List<SearchResultItem>>> actualResult = dashboardSearchResultController + .searchPortal(mockedRequest, searchString); + assertEquals(expectedResult, actualResult); + } + + @Test + public void getActiveUsersTest() { + List<String> expectedActiveUsers = new ArrayList<String>(); + EPUser user = mockUser.mockEPUser(); + ; + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + String userId = user.getOrgUserId(); + Mockito.when(searchService.getRelatedUsers(userId)).thenReturn(expectedActiveUsers); + List<String> actualOnlineUsers = dashboardSearchResultController.getActiveUsers(mockedRequest); + assertEquals(expectedActiveUsers, actualOnlineUsers); + + } + + @Test + public void getActiveUsersExceptionTest() { + List<String> expectedActiveUsers = new ArrayList<String>(); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + String userId = user.getOrgUserId(); + Mockito.when(searchService.getRelatedUsers(userId)).thenThrow(nullPointerException); + List<String> actualOnlineUsers = dashboardSearchResultController.getActiveUsers(mockedRequest); + assertEquals(expectedActiveUsers, actualOnlineUsers); + + } + + @Test + public void activeUsersTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + PortalRestResponse<List<String>> expectedResult = new PortalRestResponse<List<String>>(); + expectedResult.setMessage("success"); + expectedResult.setResponse(new ArrayList<>()); + expectedResult.setStatus(PortalRestStatusEnum.OK); + PortalRestResponse<List<String>> actualResult = dashboardSearchResultController.activeUsers(mockedRequest); + + assertEquals(actualResult, expectedResult); + + } + + @Test + public void activeUsersIfUserNullTest() { + EPUser user = null; + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + PortalRestResponse<List<String>> expectedResult = new PortalRestResponse<List<String>>(); + expectedResult.setMessage("User object is null? - check logs"); + expectedResult.setResponse(new ArrayList<>()); + expectedResult.setStatus(PortalRestStatusEnum.ERROR); + PortalRestResponse<List<String>> actualResult = dashboardSearchResultController.activeUsers(mockedRequest); + assertEquals(actualResult, expectedResult); + + } + + @Test + public void activeUsersExceptionTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + PortalRestResponse<List<String>> expectedResult = new PortalRestResponse<List<String>>(); + expectedResult.setMessage("null - check logs."); + expectedResult.setResponse(new ArrayList<>()); + expectedResult.setStatus(PortalRestStatusEnum.ERROR); + Mockito.when(searchService.getRelatedUsers(user.getLoginId())).thenThrow(nullPointerException); + PortalRestResponse<List<String>> actualResult = dashboardSearchResultController.activeUsers(mockedRequest); + assertEquals(actualResult, expectedResult); + + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/EPFusionBaseControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/EPFusionBaseControllerTest.java new file mode 100644 index 00000000..e6db1d07 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/EPFusionBaseControllerTest.java @@ -0,0 +1,63 @@ +//package org.openecomp.portalapp.portal.test.controller; +// +//import java.util.HashMap; +//import java.util.Map; +// +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +// +//import org.junit.Before; +//import org.junit.Test; +//import org.junit.runner.RunWith; +//import org.mockito.InjectMocks; +//import org.mockito.Mock; +//import org.mockito.Mockito; +//import org.mockito.MockitoAnnotations; +//import org.openecomp.portalapp.controller.EPFusionBaseController; +//import org.openecomp.portalapp.portal.core.MockEPUser; +//import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +//import org.openecomp.portalapp.portal.service.DashboardSearchService; +//import org.openecomp.portalapp.portal.service.DashboardSearchServiceImpl; +//import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +//import org.openecomp.portalapp.util.EPUserUtils; +//import org.openecomp.portalsdk.core.util.SystemProperties; +//import org.powermock.api.mockito.PowerMockito; +//import org.powermock.core.classloader.annotations.PrepareForTest; +//import org.powermock.modules.junit4.PowerMockRunner; +// +//@RunWith(PowerMockRunner.class) +//@PrepareForTest({EPUserUtils.class, SystemProperties.class}) +//public class EPFusionBaseControllerTest { +// +// @Mock +// DashboardSearchService searchService = new DashboardSearchServiceImpl(); +// +// @InjectMocks +// EPFusionBaseController epFusionBaseController; /*= mock(EPFusionBaseController.class);*/ +// +// @Before +// public void setup() { +// MockitoAnnotations.initMocks(this); +// } +// +// MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); +// +// HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); +// HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); +// +// NullPointerException nullPointerException = new NullPointerException(); +// +// MockEPUser mockUser = new MockEPUser(); +// +// @Test +// public void messagesTest(){ +// Map<String, Object> expectedData = new HashMap<String, Object>(); +// Map<String, Object> actualData = null; +// +// PowerMockito.mockStatic(SystemProperties.class); +// Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.APPLICATION_MENU_ATTRIBUTE_NAME)).then(null); +// actualData = epFusionBaseController.messages(mockedRequest); +// System.out.println(); +// +// } +//} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/ExternalAccessRolesControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/ExternalAccessRolesControllerTest.java new file mode 100644 index 00000000..81962240 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/ExternalAccessRolesControllerTest.java @@ -0,0 +1,532 @@ +package org.openecomp.portalapp.portal.controller; + + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.portal.domain.CentralRoleFunction; +import org.openecomp.portalapp.portal.domain.EPApp; +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.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.service.ExternalAccessRolesService; +import org.openecomp.portalapp.portal.service.ExternalAccessRolesServiceImpl; +import org.openecomp.portalapp.portal.transport.CentralRole; +import org.openecomp.portalsdk.core.domain.AuditLog; +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.restful.domain.EcompUser; +import org.springframework.http.HttpStatus; +import org.springframework.web.client.HttpClientErrorException; +public class ExternalAccessRolesControllerTest { + + @Mock + ExternalAccessRolesService externalAccessRolesService = new ExternalAccessRolesServiceImpl(); + + @InjectMocks + ExternalAccessRolesController externalAccessRolesController = new ExternalAccessRolesController(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + @Mock + AuditLog auditLog = new AuditLog(); + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + HttpClientErrorException httpClientErrorException = new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Failed"); + + MockEPUser mockUser = new MockEPUser(); + String loginId = "guestT"; + String uebKey = "testUebKey"; + + @Test + public void getUserTest() throws Exception { + List<EPUser> userList = new ArrayList<>(); + Mockito.when(externalAccessRolesService.getUser(loginId)).thenReturn(userList); + assertNull(externalAccessRolesController.getUser(mockedRequest, mockedResponse, loginId)); + } + + @Test + public void getUserExceptionTest() throws Exception { + Mockito.when(externalAccessRolesService.getUser(loginId)) + .thenThrow(nullPointerException); + assertNull(externalAccessRolesController.getUser(mockedRequest, mockedResponse, loginId)); + } + + public EPApp mockApp() + { + EPApp app = new EPApp(); + app.setName("Test"); + app.setImageUrl("test"); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 1); + app.setAppRestEndpoint("test"); + app.setAlternateUrl("test"); + app.setName("test"); + app.setMlAppName("test"); + app.setMlAppAdminId("test"); + app.setUsername("test"); + app.setAppPassword("test"); + app.setOpen(false); + app.setEnabled(false); + app.setUebKey("test"); + app.setUebSecret("test"); + app.setUebTopicName("test"); + app.setAppType(1); + return app; + } + + @Test + public void getRolesForAppTest() throws Exception { + List<EPApp> applicationList = new ArrayList<EPApp>(); + List<CentralRole> answer = new ArrayList<>(); + EPApp app = mockApp(); + applicationList.add(app); + Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader(uebKey))).thenReturn(applicationList); + Mockito.doNothing().when(externalAccessRolesService).syncApplicationRolesWithEcompDB(app); + Mockito.when(externalAccessRolesService.getRolesForApp(mockedRequest.getHeader(uebKey))).thenReturn(answer); + assertEquals(externalAccessRolesController.getRolesForApp(mockedRequest, mockedResponse), answer); + } + + @Test + public void getRolesForAppExceptionTest() throws Exception { + List<EPApp> applicationList = new ArrayList<EPApp>(); + List<CentralRole> answer = new ArrayList<>(); + EPApp app = mockApp(); + applicationList.add(app); + Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader(uebKey))).thenReturn(applicationList); + Mockito.doNothing().when(externalAccessRolesService).syncApplicationRolesWithEcompDB(app); + Mockito.when(externalAccessRolesService.getRolesForApp(mockedRequest.getHeader(uebKey))) + .thenThrow(httpClientErrorException); + assertNull(externalAccessRolesController.getRolesForApp(mockedRequest, mockedResponse)); + } + + @Test + public void getRoleFunctionsListTest() throws Exception { + List<CentralRoleFunction> answer = new ArrayList<>(); + Mockito.when(externalAccessRolesService.getRoleFuncList(mockedRequest.getHeader(uebKey))).thenReturn(answer); + assertEquals(externalAccessRolesController.getRoleFunctionsList(mockedRequest, mockedResponse), answer); + } + + @Test + public void getRoleFunctionsListExceptionTest() throws Exception { + Mockito.when(externalAccessRolesService.getRoleFuncList(mockedRequest.getHeader(uebKey))) + .thenThrow(httpClientErrorException); + assertNull(externalAccessRolesController.getRoleFunctionsList(mockedRequest, mockedResponse)); + } + + @Test + public void getRoleInfoTest() throws Exception { + CentralRole answer = new CentralRole(); + long roleId = 1; + Mockito.when(externalAccessRolesService.getRoleInfo(roleId, mockedRequest.getHeader(uebKey))) + .thenReturn(answer); + assertEquals(externalAccessRolesController.getRoleInfo(mockedRequest, mockedResponse, roleId), answer); + } + + @Test + public void getRoleInfoExceptionTest() throws Exception { + long roleId = 1; + Mockito.when(externalAccessRolesService.getRoleInfo(roleId, mockedRequest.getHeader(uebKey))) + .thenThrow(httpClientErrorException); + assertNull(externalAccessRolesController.getRoleInfo(mockedRequest, mockedResponse, roleId)); + } + + @Test + public void getRoleFunctionTest() throws Exception { + CentralRoleFunction centralRoleFunction = new CentralRoleFunction(); + String code = "test_menu"; + Mockito.when(externalAccessRolesService.getRoleFunction(code, mockedRequest.getHeader(uebKey))) + .thenReturn(centralRoleFunction); + assertEquals(externalAccessRolesController.getRoleFunction(mockedRequest, mockedResponse, code), + centralRoleFunction); + } + + @Test + public void getRoleFunctionExceptionTest() throws Exception { + String code = "test_menu"; + Mockito.when(externalAccessRolesService.getRoleFunction(code, mockedRequest.getHeader(uebKey))) + .thenThrow(httpClientErrorException); + assertNull(externalAccessRolesController.getRoleFunction(mockedRequest, mockedResponse, code)); + } + + @Test + public void saveRoleFunctionIfIsIsNotDeletedTest() throws Exception { + List<EPApp> applicationList = new ArrayList<EPApp>(); + EPApp app = mockApp(); + applicationList.add(app); + Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader(uebKey))).thenReturn(applicationList); + PortalRestResponse<String> portalRestResponse = null; + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage(null); + expectedportalRestResponse.setResponse("Failed"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + String data = null; + CentralRoleFunction centralRoleFunction = new CentralRoleFunction(); + Mockito.when(externalAccessRolesService.saveCentralRoleFunction(centralRoleFunction, app)).thenReturn(false); + portalRestResponse = externalAccessRolesController.saveRoleFunction(mockedRequest, mockedResponse, data); + assertEquals(portalRestResponse, expectedportalRestResponse); + } + + @Test + public void saveRoleFunctionExceptionTest() throws Exception { + List<EPApp> applicationList = new ArrayList<EPApp>(); + EPApp app = mockApp(); + applicationList.add(app); + Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader(uebKey))).thenReturn(applicationList); + PortalRestResponse<String> portalRestResponse = null; + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage(null); + expectedportalRestResponse.setResponse("Failed"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + String data = null; + CentralRoleFunction centralRoleFunction = new CentralRoleFunction(); + Mockito.when(externalAccessRolesService.saveCentralRoleFunction(centralRoleFunction, app)).thenThrow(nullPointerException); + portalRestResponse = externalAccessRolesController.saveRoleFunction(mockedRequest, mockedResponse, data); + System.out.println(portalRestResponse); + assertEquals(portalRestResponse, expectedportalRestResponse); + } + + @Test + public void saveRoleFunctionTest() throws Exception { + List<EPApp> applicationList = new ArrayList<EPApp>(); + List<CentralRole> answer = new ArrayList<>(); + EPApp app = mockApp(); + applicationList.add(app); + Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader(uebKey))).thenReturn(applicationList); + PortalRestResponse<String> portalRestResponse = null; + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage(null); + expectedportalRestResponse.setResponse("Failed"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + String data = null; + CentralRoleFunction centralRoleFunction = new CentralRoleFunction(); + Mockito.when(externalAccessRolesService.saveCentralRoleFunction(centralRoleFunction, app)).thenReturn(true); + portalRestResponse = externalAccessRolesController.saveRoleFunction(mockedRequest, mockedResponse, data); + System.out.println(portalRestResponse); + assertEquals(portalRestResponse, expectedportalRestResponse); + } + +// @Test +// public void deleteRoleFunctionTest() throws Exception { +// PortalRestResponse<String> portalRestResponse = null; +// PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); +// expectedportalRestResponse.setMessage("Successfully Deleted"); +// expectedportalRestResponse.setResponse("Success"); +// PortalRestStatusEnum portalRestStatusEnum = null; +// EPUser user = mockUser.mockEPUser(); +// EPApp app = mockApp(); +// expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); +// String code ="testNew"; +// Mockito.when(externalAccessRolesService.getUser(mockedRequest.getHeader("LOGIN_ID"))).thenReturn((List<EPUser>) user); +// Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader("UEBKEY")).get(0)).thenReturn(app); +// Mockito.when(externalAccessRolesService.deleteCentralRoleFunction(code, app)).thenReturn(true); +// portalRestResponse = externalAccessRolesController.deleteRoleFunction(mockedRequest, mockedResponse, code); +// assertEquals(portalRestResponse, expectedportalRestResponse); +// } + + @Test + public void getActiveRolesTest() throws Exception { + List<CentralRole> cenRole = new ArrayList<>(); + Mockito.when(externalAccessRolesService.getActiveRoles(mockedRequest.getHeader(uebKey))).thenReturn(cenRole); + List<CentralRole> expectedCenRole = externalAccessRolesController.getActiveRoles(mockedRequest, mockedResponse); + assertEquals(expectedCenRole, cenRole); + } + + @Test + public void getActiveRolesExceptionTest() throws Exception { + Mockito.when(externalAccessRolesService.getActiveRoles(mockedRequest.getHeader(uebKey))) + .thenThrow(httpClientErrorException); + assertNull(externalAccessRolesController.getActiveRoles(mockedRequest, mockedResponse)); + } + + @Test + public void deleteDependcyRoleRecordExceptionTest() throws Exception { + PortalRestResponse<String> portalRestResponse = null; + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Failed to deleteDependencyRoleRecord"); + expectedportalRestResponse.setResponse("Failed"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + long roleId = 123; + portalRestResponse = externalAccessRolesController.deleteDependencyRoleRecord(mockedRequest, mockedResponse, roleId); + assertEquals(expectedportalRestResponse, portalRestResponse); + } + + @Test + public void bulkUploadFunctionsTest() throws Exception { + Integer result = 0; + Mockito.when(externalAccessRolesService.bulkUploadFunctions(mockedRequest.getHeader(uebKey))) + .thenReturn(result); + PortalRestResponse<String> portalRestResponse = null; + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Successfully added: 0"); + expectedportalRestResponse.setResponse("Success"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + portalRestResponse = externalAccessRolesController.bulkUploadFunctions(mockedRequest, mockedResponse); + assertEquals(portalRestResponse, expectedportalRestResponse); + } + + @Test + public void bulkUploadFunctionsExceptionTest() throws Exception { + Mockito.when(externalAccessRolesService.bulkUploadFunctions(mockedRequest.getHeader(uebKey))) + .thenThrow(httpClientErrorException); + PortalRestResponse<String> portalRestResponse = null; + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Failed to bulkUploadFunctions"); + expectedportalRestResponse.setResponse("Failed"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + portalRestResponse = externalAccessRolesController.bulkUploadFunctions(mockedRequest, mockedResponse); + assertEquals(portalRestResponse, expectedportalRestResponse); + } + + @Test + public void bulkUploadRolesTest() throws Exception { + Integer result = 0; + PortalRestResponse<String> portalRestResponse = null; + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Successfully added: 0"); + expectedportalRestResponse.setResponse("Success"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + Mockito.when(externalAccessRolesService.bulkUploadRoles(mockedRequest.getHeader(uebKey))).thenReturn(result); + portalRestResponse = externalAccessRolesController.bulkUploadRoles(mockedRequest, mockedResponse); + assertEquals(portalRestResponse, expectedportalRestResponse); + } + + @Test + public void bulkUploadRolesTestException() throws Exception { + Mockito.when(externalAccessRolesService.bulkUploadRoles(mockedRequest.getHeader(uebKey))) + .thenThrow(httpClientErrorException); + PortalRestResponse<String> portalRestResponse = null; + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Failed to bulkUploadRoles"); + expectedportalRestResponse.setResponse("Failed"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + portalRestResponse = externalAccessRolesController.bulkUploadRoles(mockedRequest, mockedResponse); + assertEquals(portalRestResponse, expectedportalRestResponse); + } + + @Test + public void bulkUploadRoleFunctionsTest() throws Exception { + Integer result = 0; + PortalRestResponse<String> portalRestResponse = null; + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Successfully added: 0"); + expectedportalRestResponse.setResponse("Success"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + Mockito.when(externalAccessRolesService.bulkUploadRolesFunctions(mockedRequest.getHeader(uebKey))) + .thenReturn(result); + portalRestResponse = externalAccessRolesController.bulkUploadRoleFunctions(mockedRequest, mockedResponse); + assertEquals(portalRestResponse, expectedportalRestResponse); + } + + @Test + public void bulkUploadRoleFunctionsException() throws Exception { + Mockito.when(externalAccessRolesService.bulkUploadRolesFunctions(mockedRequest.getHeader(uebKey))) + .thenThrow(httpClientErrorException); + PortalRestResponse<String> portalRestResponse = null; + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Failed to bulkUploadRoleFunctions"); + expectedportalRestResponse.setResponse("Failed"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + portalRestResponse = externalAccessRolesController.bulkUploadRoleFunctions(mockedRequest, mockedResponse); + assertEquals(portalRestResponse, expectedportalRestResponse); + } + + @Test + public void bulkUploadUserRolesTest() throws Exception { + Integer result = 0; + PortalRestResponse<String> portalRestResponse = null; + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Successfully added: 0"); + expectedportalRestResponse.setResponse("Success"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + Mockito.when(externalAccessRolesService.bulkUploadUserRoles(mockedRequest.getHeader(uebKey))) + .thenReturn(result); + portalRestResponse = externalAccessRolesController.bulkUploadUserRoles(mockedRequest, mockedResponse); + assertEquals(portalRestResponse, expectedportalRestResponse); + } + + @Test + public void bulkUploadUserRolesExceptionTest() throws Exception { + Mockito.when(externalAccessRolesService.bulkUploadUserRoles(mockedRequest.getHeader(uebKey))) + .thenThrow(httpClientErrorException); + PortalRestResponse<String> portalRestResponse = null; + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Failed to bulkUploadUserRoles"); + expectedportalRestResponse.setResponse("Failed"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + portalRestResponse = externalAccessRolesController.bulkUploadUserRoles(mockedRequest, mockedResponse); + assertEquals(portalRestResponse, expectedportalRestResponse); + } + + @Test + public void bulkUploadPartnerFunctionsTest() throws Exception { + PortalRestResponse<String> portalRestResponse = null; + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Successfully added"); + expectedportalRestResponse.setResponse("Success"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + portalRestResponse = externalAccessRolesController.bulkUploadPartnerFunctions(mockedRequest, mockedResponse, null); + assertEquals(portalRestResponse, expectedportalRestResponse); + } + + + @Test + public void bulkUploadPartnerRolesTest() throws Exception { + PortalRestResponse<String> portalRestResponse = null; + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Successfully added"); + expectedportalRestResponse.setResponse("Success"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + List<Role> upload = new ArrayList<>(); + portalRestResponse = externalAccessRolesController.bulkUploadPartnerRoles(mockedRequest, mockedResponse, + upload); + assertEquals(portalRestResponse, expectedportalRestResponse); + } + + @Test + public void bulkUploadPartnerRolesExceptionTest() throws Exception + { + ExternalAccessRolesService externalAccessRolesService = null; + PortalRestResponse<String> portalRestResponse = null; + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Successfully added"); + expectedportalRestResponse.setResponse("Success"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + List<Role> upload = new ArrayList<>(); + portalRestResponse = externalAccessRolesController.bulkUploadPartnerRoles(mockedRequest, mockedResponse, + upload); + assertEquals(portalRestResponse, expectedportalRestResponse); + } + + @Test + public void getMenuFunctionsTest() throws Exception { + List<String> functionsList = new ArrayList<>(); + Mockito.when(externalAccessRolesService.getMenuFunctionsList(mockedRequest.getHeader(uebKey))) + .thenReturn(functionsList); + List<String> expectedFunctionsList = externalAccessRolesController.getMenuFunctions(mockedRequest, + mockedResponse); + assertEquals(functionsList, expectedFunctionsList); + } + + @Test + public void getMenuFunctionsExceptionTest() throws Exception { + Mockito.when(externalAccessRolesService.getMenuFunctionsList(mockedRequest.getHeader(uebKey))) + .thenThrow(httpClientErrorException); + assertNull(externalAccessRolesController.getMenuFunctions(mockedRequest, mockedResponse)); + } + +// @Test +// public void getUsersOfApplicationTest() throws Exception { +// List<String> users = new ArrayList<>(); +// Mockito.when(externalAccessRolesService.getAllUsers(mockedRequest.getHeader(uebKey))).thenReturn(users); +// List<String> expectedusers = externalAccessRolesController.getUsersOfApplication(mockedRequest, mockedResponse); +// assertEquals(users, expectedusers); +// } + +// @Test +// public void getUsersOfApplicationExceptionTest() throws Exception { +// Mockito.when(externalAccessRolesService.getAllUsers(mockedRequest.getHeader(uebKey))) +// .thenThrow(httpClientErrorException); +// assertNull(externalAccessRolesController.getUsersOfApplication(mockedRequest, mockedResponse)); +// } + + @Test + public void saveRoleExceptionTest() throws Exception { + Role role = new Role(); + PortalRestResponse<String> portalRestResponse = null; + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Failed to saveRole"); + expectedportalRestResponse.setResponse("Failed"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + List<Role> upload = new ArrayList<>(); + portalRestResponse = externalAccessRolesController.saveRole(mockedRequest, mockedResponse,role); + assertEquals(portalRestResponse, expectedportalRestResponse); + } + + @Test + public void deleteRoleExceptionTest() throws Exception { + String role = "TestNew"; + PortalRestResponse<String> portalRestResponse = null; + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Failed to deleteRole for 'TestNew'"); + expectedportalRestResponse.setResponse("Failed"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + portalRestResponse = externalAccessRolesController.deleteRole(mockedRequest, mockedResponse,role); + assertEquals(portalRestResponse, expectedportalRestResponse); + } + + + @Test + public void bulkUploadPartnerRoleFunctionsTest() throws Exception { + PortalRestResponse<String> portalRestResponse = null; + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Successfully added"); + expectedportalRestResponse.setResponse("Success"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + List<Role> upload = new ArrayList<>(); + portalRestResponse = externalAccessRolesController.bulkUploadPartnerRoleFunctions(mockedRequest, mockedResponse,upload); + assertEquals(portalRestResponse, expectedportalRestResponse); + } + + @Test + public void getUsersOfApplicationTest() throws Exception + { + List<EcompUser> users = new ArrayList<>(); + EcompUser user = new EcompUser(); + user.setOrgUserId("guestT"); + users.add(user); + Mockito.when(externalAccessRolesService.getAllAppUsers(mockedRequest.getHeader(uebKey))).thenReturn(users); + List<EcompUser> expectedUsers = externalAccessRolesController.getUsersOfApplication(mockedRequest, mockedResponse); + assertEquals(expectedUsers, users); + } + + @Test(expected = Exception.class) + public void getUsersOfApplicationExceptionTest() throws Exception + { + List<EcompUser> users = new ArrayList<>(); + EcompUser user = new EcompUser(); + user.setOrgUserId("guestT"); + users.add(user); + Mockito.when(externalAccessRolesService.getAllAppUsers(mockedRequest.getHeader(uebKey))).thenThrow(nullPointerException); + assertNull(externalAccessRolesController.getUsersOfApplication(mockedRequest, mockedResponse)); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulControllerTest.java new file mode 100644 index 00000000..9bc44174 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/ExternalAppsRestfulControllerTest.java @@ -0,0 +1,174 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.ExternalAppsRestfulController; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.AdminRolesServiceImpl; +import org.openecomp.portalapp.portal.service.EPLoginService; +import org.openecomp.portalapp.portal.service.EPLoginServiceImpl; +import org.openecomp.portalapp.portal.service.EPRoleService; +import org.openecomp.portalapp.portal.service.EPRoleServiceImpl; +import org.openecomp.portalapp.portal.service.FunctionalMenuService; +import org.openecomp.portalapp.portal.service.FunctionalMenuServiceImpl; +import org.openecomp.portalapp.portal.service.UserNotificationService; +import org.openecomp.portalapp.portal.service.UserNotificationServiceImpl; +import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItem; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.service.DataAccessServiceImpl; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.slf4j.MDC; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ MDC.class, EPCommonSystemProperties.class }) +public class ExternalAppsRestfulControllerTest { + + @InjectMocks + ExternalAppsRestfulController externalAppsRestfulController = new ExternalAppsRestfulController(); + @Mock + FunctionalMenuService functionalMenuService = new FunctionalMenuServiceImpl(); + + @Mock + EPLoginService epLoginService = new EPLoginServiceImpl(); + + @Mock + AdminRolesService adminRolesService = new AdminRolesServiceImpl(); + + @Mock + UserNotificationService userNotificationService = new UserNotificationServiceImpl(); + + @Mock + EPRoleService epRoleService = new EPRoleServiceImpl(); + + @Mock + EcompPortalUtils EcompPortalUtils = new EcompPortalUtils(); + + @Mock + DataAccessService DataAccessService = new DataAccessServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + + MockEPUser mockUser = new MockEPUser(); + + @Test(expected = Exception.class) + public void getFunctionalMenuItemsForUserIfUSerNullTest() throws + Exception + { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(MDC.class); + EPUser epUser = null; + String loginId = "guestT"; + Mockito.when(MDC.get(EPCommonSystemProperties.PARTNER_NAME)).thenReturn("Test"); + Mockito.when(epLoginService.findUserWithoutPwd(loginId)).thenReturn(epUser); + externalAppsRestfulController.getFunctionalMenuItemsForUser(mockedRequest, + mockedResponse); + } + + @Test + public void getFunctionalMenuItemsForUserIfSuperAdminTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(MDC.class); + EPUser epUser = mockUser.mockEPUser(); + epUser.setId((long) 1); + epUser.setLoginId("guestT"); + String loginId = "guestT"; + Mockito.when(MDC.get(EPCommonSystemProperties.PARTNER_NAME)).thenReturn("Test"); + Mockito.when(epLoginService.findUserWithoutPwd(loginId)).thenReturn(epUser); + List<FunctionalMenuItem> expectedList = new ArrayList<FunctionalMenuItem>(); + FunctionalMenuItem functionalMenuItem = new FunctionalMenuItem(); + expectedList.add(functionalMenuItem); + Mockito.when(mockedRequest.getHeader("LoginId")).thenReturn("guestT"); + Mockito.when(adminRolesService.isSuperAdmin(epUser)).thenReturn(true); + Mockito.when(functionalMenuService.getFunctionalMenuItems()).thenReturn(expectedList); + List<FunctionalMenuItem> actualList = externalAppsRestfulController.getFunctionalMenuItemsForUser(mockedRequest, + mockedResponse); + assertNull(actualList.get(0).menuId); + } + + @Test + public void getFunctionalMenuItemsForUserTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(MDC.class); + EPUser epUser = mockUser.mockEPUser(); + epUser.setId((long) 1); + epUser.setLoginId("guestT"); + String loginId = "guestT"; + Mockito.when(MDC.get(EPCommonSystemProperties.PARTNER_NAME)).thenReturn("Test"); + Mockito.when(epLoginService.findUserWithoutPwd(loginId)).thenReturn(epUser); + List<FunctionalMenuItem> expectedList = new ArrayList<FunctionalMenuItem>(); + FunctionalMenuItem functionalMenuItem = new FunctionalMenuItem(); + expectedList.add(functionalMenuItem); + Mockito.when(mockedRequest.getHeader("LoginId")).thenReturn("guestT"); + Mockito.when(adminRolesService.isSuperAdmin(epUser)).thenReturn(false); + Mockito.when(functionalMenuService.getFunctionalMenuItemsForUser(epUser.getOrgUserId())) + .thenReturn(expectedList); + List<FunctionalMenuItem> actualList = externalAppsRestfulController.getFunctionalMenuItemsForUser(mockedRequest, + mockedResponse); + assertNull(actualList.get(0).menuId); + } + + @Test(expected = Exception.class) + public void getFavoritesForUserIfUserNullTest() throws Exception { + List<FavoritesFunctionalMenuItemJson> favorites = new ArrayList<FavoritesFunctionalMenuItemJson>(); + FavoritesFunctionalMenuItemJson favoritesFunctionalMenuItemJson = new FavoritesFunctionalMenuItemJson(); + favorites.add(favoritesFunctionalMenuItemJson); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(MDC.class); + Mockito.when(mockedRequest.getHeader(EPCommonSystemProperties.MDC_LOGIN_ID)).thenReturn("Login_URL"); + Mockito.when(MDC.get(EPCommonSystemProperties.PARTNER_NAME)).thenReturn("Test"); + EPUser epUser = null; + externalAppsRestfulController.getFavoritesForUser(mockedRequest, mockedResponse); + } + + @Test + public void getFavoritesForUserTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(MDC.class); + EPUser epUser = mockUser.mockEPUser(); + epUser.setId((long) 1); + epUser.setLoginId("guestT"); + String loginId = "guestT"; + Mockito.when(MDC.get(EPCommonSystemProperties.PARTNER_NAME)).thenReturn("Test"); + List<FavoritesFunctionalMenuItemJson> favorites = new ArrayList<FavoritesFunctionalMenuItemJson>(); + FavoritesFunctionalMenuItemJson favoritesFunctionalMenuItemJson = new FavoritesFunctionalMenuItemJson(); + favorites.add(favoritesFunctionalMenuItemJson); + Mockito.when(mockedRequest.getHeader(EPCommonSystemProperties.MDC_LOGIN_ID)).thenReturn("Login_URL"); + Mockito.when(MDC.get(EPCommonSystemProperties.PARTNER_NAME)).thenReturn("Test"); + Mockito.when(epLoginService.findUserWithoutPwd("Login_URL")).thenReturn(epUser); + Mockito.when(functionalMenuService.getFavoriteItems(epUser.getId())).thenReturn(favorites); + List<FavoritesFunctionalMenuItemJson> actaulFavorites = externalAppsRestfulController + .getFavoritesForUser(mockedRequest, mockedResponse); + assertEquals(actaulFavorites.size(), 1); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/FunctionalMenuControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/FunctionalMenuControllerTest.java new file mode 100644 index 00000000..af0a588f --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/FunctionalMenuControllerTest.java @@ -0,0 +1,506 @@ +/*- + * ================================================================================ + * 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 static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.runners.MockitoJUnitRunner; +import org.openecomp.portalapp.portal.controller.FunctionalMenuController; +import org.openecomp.portalapp.portal.core.MockEPUser; +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.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.AdminRolesServiceImpl; +import org.openecomp.portalapp.portal.service.FunctionalMenuService; +import org.openecomp.portalapp.portal.service.FunctionalMenuServiceImpl; +import org.openecomp.portalapp.portal.service.SearchService; +import org.openecomp.portalapp.portal.transport.BusinessCardApplicationRole; +import org.openecomp.portalapp.portal.transport.BusinessCardApplicationRolesList; +import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItem; +import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.FieldsValidator.FieldName; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItem; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItemWithRoles; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(SystemProperties.class) +public class FunctionalMenuControllerTest extends MockitoTestSuite { + + String userid = "ab1234"; + + @Mock + FunctionalMenuService functionalMenuService = new FunctionalMenuServiceImpl(); + + @InjectMocks + FunctionalMenuController functionalMenuController = new FunctionalMenuController(); + + @Mock + private DataAccessService dataAccessService; + + @Mock + SearchService searchService; + + @Mock + AdminRolesService adminRolesService = new AdminRolesServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + + @InjectMocks + EPUserUtils ePUserUtils = new EPUserUtils(); + + @Mock + EPUser epuser; + + MockEPUser mockUser = new MockEPUser(); + + List<BusinessCardApplicationRolesList> appRoles = new ArrayList<BusinessCardApplicationRolesList>(); + List<BusinessCardApplicationRolesList> appRolesActual = new ArrayList<BusinessCardApplicationRolesList>(); + + List<BusinessCardApplicationRole> userAppRoleList = new ArrayList<BusinessCardApplicationRole>(); + + public List<BusinessCardApplicationRole> mockBusinessCardApplicationRole() { + List<BusinessCardApplicationRole> userAppRoleList = new ArrayList<BusinessCardApplicationRole>(); + + BusinessCardApplicationRole businessCardApplicationRole = new BusinessCardApplicationRole(); + businessCardApplicationRole.setRoleName("ADMIN"); + businessCardApplicationRole.setAppName("ASDC"); + + BusinessCardApplicationRole businessCardApplicationRole1 = new BusinessCardApplicationRole(); + businessCardApplicationRole1.setAppName("ASDC"); + businessCardApplicationRole1.setRoleName("Tester"); + + userAppRoleList.add(businessCardApplicationRole); + userAppRoleList.add(businessCardApplicationRole1); + return userAppRoleList; + } + + public List<BusinessCardApplicationRolesList> mockBusinessCardApplicationRolesList() { + List<BusinessCardApplicationRolesList> appRolesActual = new ArrayList<BusinessCardApplicationRolesList>(); + + BusinessCardApplicationRolesList businessCardApplicationRolesList = new BusinessCardApplicationRolesList(); + businessCardApplicationRolesList.setAppName("ASDC"); + + List<String> roleNames = new ArrayList<String>(); + roleNames.add("ADMIN"); + roleNames.add("Tester"); + businessCardApplicationRolesList.setRoleNames(roleNames); + + appRolesActual.add(businessCardApplicationRolesList); + return appRolesActual; + } + + @Test + public void getAppListTestIfAppAlredyExistsBusinessCardApplicationRolesList() throws IOException { + + userAppRoleList = mockBusinessCardApplicationRole(); + appRolesActual = mockBusinessCardApplicationRolesList(); + + Mockito.when(functionalMenuService.getUserAppRolesList(userid)).thenReturn(userAppRoleList); + + appRoles = functionalMenuController.getAppList(mockedRequest, userid); + + assertEquals(appRolesActual.size(), appRoles.size()); + assertEquals(appRolesActual.get(0).getAppName(), appRoles.get(0).getAppName()); + assertEquals(appRolesActual.get(0).getRoleNames(), appRoles.get(0).getRoleNames()); + + } + + @Test + public void getAppListTestIfAppDoesnotExistsInBusinessCardApplicationRolesList() throws IOException { + + userAppRoleList = mockBusinessCardApplicationRole(); + BusinessCardApplicationRole businessCardApplicationRole = new BusinessCardApplicationRole(); + businessCardApplicationRole.setAppName("CCD"); + businessCardApplicationRole.setRoleName("ADMIN"); + userAppRoleList.add(businessCardApplicationRole); + appRolesActual = mockBusinessCardApplicationRolesList(); + BusinessCardApplicationRolesList businessCardApplicationRolesList = new BusinessCardApplicationRolesList(); + businessCardApplicationRolesList.setAppName("CCD"); + List<String> roleNames1 = new ArrayList<String>(); + roleNames1.add("ADMIN"); + businessCardApplicationRolesList.setRoleNames(roleNames1); + appRolesActual.add(businessCardApplicationRolesList); + Mockito.when(functionalMenuService.getUserAppRolesList(userid)).thenReturn(userAppRoleList); + appRoles = functionalMenuController.getAppList(mockedRequest, userid); + assertEquals(appRolesActual.size(), appRoles.size()); + assertEquals(appRolesActual.get(0).getAppName(), appRoles.get(0).getAppName()); + assertEquals(appRolesActual.get(0).getRoleNames(), appRoles.get(0).getRoleNames()); + assertEquals(appRolesActual.get(1).getAppName(), appRoles.get(1).getAppName()); + assertEquals(appRolesActual.get(1).getRoleNames(), appRoles.get(1).getRoleNames()); + + } + + @Test + public void regenerateAncestorTableTest() { + EPUser user = mockUser.mockEPUser(); + + HttpSession session = mockedRequest.getSession(); + session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + FieldsValidator acutualFieldValidator = null; + FieldsValidator expectedFieldValidator = new FieldsValidator(); + List<FieldName> fields = new ArrayList<>(); + expectedFieldValidator.setHttpStatusCode((long) 200); + expectedFieldValidator.setFields(fields); + expectedFieldValidator.setErrorCode(null); + Mockito.when(!adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(functionalMenuService.regenerateAncestorTable()).thenReturn(expectedFieldValidator); + acutualFieldValidator = functionalMenuController.regenerateAncestorTable(mockedRequest, mockedResponse); + assertTrue(acutualFieldValidator.equals(expectedFieldValidator)); + } + + @Test + public void getFunctionalMenuStaticInfoExceptionTest(){ + String fnMenuStaticactualResponse = null; + String fnMenuStaticexpectedResponse = null; + String orgUserIdStr = null; + + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(searchService.searchUserByUserId(orgUserIdStr)).thenReturn(user); + fnMenuStaticactualResponse = functionalMenuController.getFunctionalMenuStaticInfo(mockedRequest, mockedResponse); + + assertEquals(fnMenuStaticactualResponse, fnMenuStaticexpectedResponse); + + } + + @Test + public void getFunctionalMenuStaticInfoTest(){ + String fnMenuStaticactualResponse = null; + String fnMenuStaticexpectedResponse = "{\"firstName\":\"test\",\"lastName\":\"test\",\"last_login\":\"09/08/2017 03:48:13-0400\",\"userId\":\"guestT\",\"email\":\"test\"}"; + String orgUserIdStr = null; + + EPUser user = mockUser.mockEPUser(); + user.setEmail("test"); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(searchService.searchUserByUserId(orgUserIdStr)).thenReturn(user); + fnMenuStaticactualResponse = functionalMenuController.getFunctionalMenuStaticInfo(mockedRequest, mockedResponse); + assertEquals(fnMenuStaticactualResponse.length(), fnMenuStaticexpectedResponse.length()); + } + + @Test + public void getMenuItemsForAuthUserNullTest(){ + List<FunctionalMenuItem> actualmenuItems = null; + List<FunctionalMenuItem> expectedmenuItems = null; + + actualmenuItems = functionalMenuController.getMenuItemsForAuthUser(mockedRequest, mockedResponse); + assertEquals(actualmenuItems, expectedmenuItems); + } + + @Test + public void getMenuItemsForAuthUserIsSuperAdminTest(){ + List<FunctionalMenuItem> actualmenuItems = null; + List<FunctionalMenuItem> expectedmenuItems = new ArrayList<FunctionalMenuItem>(); + EPUser user = mockUser.mockEPUser(); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + + actualmenuItems = functionalMenuController.getMenuItemsForAuthUser(mockedRequest, mockedResponse); + assertEquals(actualmenuItems, expectedmenuItems); + } + + @Test + public void getMenuItemsForAuthUserTest(){ + List<FunctionalMenuItem> actualmenuItems = null; + List<FunctionalMenuItem> expectedmenuItems = new ArrayList<FunctionalMenuItem>(); + EPUser user = mockUser.mockEPUser(); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + + actualmenuItems = functionalMenuController.getMenuItemsForAuthUser(mockedRequest, mockedResponse); + assertEquals(actualmenuItems, expectedmenuItems); + } + + @Test + public void getFunctionalMenuItemDetailsBadPermissionTest(){ + Integer menuId = 1234; + FunctionalMenuItem actualmenuItem = null; + FunctionalMenuItem expectedmenuItem = null; + EPUser user = mockUser.mockEPUser(); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + + actualmenuItem = functionalMenuController.getFunctionalMenuItemDetails(mockedRequest, menuId, mockedResponse); + assertEquals(actualmenuItem, expectedmenuItem); + } + + @Test + public void getFunctionalMenuItemDetailsTest(){ + Integer menuId = 1234; + FunctionalMenuItem actualmenuItem = null; + FunctionalMenuItem expectedmenuItem = null; + EPUser user = mockUser.mockEPUser(); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(functionalMenuService.getFunctionalMenuItemDetails(menuId)).thenReturn(actualmenuItem); + + actualmenuItem = functionalMenuController.getFunctionalMenuItemDetails(mockedRequest, menuId, mockedResponse); + assertEquals(actualmenuItem, expectedmenuItem); + } + + @Test + public void getMenuItemsForEditingTest(){ + List<FunctionalMenuItem> actualMenuItems = null; + List<FunctionalMenuItem> expectedMenuItems = null; + EPUser user = mockUser.mockEPUser(); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(functionalMenuService.getFunctionalMenuItems(true)).thenReturn(actualMenuItems); + + actualMenuItems = functionalMenuController.getMenuItemsForEditing(mockedRequest, mockedResponse); + assertEquals(actualMenuItems, expectedMenuItems); + } + + @Test + public void getMenuItemsForEditingBadPermissionsTest(){ + List<FunctionalMenuItem> actualMenuItems = null; + List<FunctionalMenuItem> expectedMenuItems = null; + EPUser user = mockUser.mockEPUser(); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(functionalMenuService.getFunctionalMenuItems(true)).thenReturn(actualMenuItems); + + actualMenuItems = functionalMenuController.getMenuItemsForEditing(mockedRequest, mockedResponse); + assertEquals(actualMenuItems, expectedMenuItems); + } + + @Test + public void getMenuItemsForNotificationsTest(){ + List<FunctionalMenuItem> actualMenuItems = null; + List<FunctionalMenuItem> expectedMenuItems = new ArrayList<FunctionalMenuItem>(); + Mockito.when(functionalMenuService.getFunctionalMenuItemsForNotificationTree(false)).thenReturn(actualMenuItems); + + actualMenuItems = functionalMenuController.getMenuItemsForNotifications(mockedRequest, mockedResponse); + assertEquals(actualMenuItems, expectedMenuItems); + } + + @Test + public void getMenuItemsForAppTest(){ + Integer appId = 1234; + List<FunctionalMenuItem> actualMenuItems = null; + List<FunctionalMenuItem> expectedMenuItems = null; + Mockito.when(functionalMenuService.getFunctionalMenuItemsForApp(appId)).thenReturn(actualMenuItems); + + actualMenuItems = functionalMenuController.getMenuItemsForApp(mockedRequest, appId); + assertEquals(actualMenuItems, expectedMenuItems); + } + + @Test + public void getMenuItemsForUserTest(){ + String orgUserId ="test"; + List<FunctionalMenuItem> actualMenuItems = null; + List<FunctionalMenuItem> expectedMenuItems = null; + Mockito.when(functionalMenuService.getFunctionalMenuItemsForUser(orgUserId)).thenReturn(actualMenuItems); + + actualMenuItems = functionalMenuController.getMenuItemsForUser(mockedRequest, orgUserId); + assertEquals(actualMenuItems, expectedMenuItems); + } + + @Test + public void createFunctionalMenuItemTest(){ + FieldsValidator actualFieldsValidator = new FieldsValidator(); + FieldsValidator expectedFieldsValidator = new FieldsValidator(); + List<FieldName> fields = new ArrayList<>(); + expectedFieldsValidator.setHttpStatusCode((long) 200); + expectedFieldsValidator.setFields(fields); + expectedFieldsValidator.setErrorCode(null); + FunctionalMenuItemWithRoles menuItemJson = new FunctionalMenuItemWithRoles(); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(functionalMenuService.createFunctionalMenuItem(menuItemJson)).thenReturn(expectedFieldsValidator); + actualFieldsValidator = functionalMenuController.createFunctionalMenuItem(mockedRequest, menuItemJson, mockedResponse); + assertEquals(actualFieldsValidator, expectedFieldsValidator); + } + + @Test + public void createFunctionalMenuItemBadPermisssionsTest(){ + FieldsValidator actualFieldsValidator = null; + FieldsValidator expectedFieldsValidator = null; + FunctionalMenuItemWithRoles menuItemJson = new FunctionalMenuItemWithRoles(); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + Mockito.when(functionalMenuService.createFunctionalMenuItem(menuItemJson)).thenReturn(expectedFieldsValidator); + actualFieldsValidator = functionalMenuController.createFunctionalMenuItem(mockedRequest, menuItemJson, mockedResponse); + assertEquals(actualFieldsValidator, expectedFieldsValidator); + } + + @Test + public void getFavoritesForUserTest(){ + List<FavoritesFunctionalMenuItemJson> actualFavoritesFunctionalMenuItemsJson = null; + List<FavoritesFunctionalMenuItemJson> expectedFunctionalMenuItemsJson = new ArrayList<FavoritesFunctionalMenuItemJson>(); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + Mockito.when(functionalMenuService.getFavoriteItems(user.getId())).thenReturn(expectedFunctionalMenuItemsJson); + actualFavoritesFunctionalMenuItemsJson = functionalMenuController.getFavoritesForUser(mockedRequest, mockedResponse); + assertEquals(actualFavoritesFunctionalMenuItemsJson, expectedFunctionalMenuItemsJson); + } + + @Test + public void deleteFavoriteItemTest(){ + Long userId = (long)1; + Long menuId = (long)1; + FieldsValidator actualFieldsValidator = new FieldsValidator(); + FieldsValidator expectedFieldsValidator = new FieldsValidator(); + List<FieldName> fields = new ArrayList<>(); + expectedFieldsValidator.setHttpStatusCode((long) 200); + expectedFieldsValidator.setFields(fields); + expectedFieldsValidator.setErrorCode(null); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(functionalMenuService.removeFavoriteItem(user.getId(), menuId)).thenReturn(actualFieldsValidator); + actualFieldsValidator = functionalMenuController.deleteFavoriteItem(mockedRequest, menuId, mockedResponse); + assertEquals(actualFieldsValidator, expectedFieldsValidator); + } + + @Test + public void addFavoriteItemTest(){ + FavoritesFunctionalMenuItem menuItemJson = new FavoritesFunctionalMenuItem(); + FieldsValidator actualFieldsValidator = new FieldsValidator(); + FieldsValidator expectedFieldsValidator = new FieldsValidator(); + List<FieldName> fields = new ArrayList<>(); + expectedFieldsValidator.setHttpStatusCode((long) 200); + expectedFieldsValidator.setFields(fields); + expectedFieldsValidator.setErrorCode(null); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(functionalMenuService.setFavoriteItem(menuItemJson)).thenReturn(actualFieldsValidator); + actualFieldsValidator = functionalMenuController.addFavoriteItem(mockedRequest, menuItemJson, mockedResponse); + assertEquals(actualFieldsValidator, expectedFieldsValidator); + } + + @Test + public void getMenuItemsTest(){ + List<FunctionalMenuItem> actualFunctionalMenuItems = new ArrayList<FunctionalMenuItem>(); + List<FunctionalMenuItem> expectedFunctionalMenuItems = new ArrayList<FunctionalMenuItem>(); + List<FunctionalMenuItem> menuItems = new ArrayList<FunctionalMenuItem>(); + Mockito.when(functionalMenuService.getFunctionalMenuItems()).thenReturn(menuItems); + actualFunctionalMenuItems = functionalMenuController.getMenuItems(mockedRequest, mockedResponse); + assertEquals(actualFunctionalMenuItems, expectedFunctionalMenuItems); + } + + @Test + public void deleteFunctionalMenuItemTest(){ + Long menuId = (long)1; + FieldsValidator actualFieldsValidator = new FieldsValidator(); + FieldsValidator expectedFieldsValidator = new FieldsValidator(); + List<FieldName> fields = new ArrayList<>(); + expectedFieldsValidator.setHttpStatusCode((long) 200); + expectedFieldsValidator.setFields(fields); + expectedFieldsValidator.setErrorCode(null); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(functionalMenuService.deleteFunctionalMenuItem(menuId)).thenReturn(actualFieldsValidator); + actualFieldsValidator = functionalMenuController.deleteFunctionalMenuItem(mockedRequest, menuId, mockedResponse); + assertEquals(actualFieldsValidator, expectedFieldsValidator); + } + + @Test + public void deleteFunctionalMenuItemBadPermissionsTest(){ + Long menuId = (long)1; + FieldsValidator actualFieldsValidator = null; + FieldsValidator expectedFieldsValidator = null; + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + Mockito.when(functionalMenuService.deleteFunctionalMenuItem(menuId)).thenReturn(actualFieldsValidator); + actualFieldsValidator = functionalMenuController.deleteFunctionalMenuItem(mockedRequest, menuId, mockedResponse); + assertEquals(actualFieldsValidator, expectedFieldsValidator); + } + + @Test + public void editFunctionalMenuItemTest(){ + FunctionalMenuItemWithRoles menuItemJson = new FunctionalMenuItemWithRoles(); + FieldsValidator actualFieldsValidator = new FieldsValidator(); + FieldsValidator expectedFieldsValidator = new FieldsValidator(); + List<FieldName> fields = new ArrayList<>(); + expectedFieldsValidator.setHttpStatusCode((long) 200); + expectedFieldsValidator.setFields(fields); + expectedFieldsValidator.setErrorCode(null); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(functionalMenuService.editFunctionalMenuItem(menuItemJson)).thenReturn(actualFieldsValidator); + actualFieldsValidator = functionalMenuController.editFunctionalMenuItem(mockedRequest, menuItemJson, mockedResponse); + assertEquals(actualFieldsValidator, expectedFieldsValidator); + } + + @Test + public void editFunctionalMenuItemBadPermissionsTest(){ + FunctionalMenuItemWithRoles menuItemJson = new FunctionalMenuItemWithRoles(); + FieldsValidator actualFieldsValidator = null; + FieldsValidator expectedFieldsValidator = null; + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + Mockito.when(functionalMenuService.editFunctionalMenuItem(menuItemJson)).thenReturn(actualFieldsValidator); + actualFieldsValidator = functionalMenuController.editFunctionalMenuItem(mockedRequest, menuItemJson, mockedResponse); + assertEquals(actualFieldsValidator, expectedFieldsValidator); + } + + @Test + public void getECOMPTitleTest(){ + PortalRestResponse<String> actualportalRestResponse = null; + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK); + expectedportalRestResponse.setMessage("success"); + expectedportalRestResponse.setResponse("Portal"); + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME)).thenReturn("Portal"); + actualportalRestResponse = functionalMenuController.getECOMPTitle(mockedRequest, mockedResponse); + assertEquals(actualportalRestResponse, expectedportalRestResponse); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/GetAccessControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/GetAccessControllerTest.java new file mode 100644 index 00000000..8ee27f8d --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/GetAccessControllerTest.java @@ -0,0 +1,71 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.GetAccessController; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.GetAccessResult; +import org.openecomp.portalapp.portal.service.GetAccessService; +import org.openecomp.portalapp.portal.service.GetAccessServiceImpl; +import org.openecomp.portalapp.util.EPUserUtils; + +public class GetAccessControllerTest { + + @Mock + GetAccessService getAccessService = new GetAccessServiceImpl(); + + @InjectMocks + GetAccessController getAccessController = new GetAccessController(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + MockEPUser mockUser = new MockEPUser(); + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + + + @Test + public void getAppList() throws IOException + { + List<GetAccessResult> expectedAppsList = new ArrayList<GetAccessResult>(); + EPUser user = mockUser.mockEPUser(); + GetAccessResult getAccessResult = new GetAccessResult(); + getAccessResult.setRowId("1"); + getAccessResult.setRoleId((long) 1); + getAccessResult.setEcompFunction("test"); + getAccessResult.setAppName("Test_App"); + getAccessResult.setAppMotsId(1); + getAccessResult.setRoleName("Test_role"); + getAccessResult.setRoleActive("N"); + getAccessResult.setReqType("test"); + + expectedAppsList.add(getAccessResult); + + List<GetAccessResult> actualAppsList = null; + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(getAccessService.getAppAccessList(user)).thenReturn(expectedAppsList); + actualAppsList = getAccessController.getAppList(mockedRequest); + assertTrue(actualAppsList.contains(getAccessResult)); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/ManifestControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/ManifestControllerTest.java new file mode 100644 index 00000000..c7a870cf --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/ManifestControllerTest.java @@ -0,0 +1,56 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.jar.Attributes; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.ManifestController; +import org.openecomp.portalapp.portal.service.ManifestService; +import org.openecomp.portalapp.portal.service.ManifestServiceImpl; + +public class ManifestControllerTest extends MockitoTestSuite{ + + + @Mock + ManifestService manifestService = new ManifestServiceImpl(); + + @InjectMocks + ManifestController manifestController = new ManifestController(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + NullPointerException nullPointerException = new NullPointerException(); + + @Test + public void getManifestTest() throws IOException + { + Map<String, Object> expectedResponse = new HashMap<String, Object>(); + Attributes attributes = new Attributes(); + expectedResponse.put("test", attributes); + Mockito.when(manifestService.getWebappManifest()).thenReturn(attributes); + Map<String, Object> actualResponse = manifestController.getManifest(mockedRequest); + assertTrue((actualResponse.keySet().toArray().length) == 1); + + } + + @Test + public void getManifestExceptionTest() throws IOException + { + Mockito.when(manifestService.getWebappManifest()).thenThrow(nullPointerException); + Map<String, Object> actualResponse = manifestController.getManifest(mockedRequest); + assertTrue((actualResponse.keySet().toArray().length) == 1); + assertTrue(actualResponse.get("error").equals("failed to get manifest: java.lang.NullPointerException")); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/MicroserviceControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/MicroserviceControllerTest.java new file mode 100644 index 00000000..0b12e3bc --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/MicroserviceControllerTest.java @@ -0,0 +1,232 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.MicroserviceController; +import org.openecomp.portalapp.portal.domain.MicroserviceData; +import org.openecomp.portalapp.portal.domain.WidgetCatalog; +import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.service.ConsulHealthService; +import org.openecomp.portalapp.portal.service.ConsulHealthServiceImpl; +import org.openecomp.portalapp.portal.service.MicroserviceService; +import org.openecomp.portalapp.portal.service.MicroserviceServiceImpl; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(WidgetServiceHeaders.class) +public class MicroserviceControllerTest extends MockitoTestSuite{ + + @InjectMocks + MicroserviceController microserviceController = new MicroserviceController(); + + @Mock + ConsulHealthService consulHealthService = new ConsulHealthServiceImpl(); + + @Mock + MicroserviceService microserviceService = new MicroserviceServiceImpl(); + + @Mock + RestTemplate template = new RestTemplate(); + + @Mock + MicroserviceData microserviceData = new MicroserviceData(); + + @SuppressWarnings("rawtypes") + @Mock + ResponseEntity<List<WidgetCatalog>> ans = new ResponseEntity<List<WidgetCatalog>>(HttpStatus.OK); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Mock + EcompPortalUtils EcompPortalUtils = new EcompPortalUtils(); + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + + @Test + public void createMicroserviceIfServiceDataNullTest() throws Exception { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("FAILURE"); + expectedportalRestResponse.setResponse("MicroserviceData cannot be null or empty"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + MicroserviceData microserviceData = null; + PortalRestResponse<String> actualportalRestResponse = microserviceController.createMicroservice(mockedRequest, + mockedResponse, microserviceData); + assertEquals(actualportalRestResponse, expectedportalRestResponse); + } + + @Test + public void createMicroserviceTest() throws Exception { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("SUCCESS"); + expectedportalRestResponse.setResponse(""); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + PortalRestResponse<String> actualportalRestResponse = microserviceController.createMicroservice(mockedRequest, + mockedResponse, microserviceData); + assertEquals(actualportalRestResponse, expectedportalRestResponse); + } + + @Test + public void createMicroserviceExceptionTest() throws Exception { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("FAILURE"); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + Mockito.when(microserviceService.saveMicroservice(microserviceData)).thenReturn((long) 1); + Mockito.when(microserviceData.getParameterList()).thenThrow(nullPointerException); + PortalRestResponse<String> actualportalRestResponse = microserviceController.createMicroservice(mockedRequest, + mockedResponse, microserviceData); + assertEquals(actualportalRestResponse, expectedportalRestResponse); + } + + @Test + public void getMicroserviceTest() throws Exception { + Mockito.when(microserviceService.getMicroserviceData()).thenReturn(null); + List<MicroserviceData> list = microserviceController.getMicroservice(mockedRequest, mockedResponse); + assertEquals(list, null); + } + + @Test + public void updateMicroserviceIfServiceISNullTest() throws Exception { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("FAILURE"); + expectedportalRestResponse.setResponse("MicroserviceData cannot be null or empty"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + MicroserviceData microserviceData = null; + PortalRestResponse<String> actualportalRestResponse = microserviceController.updateMicroservice(mockedRequest, + mockedResponse, 1, microserviceData); + assertEquals(actualportalRestResponse, expectedportalRestResponse); + } + + @Test + public void updateMicroserviceTest() throws Exception { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("SUCCESS"); + expectedportalRestResponse.setResponse(""); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + PortalRestResponse<String> actualportalRestResponse = microserviceController.updateMicroservice(mockedRequest, + mockedResponse, 1, microserviceData); + assertEquals(actualportalRestResponse, expectedportalRestResponse); + } + + @Test + public void updateMicroserviceExceptionTest() throws Exception { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("FAILURE"); + expectedportalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + Mockito.when(microserviceController.updateMicroservice(mockedRequest, mockedResponse, 1, microserviceData)) + .thenThrow(nullPointerException); + PortalRestResponse<String> actualportalRestResponse = microserviceController.updateMicroservice(mockedRequest, + mockedResponse, 1, microserviceData); + assertEquals(actualportalRestResponse, expectedportalRestResponse); + } + + @Test + public void deleteMicroserviceExceptionTest() throws Exception { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("FAILURE"); + expectedportalRestResponse.setResponse( + "I/O error on GET request for \"" + EcompPortalUtils.widgetMsProtocol() + "://null/widget/microservices/widgetCatalog/service/1\":null; nested exception is java.net.UnknownHostException: null"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + PowerMockito.mockStatic(WidgetServiceHeaders.class); + PortalRestResponse<String> actuaPportalRestResponse = microserviceController.deleteMicroservice(mockedRequest, + mockedResponse, 1); + assertEquals(actuaPportalRestResponse.getStatus(), expectedportalRestResponse.getStatus()); + } + + @SuppressWarnings("unchecked") + @Test + public void deleteMicroserviceTest() throws Exception { + String HTTPS = "https://"; + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("SOME WIDGETS ASSOICATE WITH THIS SERVICE"); + expectedportalRestResponse.setResponse("'null' ,'null' "); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.WARN); + List<WidgetCatalog> List = new ArrayList<WidgetCatalog>(); + WidgetCatalog widgetCatalog = new WidgetCatalog(); + widgetCatalog.setId(1); + WidgetCatalog widgetCatalog1 = new WidgetCatalog(); + widgetCatalog.setId(2); + List.add(widgetCatalog); + List.add(widgetCatalog1); + PowerMockito.mockStatic(WidgetServiceHeaders.class); + String whatService = "widgets-service"; + Mockito.when(consulHealthService.getServiceLocation(whatService, SystemProperties.getProperty("microservices.widget.local.port"))).thenReturn("Test"); + Mockito.when(ans.getBody()).thenReturn(List); + ParameterizedTypeReference<List<WidgetCatalog>> typeRef = new ParameterizedTypeReference<List<WidgetCatalog>>() { + }; + Mockito.when(template.exchange( + HTTPS + consulHealthService.getServiceLocation(whatService, SystemProperties.getProperty("microservices.widget.local.port")) + + "/widget/microservices/widgetCatalog/service/" + 1, + HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), typeRef)).thenReturn(ans); + + PortalRestResponse<String> actuaPportalRestResponse = microserviceController.deleteMicroservice(mockedRequest, + mockedResponse, 1); + assertEquals(actuaPportalRestResponse, expectedportalRestResponse); + } + + @SuppressWarnings("unchecked") + @Test + public void deleteMicroserviceWhenNoWidgetsAssociatedTest() throws Exception { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("SUCCESS"); + expectedportalRestResponse.setResponse(""); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + List<WidgetCatalog> List = new ArrayList<WidgetCatalog>(); + PowerMockito.mockStatic(WidgetServiceHeaders.class); + String whatService = "widgets-service"; + Mockito.when(consulHealthService.getServiceLocation(whatService, SystemProperties.getProperty("microservices.widget.local.port"))).thenReturn("Test"); + Mockito.when(ans.getBody()).thenReturn(List); + ParameterizedTypeReference<List<WidgetCatalog>> typeRef = new ParameterizedTypeReference<List<WidgetCatalog>>() { + }; + Mockito.when(template.exchange( + EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, SystemProperties.getProperty("microservices.widget.local.port")) + + "/widget/microservices/widgetCatalog/service/" + 1, + HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), typeRef)).thenReturn(ans); + PortalRestResponse<String> actuaPportalRestResponse = microserviceController.deleteMicroservice(mockedRequest, + mockedResponse, 1); + assertEquals(actuaPportalRestResponse, expectedportalRestResponse); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/MicroserviceProxyControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/MicroserviceProxyControllerTest.java new file mode 100644 index 00000000..0cb8dcdb --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/MicroserviceProxyControllerTest.java @@ -0,0 +1,106 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.assertTrue; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.MicroserviceProxyController; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.service.MicroserviceProxyService; +import org.openecomp.portalapp.portal.service.MicroserviceProxyServiceImpl; +import org.openecomp.portalapp.util.EPUserUtils; +import org.springframework.http.HttpStatus; +import org.springframework.web.client.HttpClientErrorException; + +import com.fasterxml.jackson.databind.ObjectMapper; + + + +public class MicroserviceProxyControllerTest extends MockitoTestSuite { + + @Mock + MicroserviceProxyService microserviceProxyService = new MicroserviceProxyServiceImpl(); + + @InjectMocks + MicroserviceProxyController microserviceProxyController = new MicroserviceProxyController(); + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + + @Mock + EPUserUtils ePUserUtils = new EPUserUtils(); + @Mock + ObjectMapper objectMapper = new ObjectMapper(); + MockEPUser mockUser = new MockEPUser(); + + @Test + public void getMicroserviceProxyTest() throws Exception { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(microserviceProxyService.proxyToDestination(1, user, mockedRequest)).thenReturn("Success"); + String acutualString = microserviceProxyController.getMicroserviceProxy(mockedRequest, getMockedResponse(), 1); + assertTrue(acutualString.equals("{\"error\":\"Success\"}")); + } + + @Test(expected = NullPointerException.class) + public void getMicroserviceProxyNullPoniterExceptionTest() throws Exception { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(microserviceProxyService.proxyToDestination(1, user, mockedRequest)) + .thenThrow(nullPointerException); + microserviceProxyController.getMicroserviceProxy(mockedRequest, getMockedResponse(), 1); + } + + @Test + public void getMicroserviceProxyExceptionTest() throws Exception { + HttpClientErrorException httpClientErrorException = new HttpClientErrorException(HttpStatus.OK, "Success"); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(microserviceProxyService.proxyToDestination(1, user, mockedRequest)) + .thenThrow(httpClientErrorException); + String acutualString = microserviceProxyController.getMicroserviceProxy(mockedRequest, getMockedResponse(), 1); + assertTrue(acutualString.equals("{\"error\":\"\"}")); + } + + @Test + public void getMicroserviceProxyByWidgetIdTest() throws Exception { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(microserviceProxyService.proxyToDestinationByWidgetId(1, user, mockedRequest)) + .thenReturn("Success"); + String acutualString = microserviceProxyController.getMicroserviceProxyByWidgetId(mockedRequest, + getMockedResponse(), 1); + assertTrue(acutualString.equals("{\"error\":\"Success\"}")); + } + + @Test(expected = NullPointerException.class) + public void getMicroserviceProxyByWidgetIdNullPointerExceptionTest() throws Exception { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(microserviceProxyService.proxyToDestinationByWidgetId(1, user, mockedRequest)) + .thenThrow(nullPointerException); + microserviceProxyController.getMicroserviceProxyByWidgetId(mockedRequest, getMockedResponse(), 1); + } + + @Test + public void getMicroserviceProxyByWidgetIdExceptionTest() throws Exception { + HttpClientErrorException httpClientErrorException = new HttpClientErrorException(HttpStatus.OK, "Success"); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(microserviceProxyService.proxyToDestinationByWidgetId(1, user, mockedRequest)) + .thenThrow(httpClientErrorException); + String acutualString = microserviceProxyController.getMicroserviceProxyByWidgetId(mockedRequest, + getMockedResponse(), 1); + assertTrue(acutualString.equals("{\"error\":\"\"}")); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/PortalAdminControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/PortalAdminControllerTest.java new file mode 100644 index 00000000..6917b6e7 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/PortalAdminControllerTest.java @@ -0,0 +1,155 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.PortalAdminController; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.exceptions.NoHealthyServiceException; +import org.openecomp.portalapp.portal.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.AdminRolesServiceImpl; +import org.openecomp.portalapp.portal.service.PortalAdminService; +import org.openecomp.portalapp.portal.service.PortalAdminServiceImpl; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.PortalAdmin; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.service.AuditService; +import org.openecomp.portalsdk.core.service.AuditServiceImpl; + +public class PortalAdminControllerTest extends MockitoTestSuite{ + + @InjectMocks + PortalAdminController portalAdminController = new PortalAdminController(); + + @Mock + AdminRolesService adminRolesService = new AdminRolesServiceImpl(); + + @Mock + PortalAdminService portalAdminService = new PortalAdminServiceImpl(); + + @Mock + AuditService auditService = new AuditServiceImpl(); + + + @Mock + EcompPortalUtils ecompPortalUtils = new EcompPortalUtils(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + + @Mock + EPUserUtils ePUserUtils = new EPUserUtils(); + + MockEPUser mockUser = new MockEPUser(); + + + @Test + public void getPortalAdminsTest() + { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<PortalAdmin> expectedPortalAdminsList = new ArrayList<PortalAdmin>(); + PortalAdmin portalAdmin= new PortalAdmin(); + + portalAdmin.setUserId((long) 1); + portalAdmin.setLoginId("guestT"); + portalAdmin.setFirstName("Test_FirstName"); + portalAdmin.setLastName("Test_LastName"); + + expectedPortalAdminsList.add(portalAdmin); + + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + + Mockito.when(portalAdminService.getPortalAdmins()).thenReturn(expectedPortalAdminsList); + List<PortalAdmin> actualPortalAdminsList = portalAdminController.getPortalAdmins(mockedRequest, mockedResponse); + assertEquals(actualPortalAdminsList,expectedPortalAdminsList); + + } +// @Test +// public void getPortalAdminsIfUserIsNullTest() +// { +// EPUser user = null; +// Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); +// +// assertNull(portalAdminController.getPortalAdmins(mockedRequest, mockedResponse)); +// +// } + + @Test + public void getPortalAdminsIfUserIsSuperAdminTest() + { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + assertNull(portalAdminController.getPortalAdmins(mockedRequest, mockedResponse)); + + } + + + + @Test + public void createPortalAdminTest() + { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + + FieldsValidator expectedFieldValidator = new FieldsValidator(); + expectedFieldValidator.setHttpStatusCode((long) 200); + expectedFieldValidator.setFields(null); + expectedFieldValidator.setErrorCode(null); + FieldsValidator actualFieldValidator = new FieldsValidator(); + String sbcid = "Test"; + + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(portalAdminService.createPortalAdmin(sbcid)).thenReturn(expectedFieldValidator); + actualFieldValidator = portalAdminController.createPortalAdmin(mockedRequest, sbcid, mockedResponse); + assertEquals(actualFieldValidator,expectedFieldValidator); + + } + +// @Test +// public void createPortalAdminIfUserIsNullTest() +// { +// //EPUser user = null; +// Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(null); +// String sbcid = "null"; +// assertNull(portalAdminController.createPortalAdmin(mockedRequest, sbcid, mockedResponse)); +// +// } + + @Test + public void createPortalAdminIfUserIsSuperAdminTest() + { + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + String sbcid = "Test"; + assertNull(portalAdminController.createPortalAdmin(mockedRequest, sbcid, mockedResponse)); + + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/RoleManageControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/RoleManageControllerTest.java new file mode 100644 index 00000000..ea7b532e --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/RoleManageControllerTest.java @@ -0,0 +1,189 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.assertEquals; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.controller.core.RoleController; +import org.openecomp.portalapp.controller.core.RoleFunctionListController; +import org.openecomp.portalapp.controller.core.RoleListController; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.RoleManageController; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.service.ExternalAccessRolesService; +import org.springframework.web.servlet.ModelAndView; + +public class RoleManageControllerTest { + + + + @Mock + RoleController roleController; + + @Mock + RoleListController roleListController; + + @Mock + RoleFunctionListController roleFunctionListController; + + + @Mock + ExternalAccessRolesService externalAccessRolesService; + + @Mock + ExternalAccessRolesService externalAccessRolesService1 = null; + + @InjectMocks + RoleManageController roleManageController = new RoleManageController(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + MockEPUser mockUser = new MockEPUser(); + + @Test + public void toggleRoleTest() + { + PortalRestResponse<String> portalRestResponse = new PortalRestResponse<String>(); + portalRestResponse.setMessage("success"); + portalRestResponse.setResponse(null); + PortalRestStatusEnum portalRestStatusEnum = null; + portalRestResponse.setStatus(portalRestStatusEnum.OK); + + PortalRestResponse<String> expectedpPortalRestResponse=roleManageController.toggleRole(mockedRequest, mockedResponse); + assertEquals(portalRestResponse,expectedpPortalRestResponse); + + } + +// @Test +// public void toggleRoleExceptionTest() +// { +// PortalRestResponse<String> portalRestResponse = new PortalRestResponse<String>(); +// portalRestResponse.setMessage("success"); +// portalRestResponse.setResponse(null); +// PortalRestStatusEnum portalRestStatusEnum = null; +// portalRestResponse.setStatus(portalRestStatusEnum.OK); +// Mockito.doNothing().when(roleListController).toggleRole(mockedRequest, mockedResponse))).th +// getRoleListController().toggleRole(request, response) +// +// PortalRestResponse<String> expectedpPortalRestResponse=roleManageController.toggleRole(mockedRequest, mockedResponse); +// assertEquals(portalRestResponse,expectedpPortalRestResponse); +// +// } + @Test + public void removeRoleTest() throws Exception + { + ModelAndView modelandView = new ModelAndView("login.htm"); + Mockito.when(roleListController.removeRole(mockedRequest, mockedResponse)).thenReturn(modelandView); + ModelAndView expectedModelandView = roleManageController.removeRole(mockedRequest, mockedResponse); + assertEquals(expectedModelandView, modelandView); + } + + @Test + public void saveRoleTest() throws Exception + { + ModelAndView modelandView = new ModelAndView("login.htm"); + Mockito.when(roleController.saveRole(mockedRequest, mockedResponse)).thenReturn(modelandView); + ModelAndView expectedModelandView = roleManageController.saveRole(mockedRequest, mockedResponse); + assertEquals(expectedModelandView, modelandView); + } + + @Test + public void removeRoleRoleFunctionTest() throws Exception + { + ModelAndView modelandView = new ModelAndView("login.htm"); + Mockito.when(roleController.removeRoleFunction(mockedRequest, mockedResponse)).thenReturn(modelandView); + ModelAndView expectedModelandView = roleManageController.removeRoleRoleFunction(mockedRequest, mockedResponse); + assertEquals(expectedModelandView, modelandView); + } + + @Test + public void addRoleRoRoleFunctionTest() throws Exception + { + ModelAndView modelandView = new ModelAndView("login.htm"); + Mockito.when(roleController.addRoleFunction(mockedRequest, mockedResponse)).thenReturn(modelandView); + ModelAndView expectedModelandView = roleManageController.addRoleRoRoleFunction(mockedRequest, mockedResponse); + assertEquals(expectedModelandView, modelandView); + } + + @Test + public void removeChildRoleTest() throws Exception + { + ModelAndView modelandView = new ModelAndView("login.htm"); + Mockito.when(roleController.removeChildRole(mockedRequest, mockedResponse)).thenReturn(modelandView); + ModelAndView expectedModelandView = roleManageController.removeChildRole(mockedRequest, mockedResponse); + assertEquals(expectedModelandView, modelandView); + } + + + @Test + public void getRoleTest() throws Exception + { + Mockito.doNothing().when(roleController).getRole(mockedRequest, mockedResponse); + roleManageController.getRole(mockedRequest, mockedResponse); + } + + @Test + public void getRolesTest() throws Exception + { + Mockito.doNothing().when(roleListController).getRoles(mockedRequest, mockedResponse); + roleManageController.getRoles(mockedRequest, mockedResponse); + } + + @Test + public void getRoleFunctionListTest() throws Exception + { + Mockito.doNothing().when(roleFunctionListController).getRoleFunctionList(mockedRequest, mockedResponse); + roleManageController.getRoleFunctionList(mockedRequest, mockedResponse); + } + + @Test + public void saveRoleFunctionTest() throws Exception + { + Mockito.doNothing().when(roleFunctionListController).saveRoleFunction(mockedRequest, mockedResponse, "test"); + roleManageController.saveRoleFunction(mockedRequest, mockedResponse, "test"); + } + + @Test + public void removeRoleFunctionTest() throws Exception + { + Mockito.doNothing().when(roleFunctionListController).removeRoleFunction(mockedRequest, mockedResponse, "test"); + roleManageController.removeRoleFunction(mockedRequest, mockedResponse, "test"); + } + + @Test + public void syncRolesTest() throws Exception + { + EPApp app = new EPApp(); + Mockito.doNothing().when(externalAccessRolesService).syncApplicationRolesWithEcompDB(app); + roleManageController.syncRoles(app); + } + + + @Test + public void addeChildRoleTest() throws Exception + { + ModelAndView modelandView = new ModelAndView("login.htm"); + Mockito.when(roleController.addChildRole(mockedRequest, mockedResponse)).thenReturn(modelandView); + ModelAndView expectedModelandView = roleManageController.addChildRole(mockedRequest, mockedResponse); + assertEquals(expectedModelandView, modelandView); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/RolesApprovalSystemControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/RolesApprovalSystemControllerTest.java new file mode 100644 index 00000000..e55b9a9c --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/RolesApprovalSystemControllerTest.java @@ -0,0 +1,336 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval; +import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemUser; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.RolesApprovalSystemController; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.service.UserRolesService; +import org.openecomp.portalapp.portal.transport.ExternalRequestFieldsValidator; + +public class RolesApprovalSystemControllerTest extends MockitoTestSuite { + + @Mock + UserRolesService userRolesService; + + @InjectMocks + RolesApprovalSystemController rolesApprovalSystemController = new RolesApprovalSystemController(); + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void postUserProfileIfRolesNullTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Request has no roles"); + expectedportalRestResponse.setResponse("save user profile failed"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + ExternalSystemUser extSysUser = new ExternalSystemUser(); + extSysUser.setApplicationName("Test_App"); + extSysUser.setLoginId("1"); + extSysUser.setMyloginrequestId("Test"); + List<ExternalSystemRoleApproval> externalSystemRoleApprovalList = null; + extSysUser.setRoles(externalSystemRoleApprovalList); + + PortalRestResponse<String> actualportalRestResponse = rolesApprovalSystemController + .postUserProfile(mockedRequest, extSysUser, mockedResponse); + assertEquals(expectedportalRestResponse, actualportalRestResponse); + } + + @Test + public void postUserProfileTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Saved Successfully"); + expectedportalRestResponse.setResponse("Success"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + ExternalSystemUser extSysUser = new ExternalSystemUser(); + extSysUser.setApplicationName("Test_App"); + extSysUser.setLoginId("1"); + extSysUser.setMyloginrequestId("Test"); + List<ExternalSystemRoleApproval> externalSystemRoleApprovalList = new ArrayList<ExternalSystemRoleApproval>(); + ExternalSystemRoleApproval externalSystemRoleApproval = new ExternalSystemRoleApproval(); + externalSystemRoleApprovalList.add(externalSystemRoleApproval); + extSysUser.setRoles(externalSystemRoleApprovalList); + ExternalRequestFieldsValidator externalRequestFieldsValidator = new ExternalRequestFieldsValidator(true, + "Saved Successfully"); + + Mockito.when(userRolesService.setExternalRequestUserAppRole(extSysUser, "POST")) + .thenReturn(externalRequestFieldsValidator); + PortalRestResponse<String> actualportalRestResponse = rolesApprovalSystemController + .postUserProfile(mockedRequest, extSysUser, mockedResponse); + assertEquals(expectedportalRestResponse, actualportalRestResponse); + } + + @Test + public void postUserProfileFailureTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Received Bad String"); + expectedportalRestResponse.setResponse("save user profile failed"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + ExternalSystemUser extSysUser = new ExternalSystemUser(); + extSysUser.setApplicationName("Test_App"); + extSysUser.setLoginId("1"); + extSysUser.setMyloginrequestId("Test"); + List<ExternalSystemRoleApproval> externalSystemRoleApprovalList = new ArrayList<ExternalSystemRoleApproval>(); + ExternalSystemRoleApproval externalSystemRoleApproval = new ExternalSystemRoleApproval(); + externalSystemRoleApprovalList.add(externalSystemRoleApproval); + extSysUser.setRoles(externalSystemRoleApprovalList); + ExternalRequestFieldsValidator externalRequestFieldsValidator = new ExternalRequestFieldsValidator(false, + "Received Bad String"); + Mockito.when(userRolesService.setExternalRequestUserAppRole(extSysUser, "POST")) + .thenReturn(externalRequestFieldsValidator); + + PortalRestResponse<String> actualportalRestResponse = rolesApprovalSystemController + .postUserProfile(mockedRequest, extSysUser, mockedResponse); + assertEquals(expectedportalRestResponse, actualportalRestResponse); + } + + @Test + public void postUserProfileExceptionTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage(null); + expectedportalRestResponse.setResponse("save user profile failed"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + ExternalSystemUser extSysUser = new ExternalSystemUser(); + extSysUser.setApplicationName("Test_App"); + extSysUser.setLoginId("1"); + extSysUser.setMyloginrequestId("Test"); + List<ExternalSystemRoleApproval> externalSystemRoleApprovalList = new ArrayList<ExternalSystemRoleApproval>(); + ExternalSystemRoleApproval externalSystemRoleApproval = new ExternalSystemRoleApproval(); + externalSystemRoleApprovalList.add(externalSystemRoleApproval); + extSysUser.setRoles(externalSystemRoleApprovalList); + Mockito.when(userRolesService.setExternalRequestUserAppRole(extSysUser, "POST")).thenThrow(nullPointerException); + PortalRestResponse<String> actualportalRestResponse = rolesApprovalSystemController + .postUserProfile(mockedRequest, extSysUser, mockedResponse); + assertEquals(expectedportalRestResponse, actualportalRestResponse); + } + + @Test + public void putUserProfileIfLoginIdNullTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Request has no login ID"); + expectedportalRestResponse.setResponse("save user profile failed"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + ExternalSystemUser extSysUser = new ExternalSystemUser(); + extSysUser.setApplicationName("Test_App"); + extSysUser.setLoginId(null); + extSysUser.setMyloginrequestId("Test"); + List<ExternalSystemRoleApproval> externalSystemRoleApprovalList = new ArrayList<ExternalSystemRoleApproval>(); + extSysUser.setRoles(externalSystemRoleApprovalList); + PortalRestResponse<String> actualportalRestResponse = rolesApprovalSystemController + .putUserProfile(mockedRequest, extSysUser, mockedResponse); + assertEquals(expectedportalRestResponse, actualportalRestResponse); + } + + @Test + public void putUserProfileTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Updated Successfully"); + expectedportalRestResponse.setResponse("Success"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + ExternalSystemUser extSysUser = new ExternalSystemUser(); + extSysUser.setApplicationName("Test_App"); + extSysUser.setLoginId("1"); + extSysUser.setMyloginrequestId("Test"); + List<ExternalSystemRoleApproval> externalSystemRoleApprovalList = new ArrayList<ExternalSystemRoleApproval>(); + ExternalSystemRoleApproval externalSystemRoleApproval = new ExternalSystemRoleApproval(); + externalSystemRoleApprovalList.add(externalSystemRoleApproval); + extSysUser.setRoles(externalSystemRoleApprovalList); + ExternalRequestFieldsValidator externalRequestFieldsValidator = new ExternalRequestFieldsValidator(true, + "Updated Successfully"); + + Mockito.when(userRolesService.setExternalRequestUserAppRole(extSysUser, "PUT")) + .thenReturn(externalRequestFieldsValidator); + PortalRestResponse<String> actualportalRestResponse = rolesApprovalSystemController + .putUserProfile(mockedRequest, extSysUser, mockedResponse); + assertEquals(expectedportalRestResponse, actualportalRestResponse); + } + + @Test + public void putUserProfileFailureTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Received Bad String"); + expectedportalRestResponse.setResponse("save user profile failed"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + ExternalSystemUser extSysUser = new ExternalSystemUser(); + extSysUser.setApplicationName("Test_App"); + extSysUser.setLoginId("1"); + extSysUser.setMyloginrequestId("Test"); + List<ExternalSystemRoleApproval> externalSystemRoleApprovalList = new ArrayList<ExternalSystemRoleApproval>(); + ExternalSystemRoleApproval externalSystemRoleApproval = new ExternalSystemRoleApproval(); + externalSystemRoleApprovalList.add(externalSystemRoleApproval); + extSysUser.setRoles(externalSystemRoleApprovalList); + ExternalRequestFieldsValidator externalRequestFieldsValidator = new ExternalRequestFieldsValidator(false, + "Received Bad String"); + + Mockito.when(userRolesService.setExternalRequestUserAppRole(extSysUser, "PUT")) + .thenReturn(externalRequestFieldsValidator); + PortalRestResponse<String> actualportalRestResponse = rolesApprovalSystemController + .putUserProfile(mockedRequest, extSysUser, mockedResponse); + + assertEquals(expectedportalRestResponse, actualportalRestResponse); + } + + @Test + public void putUserProfileExceptionTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage(null); + expectedportalRestResponse.setResponse("save user profile failed"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + ExternalSystemUser extSysUser = new ExternalSystemUser(); + extSysUser.setApplicationName("Test_App"); + extSysUser.setLoginId("1"); + extSysUser.setMyloginrequestId("Test"); + List<ExternalSystemRoleApproval> externalSystemRoleApprovalList = new ArrayList<ExternalSystemRoleApproval>(); + ExternalSystemRoleApproval externalSystemRoleApproval = new ExternalSystemRoleApproval(); + externalSystemRoleApprovalList.add(externalSystemRoleApproval); + extSysUser.setRoles(externalSystemRoleApprovalList); + Mockito.when(userRolesService.setExternalRequestUserAppRole(extSysUser, "PUT")).thenThrow(nullPointerException); + PortalRestResponse<String> actualportalRestResponse = rolesApprovalSystemController + .putUserProfile(mockedRequest, extSysUser, mockedResponse); + + assertEquals(expectedportalRestResponse, actualportalRestResponse); + } + + @Test + public void deleteUserProfileIfApplicationNameNullTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Request has no application name"); + expectedportalRestResponse.setResponse("delete user profile failed"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + ExternalSystemUser extSysUser = new ExternalSystemUser(); + extSysUser.setApplicationName(null); + extSysUser.setLoginId("1"); + extSysUser.setMyloginrequestId("Test"); + List<ExternalSystemRoleApproval> externalSystemRoleApprovalList = new ArrayList<ExternalSystemRoleApproval>(); + extSysUser.setRoles(externalSystemRoleApprovalList); + PortalRestResponse<String> actualportalRestResponse = rolesApprovalSystemController + .deleteUserProfile(mockedRequest, extSysUser, mockedResponse); + + assertEquals(expectedportalRestResponse, actualportalRestResponse); + } + + @Test + public void deleteUserProfileIfMyloginrequestIdNullTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Request has no request ID"); + expectedportalRestResponse.setResponse("delete user profile failed"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + ExternalSystemUser extSysUser = new ExternalSystemUser(); + extSysUser.setApplicationName("Test"); + extSysUser.setLoginId("1"); + extSysUser.setMyloginrequestId(null); + List<ExternalSystemRoleApproval> externalSystemRoleApprovalList = new ArrayList<ExternalSystemRoleApproval>(); + extSysUser.setRoles(externalSystemRoleApprovalList); + PortalRestResponse<String> actualportalRestResponse = rolesApprovalSystemController + .deleteUserProfile(mockedRequest, extSysUser, mockedResponse); + assertEquals(expectedportalRestResponse, actualportalRestResponse); + } + + @Test + public void deleteUserProfileTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("Deleted Successfully"); + expectedportalRestResponse.setResponse("Success"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.OK); + ExternalSystemUser extSysUser = new ExternalSystemUser(); + extSysUser.setApplicationName("Test_App"); + extSysUser.setLoginId("1"); + extSysUser.setMyloginrequestId("Test"); + List<ExternalSystemRoleApproval> externalSystemRoleApprovalList = new ArrayList<ExternalSystemRoleApproval>(); + ExternalSystemRoleApproval externalSystemRoleApproval = new ExternalSystemRoleApproval(); + externalSystemRoleApprovalList.add(externalSystemRoleApproval); + extSysUser.setRoles(externalSystemRoleApprovalList); + ExternalRequestFieldsValidator externalRequestFieldsValidator = new ExternalRequestFieldsValidator(true, + "Success"); + + Mockito.when(userRolesService.setExternalRequestUserAppRole(extSysUser, "DELETE")) + .thenReturn(externalRequestFieldsValidator); + PortalRestResponse<String> actualportalRestResponse = rolesApprovalSystemController + .deleteUserProfile(mockedRequest, extSysUser, mockedResponse); + + assertEquals(expectedportalRestResponse, actualportalRestResponse); + } + + @Test + public void deleteUserProfileFailureTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage("failed"); + expectedportalRestResponse.setResponse("delete user profile failed"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + ExternalSystemUser extSysUser = new ExternalSystemUser(); + extSysUser.setApplicationName("Test_App"); + extSysUser.setLoginId("1"); + extSysUser.setMyloginrequestId("Test"); + List<ExternalSystemRoleApproval> externalSystemRoleApprovalList = new ArrayList<ExternalSystemRoleApproval>(); + ExternalSystemRoleApproval externalSystemRoleApproval = new ExternalSystemRoleApproval(); + externalSystemRoleApprovalList.add(externalSystemRoleApproval); + extSysUser.setRoles(externalSystemRoleApprovalList); + ExternalRequestFieldsValidator externalRequestFieldsValidator = new ExternalRequestFieldsValidator(false, + "failed"); + + Mockito.when(userRolesService.setExternalRequestUserAppRole(extSysUser, "DELETE")) + .thenReturn(externalRequestFieldsValidator); + PortalRestResponse<String> actualportalRestResponse = rolesApprovalSystemController + .deleteUserProfile(mockedRequest, extSysUser, mockedResponse); + + assertEquals(expectedportalRestResponse, actualportalRestResponse); + } + + @Test + public void deleteUserProfileExceptionTest() { + PortalRestResponse<String> expectedportalRestResponse = new PortalRestResponse<String>(); + expectedportalRestResponse.setMessage(null); + expectedportalRestResponse.setResponse("delete user profile failed"); + PortalRestStatusEnum portalRestStatusEnum = null; + expectedportalRestResponse.setStatus(portalRestStatusEnum.ERROR); + ExternalSystemUser extSysUser = new ExternalSystemUser(); + extSysUser.setApplicationName("Test_App"); + extSysUser.setLoginId("1"); + extSysUser.setMyloginrequestId("Test"); + List<ExternalSystemRoleApproval> externalSystemRoleApprovalList = new ArrayList<ExternalSystemRoleApproval>(); + ExternalSystemRoleApproval externalSystemRoleApproval = new ExternalSystemRoleApproval(); + externalSystemRoleApprovalList.add(externalSystemRoleApproval); + extSysUser.setRoles(externalSystemRoleApprovalList); + Mockito.when(userRolesService.setExternalRequestUserAppRole(extSysUser, "DELETE")).thenThrow(nullPointerException); + PortalRestResponse<String> actualportalRestResponse = rolesApprovalSystemController + .deleteUserProfile(mockedRequest, extSysUser, mockedResponse); + + assertEquals(expectedportalRestResponse, actualportalRestResponse); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/SessionCommunicationControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/SessionCommunicationControllerTest.java new file mode 100644 index 00000000..0f6f6ca6 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/SessionCommunicationControllerTest.java @@ -0,0 +1,59 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.*; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.drools.core.command.assertion.AssertEquals; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.controller.sessionmgt.SessionCommunicationController; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.service.sessionmgt.ManageService; + +public class SessionCommunicationControllerTest { + + + @Mock + ManageService manageService; + + @InjectMocks + SessionCommunicationController SessionCommunicationController = new SessionCommunicationController(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + NullPointerException nullPointerException = new NullPointerException(); + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + MockEPUser mockUser = new MockEPUser(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + + + @Test + public void getSessionSlotCheckIntervalTest() throws Exception + { + Mockito.when(manageService.fetchSessionSlotCheckInterval()).thenReturn(1); + int result = SessionCommunicationController.getSessionSlotCheckInterval(mockedRequest, mockedResponse); + assertEquals(result, 1); + + } + + @Test + public void extendSessionTimeOutsTest() throws Exception + { + Mockito.doNothing().when(manageService).extendSessionTimeOuts("test"); + Boolean result = SessionCommunicationController.extendSessionTimeOuts(mockedRequest, mockedResponse, "test"); + assertEquals(result, true); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/TicketEventControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/TicketEventControllerTest.java new file mode 100644 index 00000000..9347cf6a --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/TicketEventControllerTest.java @@ -0,0 +1,99 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.TicketEventController; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.service.UserNotificationService; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(UserUtils.class) +public class TicketEventControllerTest { + + @Mock + UserNotificationService userNotificationService; + + @InjectMocks + TicketEventController ticketEventController = new TicketEventController(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + MockEPUser mockUser = new MockEPUser(); + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + +// @Test +// public void saveTest() throws Exception { +// String ticketEventJson = "{\"application\": \"cbus\",\"event\": {\"body\": {\"ticketStatePhrase\": \"We recently detected a problem with the equipment at your site. The event is in queue for immediate work.\", \"ivrNotificationFlag\": \"1\",\"expectedRestoreDate\": 0,\"bridgeTransport\": \"AOTS\", \"reptRequestType\": 0,\"ticketNum\": \"000002000857405\",\"assetID\": \"CISCO_1921C1_ISR_G2\", \"eventDate\": 1490545134601,\"eventAbstract\": \"ospfIfConfigError trap received from Cisco_1921c1_ISR_G2 with arguments: ospfRouterId=Cisco_1921c1_ISR_G2; ospfIfIpAddress=1921c1_288266; ospfAddressLessIf=0; ospfPacketSrc=172.17.0.11; ospfConfigErrorType=2; ospfPacketType=1\",\"severity\": \"2 - Major\",\"ticketPriority\": \"3\",\"reportedCustomerImpact\": 0,\"testAutoIndicator\": 0,\"supportGroupName\": \"US-TEST-ORT\",\"lastModifiedDate\": \"1487687703\",\"messageGroup\": \"SNMP\",\"csi\": 0,\"mfabRestoredTime\": 0},\"header\": {\"timestamp\": \"2017-02-21T14:35:05.219+0000\",\"eventSource\": \"aotstm\",\"entityId\": \"000002000857405\", \"sequenceNumber\": 2 },\"blinkMsgId\": \"f38c071e-1a47-4b55-9e72-1db830100a61\",\"sourceIP\": \"130.4.165.158\"},\"SubscriberInfo\": {\"UserList\": [\"hk8777\"] }}"; +// PortalRestResponse<String> actualPortalRestResponse = ticketEventController.handleRequest(mockedRequest, +// mockedResponse, ticketEventJson); +// assertTrue(actualPortalRestResponse.getStatus().compareTo(PortalRestStatusEnum.OK) == 0); +// } + + @Test + public void saveTestForException() throws Exception { + String ticketEventJson = "\"event\": {\"body\": {\"ticketStatePhrase\": \"We recently detected a problem with the equipment at your site. The event is in queue for immediate work.\", \"ivrNotificationFlag\": \"1\",\"expectedRestoreDate\": 0,\"bridgeTransport\": \"AOTS\", \"reptRequestType\": 0,\"ticketNum\": \"000002000857405\",\"assetID\": \"CISCO_1921C1_ISR_G2\", \"eventDate\": 1490545134601,\"eventAbstract\": \"ospfIfConfigError trap received from Cisco_1921c1_ISR_G2 with arguments: ospfRouterId=Cisco_1921c1_ISR_G2; ospfIfIpAddress=1921c1_288266; ospfAddressLessIf=0; ospfPacketSrc=172.17.0.11; ospfConfigErrorType=2; ospfPacketType=1\",\"severity\": \"2 - Major\",\"ticketPriority\": \"3\",\"reportedCustomerImpact\": 0,\"testAutoIndicator\": 0,\"supportGroupName\": \"US-TEST-ORT\",\"lastModifiedDate\": \"1487687703\",\"messageGroup\": \"SNMP\",\"csi\": 0,\"mfabRestoredTime\": 0},\"header\": {\"timestamp\": \"2017-02-21T14:35:05.219+0000\",\"eventSource\": \"aotstm\",\"entityId\": \"000002000857405\", \"sequenceNumber\": 2 },\"blinkMsgId\": \"f38c071e-1a47-4b55-9e72-1db830100a61\",\"sourceIP\": \"130.4.165.158\"},\"SubscriberInfo\": {\"UserList\": [\"hk8777\"] }}"; + PortalRestResponse<String> actualPortalRestResponse = ticketEventController.handleRequest(mockedRequest, + mockedResponse, ticketEventJson); + assertTrue(actualPortalRestResponse.getStatus().compareTo(PortalRestStatusEnum.ERROR) == 0); + } + +// @Test +// public void saveTestForApplicationValid() throws Exception { +// String ticketEventJson = "{\"event\": {\"body\": {\"ticketStatePhrase\": \"We recently detected a problem with the equipment at your site. The event is in queue for immediate work.\", \"ivrNotificationFlag\": \"1\",\"expectedRestoreDate\": 0,\"bridgeTransport\": \"AOTS\", \"reptRequestType\": 0,\"ticketNum\": \"000002000857405\",\"assetID\": \"CISCO_1921C1_ISR_G2\", \"eventDate\": 1490545134601,\"eventAbstract\": \"ospfIfConfigError trap received from Cisco_1921c1_ISR_G2 with arguments: ospfRouterId=Cisco_1921c1_ISR_G2; ospfIfIpAddress=1921c1_288266; ospfAddressLessIf=0; ospfPacketSrc=172.17.0.11; ospfConfigErrorType=2; ospfPacketType=1\",\"severity\": \"2 - Major\",\"ticketPriority\": \"3\",\"reportedCustomerImpact\": 0,\"testAutoIndicator\": 0,\"supportGroupName\": \"US-TEST-ORT\",\"lastModifiedDate\": \"1487687703\",\"messageGroup\": \"SNMP\",\"csi\": 0,\"mfabRestoredTime\": 0},\"header\": {\"timestamp\": \"2017-02-21T14:35:05.219+0000\",\"eventSource\": \"aotstm\",\"entityId\": \"000002000857405\", \"sequenceNumber\": 2 },\"blinkMsgId\": \"f38c071e-1a47-4b55-9e72-1db830100a61\",\"sourceIP\": \"130.4.165.158\"},\"SubscriberInfo\": {\"UserList\": [\"hk8777\"] }}"; +// PortalRestResponse<String> actualPortalRestResponse = ticketEventController.handleRequest(mockedRequest, +// mockedResponse, ticketEventJson); +// assertTrue(actualPortalRestResponse.getStatus().compareTo(PortalRestStatusEnum.ERROR) == 0); +// assertEquals(actualPortalRestResponse.getMessage(), "application is mandatory"); +// +// } + + @Test + public void saveTestForBodyValid() throws Exception { + String ticketEventJson = "{\"application\": \"cbus\",\"event\": {\"header\": {\"timestamp\": \"2017-02-21T14:35:05.219+0000\",\"eventSource\": \"aotstm\",\"entityId\": \"000002000857405\",\"sequenceNumber\": 2 },\"blinkMsgId\": \"f38c071e-1a47-4b55-9e72-1db830100a61\",\"sourceIP\": \"130.4.165.158\"},\"SubscriberInfo\": {\"UserList\": [\"hk8777\"] }}"; + PortalRestResponse<String> actualPortalRestResponse = ticketEventController.handleRequest(mockedRequest, + mockedResponse, ticketEventJson); + assertTrue(actualPortalRestResponse.getStatus().compareTo(PortalRestStatusEnum.ERROR) == 0); + assertEquals(actualPortalRestResponse.getMessage(), "body is mandatory"); + } + + @Test + public void saveTestForEventSourceValid() throws Exception { + String ticketEventJson = "{\"application\": \"cbus\",\"event\": {\"body\": {\"ticketStatePhrase\": \"We recently detected a problem with the equipment at your site. The event is in queue for immediate work.\", \"ivrNotificationFlag\": \"1\",\"expectedRestoreDate\": 0,\"bridgeTransport\": \"AOTS\", \"reptRequestType\": 0,\"ticketNum\": \"000002000857405\",\"assetID\": \"CISCO_1921C1_ISR_G2\", \"eventDate\": 1490545134601,\"eventAbstract\": \"ospfIfConfigError trap received from Cisco_1921c1_ISR_G2 with arguments: ospfRouterId=Cisco_1921c1_ISR_G2; ospfIfIpAddress=1921c1_288266; ospfAddressLessIf=0; ospfPacketSrc=172.17.0.11; ospfConfigErrorType=2; ospfPacketType=1\",\"severity\": \"2 - Major\",\"ticketPriority\": \"3\",\"reportedCustomerImpact\": 0,\"testAutoIndicator\": 0,\"supportGroupName\": \"US-TEST-ORT\",\"lastModifiedDate\": \"1487687703\",\"messageGroup\": \"SNMP\",\"csi\": 0,\"mfabRestoredTime\": 0},\"header\": {\"timestamp\": \"2017-02-21T14:35:05.219+0000\",\"entityId\": \"000002000857405\", \"sequenceNumber\": 2 },\"blinkMsgId\": \"f38c071e-1a47-4b55-9e72-1db830100a61\",\"sourceIP\": \"130.4.165.158\"},\"SubscriberInfo\": {\"UserList\": [\"hk8777\"] }}"; + PortalRestResponse<String> actualPortalRestResponse = ticketEventController.handleRequest(mockedRequest, + mockedResponse, ticketEventJson); + assertTrue(actualPortalRestResponse.getStatus().compareTo(PortalRestStatusEnum.ERROR) == 0); + assertEquals(actualPortalRestResponse.getMessage(), "Message Source is mandatory"); + } + + @Test + public void saveTestForUserListValid() throws Exception { + String ticketEventJson = "{\"application\": \"cbus\",\"event\": {\"body\": {\"ticketStatePhrase\": \"We recently detected a problem with the equipment at your site. The event is in queue for immediate work.\", \"ivrNotificationFlag\": \"1\",\"expectedRestoreDate\": 0,\"bridgeTransport\": \"AOTS\", \"reptRequestType\": 0,\"ticketNum\": \"000002000857405\",\"assetID\": \"CISCO_1921C1_ISR_G2\", \"eventDate\": 1490545134601,\"eventAbstract\": \"ospfIfConfigError trap received from Cisco_1921c1_ISR_G2 with arguments: ospfRouterId=Cisco_1921c1_ISR_G2; ospfIfIpAddress=1921c1_288266; ospfAddressLessIf=0; ospfPacketSrc=172.17.0.11; ospfConfigErrorType=2; ospfPacketType=1\",\"severity\": \"2 - Major\",\"ticketPriority\": \"3\",\"reportedCustomerImpact\": 0,\"testAutoIndicator\": 0,\"supportGroupName\": \"US-TEST-ORT\",\"lastModifiedDate\": \"1487687703\",\"messageGroup\": \"SNMP\",\"csi\": 0,\"mfabRestoredTime\": 0},\"header\": {\"timestamp\": \"2017-02-21T14:35:05.219+0000\",\"eventSource\": \"aotstm\",\"entityId\": \"000002000857405\", \"sequenceNumber\": 2 },\"blinkMsgId\": \"f38c071e-1a47-4b55-9e72-1db830100a61\",\"sourceIP\": \"130.4.165.158\"},\"SubscriberInfo\": {}}"; + PortalRestResponse<String> actualPortalRestResponse = ticketEventController.handleRequest(mockedRequest, + mockedResponse, ticketEventJson); + assertTrue(actualPortalRestResponse.getStatus().compareTo(PortalRestStatusEnum.ERROR) == 0); + assertEquals(actualPortalRestResponse.getMessage(), "At least one user Id is mandatory"); + } +}
\ No newline at end of file diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/UserControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/UserControllerTest.java new file mode 100644 index 00000000..acfa25a4 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/UserControllerTest.java @@ -0,0 +1,141 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.assertEquals; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.UserController; +import org.openecomp.portalapp.portal.core.MockEPUser; +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.service.UserService; +import org.openecomp.portalapp.portal.service.UserServiceImpl; +import org.openecomp.portalapp.portal.transport.ProfileDetail; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(CipherUtil.class) +public class UserControllerTest extends MockitoTestSuite { + + @InjectMocks + UserController userController = new UserController(); + + @Mock + UserService userService = new UserServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Mock + EPUserUtils ePUserUtils = new EPUserUtils(); + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + + MockEPUser mockUser = new MockEPUser(); + + @Test + public void getLoggedinUserExceptionTest() { + EPUser epUser = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(epUser); + PortalRestResponse<ProfileDetail> expectedResponse = new PortalRestResponse<ProfileDetail>(); + expectedResponse.setMessage(null); + expectedResponse.setResponse(null); + PortalRestStatusEnum enu = null; + expectedResponse.setStatus(enu.ERROR); + PortalRestResponse<ProfileDetail> response = userController.getLoggedinUser(mockedRequest); + assertEquals(response, expectedResponse); + } + + @Test + public void getLoggedinUserTest() throws Exception { + EPUser epUser = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(epUser); + PortalRestResponse<ProfileDetail> expectedResponse = new PortalRestResponse<ProfileDetail>(); + expectedResponse.setMessage("success"); + ProfileDetail profileDetail = new ProfileDetail(); + expectedResponse.setResponse(profileDetail); + PortalRestStatusEnum enu = null; + expectedResponse.setStatus(enu.OK); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(CipherUtil.decrypt(epUser.getLoginPwd())).thenReturn("Password"); + PortalRestResponse<ProfileDetail> response = userController.getLoggedinUser(mockedRequest); + assertEquals(response.getMessage(), expectedResponse.getMessage()); + assertEquals(response.getStatus(), expectedResponse.getStatus()); + } + + @Test + public void modifyLoggedinUserIfProfileNullTest() { + PortalRestResponse<String> expectedResponse = new PortalRestResponse<String>(); + expectedResponse.setMessage("java.lang.NullPointerException"); + expectedResponse.setResponse(null); + PortalRestStatusEnum enu = null; + expectedResponse.setStatus(enu.ERROR); + ProfileDetail profileDetail = null; + PortalRestResponse<String> actualResponse = userController.modifyLoggedinUser(mockedRequest, profileDetail); + assertEquals(actualResponse, expectedResponse); + assertEquals(actualResponse.getStatus(), expectedResponse.getStatus()); + } + + @Test + public void modifyLoggedinUserExceptionTest() { + EPUser epUser = mockUser.mockEPUser(); + + PortalRestResponse<String> expectedResponse = new PortalRestResponse<String>(); + expectedResponse.setMessage( + "java.lang.ClassCastException: com.sun.crypto.provider.AESCipher$General cannot be cast to javax.crypto.CipherSpi"); + expectedResponse.setResponse(null); + PortalRestStatusEnum enu = null; + expectedResponse.setStatus(enu.ERROR); + ProfileDetail profileDetail = new ProfileDetail(); + profileDetail.setFirstName("Test_FirstName"); + profileDetail.setLastName("Test_LastName"); + profileDetail.setEmail("Test_Email"); + profileDetail.setLoginId("Test_LoginId"); + profileDetail.setLoginPassword("Test_LoginPassword"); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(epUser); + PortalRestResponse<String> actualResponse = userController.modifyLoggedinUser(mockedRequest, profileDetail); + assertEquals(actualResponse, expectedResponse); + + } + + /*@Test + public void modifyLoggedinUserTest() throws Exception { + EPUser epUser = mockUser.mockEPUser(); + PortalRestResponse<String> expectedResponse = new PortalRestResponse<String>(); + expectedResponse.setMessage("success"); + expectedResponse.setResponse(null); + PortalRestStatusEnum enu = null; + expectedResponse.setStatus(enu.OK); + ProfileDetail profileDetail = new ProfileDetail(); + profileDetail.setFirstName("Test_FirstName"); + profileDetail.setLastName("Test_LastName"); + profileDetail.setEmail("Test_Email"); + profileDetail.setLoginId("Test_LoginId"); + profileDetail.setLoginPassword("Test_LoginPassword"); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(epUser); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(CipherUtil.decrypt(epUser.getLoginPwd())).thenReturn("Password"); + PortalRestResponse<String> actualResponse = userController.modifyLoggedinUser(mockedRequest, profileDetail); + System.out.println(actualResponse); + }*/ +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/UserNotificationControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/UserNotificationControllerTest.java new file mode 100644 index 00000000..ebe5f7cd --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/UserNotificationControllerTest.java @@ -0,0 +1,263 @@ +/*- + * ================================================================================ + * 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 static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.UserNotificationController; +import org.openecomp.portalapp.portal.core.MockEPUser; +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.service.FunctionalMenuService; +import org.openecomp.portalapp.portal.service.FunctionalMenuServiceImpl; +import org.openecomp.portalapp.portal.service.UserNotificationService; +import org.openecomp.portalapp.portal.service.UserNotificationServiceImpl; +import org.openecomp.portalapp.portal.transport.EpNotificationItem; +import org.openecomp.portalapp.portal.transport.EpNotificationItemVO; +import org.openecomp.portalapp.portal.transport.FunctionalMenuRole; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(UserUtils.class) +public class UserNotificationControllerTest { + + @Mock + FunctionalMenuService functionalMenuService = new FunctionalMenuServiceImpl(); + + @Mock + UserNotificationService userNotificationService = new UserNotificationServiceImpl(); + + @InjectMocks + UserNotificationController userNotificationController = new UserNotificationController(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + MockEPUser mockUser = new MockEPUser(); + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + + @Test + public void getMenuIdRoleIdTest() { + List<FunctionalMenuRole> expectedMenuRoleList = new ArrayList<FunctionalMenuRole>(); + FunctionalMenuRole functionalMenuRole = new FunctionalMenuRole(); + functionalMenuRole.setId(new Integer(99999999)); + functionalMenuRole.setMenuId((long) 137); + functionalMenuRole.setAppId(new Integer(456)); + functionalMenuRole.setRoleId(new Integer(6214)); + expectedMenuRoleList.add(functionalMenuRole); + List<FunctionalMenuRole> actualFunctionalMenuRoleList = null; + Mockito.when(functionalMenuService.getFunctionalMenuRole()).thenReturn(expectedMenuRoleList); + actualFunctionalMenuRoleList = userNotificationController.getMenuIdRoleId(mockedRequest, mockedResponse); + assertTrue(actualFunctionalMenuRoleList.equals(expectedMenuRoleList)); + + } + + @Test + public void getNotificationsTest() { + EPUser user = mockUser.mockEPUser(); + HttpSession session = mockedRequest.getSession(); + session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<EpNotificationItem> expectedEpNotificationList = new ArrayList<EpNotificationItem>(); + EpNotificationItem epNotificationItem = new EpNotificationItem(); + epNotificationItem.setNotificationId((long) 200); + expectedEpNotificationList.add(epNotificationItem); + PortalRestResponse<List<EpNotificationItem>> expectedportalRestResponse = new PortalRestResponse<List<EpNotificationItem>>(); + expectedportalRestResponse.setMessage("success"); + expectedportalRestResponse.setResponse(expectedEpNotificationList); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.OK); + PortalRestResponse<List<EpNotificationItem>> actualPortalRestResponse = null; + Mockito.when(userNotificationService.getNotifications(user.getId())).thenReturn(expectedEpNotificationList); + actualPortalRestResponse = userNotificationController.getNotifications(mockedRequest, mockedResponse); + assertTrue(expectedportalRestResponse.equals(actualPortalRestResponse)); + + } + + @Test + public void getNotificationsCatchesExceptionTest() { + EPUser user = mockUser.mockEPUser(); + HttpSession session = mockedRequest.getSession(); + session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<EpNotificationItem> expectedEpNotificationList = null; + PortalRestResponse<List<EpNotificationItem>> expectedportalRestResponse = new PortalRestResponse<List<EpNotificationItem>>(); + expectedportalRestResponse.setMessage(null); + expectedportalRestResponse.setResponse(expectedEpNotificationList); + expectedportalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + PortalRestResponse<List<EpNotificationItem>> actualPortalRestResponse = null; + Mockito.when(userNotificationService.getNotifications(user.getId())).thenThrow(new NullPointerException()); + actualPortalRestResponse = userNotificationController.getNotifications(mockedRequest, mockedResponse); + assertTrue(expectedportalRestResponse.equals(actualPortalRestResponse)); + } + + @Test + public void getAdminNotificationsTest() { + EPUser user = mockUser.mockEPUser(); + HttpSession session = mockedRequest.getSession(); + session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<EpNotificationItemVO> actualEpNotificationsList = new ArrayList<EpNotificationItemVO>(); + List<EpNotificationItemVO> expectedEpNotificationsList = new ArrayList<EpNotificationItemVO>(); + EpNotificationItemVO epNotificationItemVO = new EpNotificationItemVO(); + epNotificationItemVO.setId((long) 1); + expectedEpNotificationsList.add(epNotificationItemVO); + Mockito.when(userNotificationService.getAdminNotificationVOS(Matchers.anyLong())).thenReturn(expectedEpNotificationsList); + actualEpNotificationsList = userNotificationController.getAdminNotifications(mockedRequest, mockedResponse); + assertTrue(actualEpNotificationsList.equals(expectedEpNotificationsList)); + } + + @Test + public void saveTestWhenNotificationIsNull() throws Exception { + EPUser user = mockUser.mockEPUser(); + HttpSession session = mockedRequest.getSession(); + session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + + PortalRestResponse<String> actualPortalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> expectedPortalRestResponse = new PortalRestResponse<String>(); + expectedPortalRestResponse.setMessage("FAILURE"); + expectedPortalRestResponse.setResponse("Notification Header cannot be null or empty"); + expectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + + EpNotificationItem notificationItem = null; + actualPortalRestResponse = userNotificationController.save(mockedRequest, mockedResponse, notificationItem); + assertTrue(actualPortalRestResponse.equals(expectedPortalRestResponse)); + } + + @Test + public void saveTestWhenEndTimeIsGreater() throws Exception { + EPUser user = mockUser.mockEPUser(); + HttpSession session = mockedRequest.getSession(); + session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + PortalRestResponse<String> actualPortalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> expectedPortalRestResponse = new PortalRestResponse<String>(); + expectedPortalRestResponse.setMessage("FAILURE"); + expectedPortalRestResponse.setResponse("End Time should be greater than start time"); + expectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + EpNotificationItem notificationItem = new EpNotificationItem(); + notificationItem.setNotificationId((long) 1); + notificationItem.setMsgHeader("Test"); + Date currentDate = new Date(); + Calendar c = Calendar.getInstance(); + c.setTime(currentDate); + c.add(Calendar.DATE, 1); + Date currentDatePlusOne = c.getTime(); + notificationItem.setStartTime(currentDatePlusOne); + notificationItem.setEndTime(currentDate); + + actualPortalRestResponse = userNotificationController.save(mockedRequest, mockedResponse, notificationItem); + assertTrue(actualPortalRestResponse.equals(expectedPortalRestResponse)); + + } + + @Test + public void saveTestWhenNoRoleIDExists() throws Exception { + EPUser user = mockUser.mockEPUser(); + HttpSession session = mockedRequest.getSession(); + session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + PortalRestResponse<String> actualPortalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> expectedPortalRestResponse = new PortalRestResponse<String>(); + expectedPortalRestResponse.setMessage("FAILURE"); + expectedPortalRestResponse.setResponse("No Roles Ids Exist for the selected Roles"); + expectedPortalRestResponse.setStatus(PortalRestStatusEnum.ERROR); + EpNotificationItem notificationItem = new EpNotificationItem(); + notificationItem.setNotificationId((long) 1); + notificationItem.setMsgHeader("Test"); + notificationItem.setIsForAllRoles("N"); + Date currentDate = new Date(); + Calendar c = Calendar.getInstance(); + c.setTime(currentDate); + c.add(Calendar.DATE, 1); + Date currentDatePlusOne = c.getTime(); + notificationItem.setStartTime(currentDate); + notificationItem.setEndTime(currentDatePlusOne); + List<Long> roleList = new ArrayList<Long>(); + notificationItem.setRoleIds(roleList); + actualPortalRestResponse = userNotificationController.save(mockedRequest, mockedResponse, notificationItem); + assertTrue(actualPortalRestResponse.equals(expectedPortalRestResponse)); + } + + @Test + public void saveTest() throws Exception { + EPUser user = mockUser.mockEPUser(); + HttpSession session = mockedRequest.getSession(); + session.setAttribute("user", user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + PortalRestResponse<String> actualPortalRestResponse = new PortalRestResponse<String>(); + PortalRestResponse<String> expectedPortalRestResponse = new PortalRestResponse<String>(); + expectedPortalRestResponse.setMessage("SUCCESS"); + expectedPortalRestResponse.setResponse(""); + expectedPortalRestResponse.setStatus(PortalRestStatusEnum.OK); + EpNotificationItem notificationItem = new EpNotificationItem(); + notificationItem.setNotificationId((long) 1); + notificationItem.setMsgHeader("Test"); + notificationItem.setIsForAllRoles("Y"); + Date currentDate = new Date(); + Calendar c = Calendar.getInstance(); + c.setTime(currentDate); + c.add(Calendar.DATE, 1); + Date currentDatePlusOne = c.getTime(); + notificationItem.setStartTime(currentDate); + notificationItem.setEndTime(currentDatePlusOne); + List<Long> roleList = new ArrayList<Long>(); + Long role1 = (long) 1; + roleList.add(role1); + notificationItem.setRoleIds(roleList); + HttpServletRequest request = mockitoTestSuite.getMockedRequest(); + PowerMockito.mockStatic(UserUtils.class); + Mockito.when(UserUtils.getUserIdAsLong(request)).thenReturn((long) 1); + Mockito.when(userNotificationService.saveNotification(notificationItem)).thenReturn("Test"); + actualPortalRestResponse = userNotificationController.save(mockedRequest, mockedResponse, notificationItem); + assertTrue(actualPortalRestResponse.equals(expectedPortalRestResponse)); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/UserRolesControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/UserRolesControllerTest.java new file mode 100644 index 00000000..56fa6a4d --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/UserRolesControllerTest.java @@ -0,0 +1,308 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.UserRolesController; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EcompAuditLog; +import org.openecomp.portalapp.portal.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.SearchService; +import org.openecomp.portalapp.portal.service.UserRolesService; +import org.openecomp.portalapp.portal.transport.AppWithRolesForUser; +import org.openecomp.portalapp.portal.transport.AppsListWithAdminRole; +import org.openecomp.portalapp.portal.transport.FieldsValidator; +import org.openecomp.portalapp.portal.transport.FieldsValidator.FieldName; +import org.openecomp.portalapp.portal.transport.RoleInAppForUser; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.service.AuditService; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({EcompPortalUtils.class, EPCommonSystemProperties.class, EcompAuditLog.class, SystemProperties.class}) +public class UserRolesControllerTest extends MockitoTestSuite { + + String userid = "ab1234"; + + @Mock + UserRolesService userRolesService; + + @Mock + SearchService searchService; + + @Mock + AuditService auditService; + + @Mock + AdminRolesService adminRolesService; + + @Mock + FieldsValidator fieldsValidator; + + @InjectMocks + UserRolesController userRolesController = new UserRolesController(); + + @Mock + private DataAccessService dataAccessService; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + + @Mock + EPUserUtils ePUserUtils = new EPUserUtils(); + + @Mock + EPUser epuser; + + MockEPUser mockUser = new MockEPUser(); + + @Test + public void putAppWithUserRoleRequestTest() { + + FieldsValidator actualFieldsValidator = null; + + AppWithRolesForUser appWithRolesForUser = new AppWithRolesForUser(); + List<RoleInAppForUser> listofRoles = new ArrayList<RoleInAppForUser>(); + + appWithRolesForUser.setOrgUserId("guest"); + appWithRolesForUser.setAppId((long) 550); + appWithRolesForUser.setAppName("D2 Services Analytics Dashboard"); + appWithRolesForUser.setAppRoles(listofRoles); + + RoleInAppForUser roleInAppForUser = new RoleInAppForUser(); + roleInAppForUser.setIsApplied(false); + roleInAppForUser.setRoleId((long) 1); + roleInAppForUser.setRoleName("System Administrator"); + + RoleInAppForUser roleInAppForUser1 = new RoleInAppForUser(); + roleInAppForUser1.setIsApplied(true); + roleInAppForUser1.setRoleId((long) 16); + roleInAppForUser1.setRoleName("Standard User"); + + listofRoles.add(roleInAppForUser); + listofRoles.add(roleInAppForUser1); + EPUser user = mockUser.mockEPUser(); + FieldsValidator expectedFieldValidator = new FieldsValidator(); + List<FieldName> fields = new ArrayList<>(); + + expectedFieldValidator.setHttpStatusCode((long) 200); + expectedFieldValidator.setFields(fields); + expectedFieldValidator.setErrorCode(null); + HttpSession session = mockedRequest.getSession(); + session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user); + + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(userRolesService.putUserAppRolesRequest(appWithRolesForUser, user)) + .thenReturn(expectedFieldValidator); + + actualFieldsValidator = userRolesController.putAppWithUserRoleRequest(mockedRequest, appWithRolesForUser, + mockedResponse); + assertEquals(expectedFieldValidator.getHttpStatusCode(), actualFieldsValidator.getHttpStatusCode()); + assertEquals(expectedFieldValidator.getErrorCode(), actualFieldsValidator.getErrorCode()); + assertEquals(expectedFieldValidator.getFields(), actualFieldsValidator.getFields()); + + } + + @Test + public void getPhoneBookSearchResultBadPermissionsTest() { + String searchString = "test"; + String actualResult = null; + String expectedResult = null; + + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + Mockito.when(adminRolesService.isAccountAdmin(user)).thenReturn(false); + Mockito.when(searchService.searchUsersInPhoneBook(searchString)).thenReturn(actualResult); + + actualResult = userRolesController.getPhoneBookSearchResult(mockedRequest, searchString, mockedResponse); + assertEquals(expectedResult, actualResult); + + } + + @Test + public void getPhoneBookSearchResultValidationTest() { + String searchString = " t"; + String actualResult = null; + String expectedResult = null; + + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(adminRolesService.isAccountAdmin(user)).thenReturn(false); + Mockito.when(searchService.searchUsersInPhoneBook(searchString)).thenReturn(actualResult); + + actualResult = userRolesController.getPhoneBookSearchResult(mockedRequest, searchString, mockedResponse); + assertEquals(expectedResult, actualResult); + + } + + @Test + public void getPhoneBookSearchResultTest() { + String searchString = "test"; + String actualResult = null; + String expectedResult = null; + + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(adminRolesService.isAccountAdmin(user)).thenReturn(false); + Mockito.when(searchService.searchUsersInPhoneBook(searchString)).thenReturn(actualResult); + + actualResult = userRolesController.getPhoneBookSearchResult(mockedRequest, searchString, mockedResponse); + assertEquals(expectedResult, actualResult); + + } + + @Test + public void getAppsWithAdminRoleStateForUserTest(){ + + String orgUserId = "hb123f"; + AppsListWithAdminRole actualResult = new AppsListWithAdminRole(); + AppsListWithAdminRole expectedResult = new AppsListWithAdminRole(); + EPUser user = mockUser.mockEPUser(); + // PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(adminRolesService.getAppsWithAdminRoleStateForUser(orgUserId)).thenReturn(actualResult); + + actualResult = userRolesController.getAppsWithAdminRoleStateForUser(mockedRequest, orgUserId, mockedResponse); + assertEquals(expectedResult, actualResult); + } + + /*@Test + public void getAppsWithAdminRoleStateForUserBadRequestTest(){ + + String orgUserId = "hb123f"; + AppsListWithAdminRole actualResult = null; + AppsListWithAdminRole expectedResult = null; + EPUser user = mockUser.mockEPUser(); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.when(EcompPortalUtils.legitimateUserId(orgUserId)).thenReturn(false); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(adminRolesService.getAppsWithAdminRoleStateForUser(orgUserId)).thenReturn(actualResult); + + actualResult = userRolesController.getAppsWithAdminRoleStateForUser(mockedRequest, orgUserId, mockedResponse); + assertEquals(expectedResult, actualResult); + }*/ + + @Test + public void putAppsWithAdminRoleStateForUserBadStatusCodeTest(){ + FieldsValidator actualFieldsValidator = null; + AppsListWithAdminRole newAppsListWithAdminRoles = new AppsListWithAdminRole(); + FieldsValidator expectedFieldsValidator = new FieldsValidator(); + List<FieldName> fieldNames = new ArrayList<FieldName>(); + expectedFieldsValidator.setErrorCode(null); + expectedFieldsValidator.setFields(fieldNames); + expectedFieldsValidator.setHttpStatusCode((long)200); + + EPUser user = mockUser.mockEPUser(); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + + actualFieldsValidator = userRolesController.putAppsWithAdminRoleStateForUser(mockedRequest, newAppsListWithAdminRoles, mockedResponse); + assertEquals(expectedFieldsValidator, actualFieldsValidator); + } + + + /*@Test + public void putAppsWithAdminRoleStateForUserTest() { + + FieldsValidator actualFieldsValidator = null; + AppsListWithAdminRole newAppsListWithAdminRoles = new AppsListWithAdminRole(); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(adminRolesService.isAccountAdmin(user)).thenReturn(false); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompAuditLog.class); + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.getProperty(EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN)).thenReturn("1400"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP)).thenReturn("1400"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)).thenReturn("1400"); + Mockito.when(SystemProperties.getProperty(SystemProperties.MDC_TIMER)).thenReturn("1400"); + + actualFieldsValidator = userRolesController.putAppsWithAdminRoleStateForUser(mockedRequest, newAppsListWithAdminRoles, mockedResponse); + + System.out.println(actualFieldsValidator); + Mockito.when(searchService.searchUsersInPhoneBook(searchString)).thenReturn(actualResult); + + actualResult = userRolesController.getPhoneBookSearchResult(mockedRequest, searchString, mockedResponse); + assertEquals(expectedResult, actualResult); + + }*/ + + /*@Test + public void putAppsWithAdminRoleStateForUserTest(){ + FieldsValidator actualFieldsValidator = null; + AppsListWithAdminRole newAppsListWithAdminRoles = new AppsListWithAdminRole(); + FieldsValidator expectedFieldsValidator = new FieldsValidator(); + List<FieldName> fieldNames = new ArrayList<FieldName>(); + expectedFieldsValidator.setErrorCode(null); + expectedFieldsValidator.setFields(fieldNames); + expectedFieldsValidator.setHttpStatusCode((long)200); + + EPUser user = mockUser.mockEPUser(); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompAuditLog.class); + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + Mockito.when(adminRolesService.setAppsWithAdminRoleStateForUser(newAppsListWithAdminRoles)); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + + // Mockito.call(auditService.logActivity(auditLog, null)); +// Mockito.when(SystemProperties.getProperty(EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN)).thenReturn("1400"); +// Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP)).thenReturn("1400"); +// Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP)).thenReturn("1400"); +// Mockito.when(SystemProperties.getProperty(SystemProperties.MDC_TIMER)).thenReturn("1400"); + + actualFieldsValidator = userRolesController.putAppsWithAdminRoleStateForUser(mockedRequest, newAppsListWithAdminRoles, mockedResponse); + assertEquals(expectedFieldsValidator, actualFieldsValidator); + }*/ +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/WebAnalyticsExtAppControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/WebAnalyticsExtAppControllerTest.java new file mode 100644 index 00000000..fde29913 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/WebAnalyticsExtAppControllerTest.java @@ -0,0 +1,110 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.*; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.io.IOUtils; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.WebAnalyticsExtAppController; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.AdminRolesServiceImpl; +import org.openecomp.portalapp.portal.service.AppsCacheService; +import org.openecomp.portalapp.portal.service.AppsCacheServiceImple; +import org.openecomp.portalapp.portal.transport.Analytics; +import org.openecomp.portalsdk.core.onboarding.crossapi.PortalAPIResponse; +import org.openecomp.portalsdk.core.service.AuditService; +import org.openecomp.portalsdk.core.service.AuditServiceImpl; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({SystemProperties.class,IOUtils.class,Object.class}) +public class WebAnalyticsExtAppControllerTest { + + + + @InjectMocks + WebAnalyticsExtAppController webAnalyticsExtAppController = new WebAnalyticsExtAppController(); + + @Mock + AdminRolesService adminRolesService = new AdminRolesServiceImpl(); + + @Mock + AppsCacheService appCacheService = new AppsCacheServiceImple(); + + @Mock + AuditService auditService = new AuditServiceImpl(); + +// @Mock +// InputStream analyticsFileStream; + + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + + /*@Test + public void getAnalyticsScriptTest() throws Exception + { + String expectedResponse = "http://www.ecomp.com"; + + InputStream analyticsFileStream = null; + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(IOUtils.class); + Mockito.when(IOUtils.toString(analyticsFileStream, StandardCharsets.UTF_8.name())).thenReturn("PORTAL_ENV_URL"); + Mockito.when(SystemProperties.getProperty("frontend_url")).thenReturn("http://www.ecomp.com/test"); + String actualResponse = webAnalyticsExtAppController.getAnalyticsScript(mockedRequest); +// assertNull(webAnalyticsExtAppController.getAnalyticsScript(mockedRequest)); + + // System.out.println(actualResponse); + assertTrue(actualResponse.equals(expectedResponse)); + }*/ + + /*@Test + public void getAnalyticsScriptExceptionTest() throws Exception + { + String expectedResponse = ""; + InputStream analyticsFileStream = null; + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(IOUtils.class); + Mockito.when(IOUtils.toString(analyticsFileStream, StandardCharsets.UTF_8.name())).thenThrow(nullPointerException); + Mockito.when(SystemProperties.getProperty("frontend_url")).thenReturn("http://www.ecomp.com/test"); + String actualResponse = webAnalyticsExtAppController.getAnalyticsScript(mockedRequest); + assertEquals(actualResponse,expectedResponse); + }*/ + + @Test + public void storeAnalyticsScriptIfAnalyticsNullTest() throws Exception + { + PortalAPIResponse expectedPortalAPIResponse = new PortalAPIResponse(true, "error"); + Analytics analytics= null; + Mockito.when(mockedRequest.getHeader("uebkey")).thenReturn(null); + PortalAPIResponse actualPortalAPIResponse = webAnalyticsExtAppController.storeAnalyticsScript(mockedRequest, analytics); + assertTrue(expectedPortalAPIResponse.getMessage().equals(actualPortalAPIResponse.getMessage())); + assertTrue(expectedPortalAPIResponse.getStatus().equals(actualPortalAPIResponse.getStatus())); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogControllerTest.java new file mode 100644 index 00000000..4087a599 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogControllerTest.java @@ -0,0 +1,87 @@ +//package org.openecomp.portalapp.portal.controller; +// +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +// +//import org.junit.Before; +//import org.junit.runner.RunWith; +//import org.mockito.InjectMocks; +//import org.mockito.Mock; +//import org.mockito.MockitoAnnotations; +//import org.openecomp.portalapp.portal.core.MockEPUser; +//import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +//import org.openecomp.portalapp.portal.service.ConsulHealthService; +//import org.openecomp.portalapp.portal.service.ConsulHealthServiceImpl; +//import org.openecomp.portalapp.portal.service.MicroserviceService; +//import org.openecomp.portalapp.portal.service.MicroserviceServiceImpl; +//import org.openecomp.portalapp.portal.service.WidgetParameterService; +//import org.openecomp.portalapp.portal.service.WidgetParameterServiceImpl; +//import org.openecomp.portalapp.util.EPUserUtils; +//import org.powermock.core.classloader.annotations.PrepareForTest; +//import org.powermock.modules.junit4.PowerMockRunner; +// +//@RunWith(PowerMockRunner.class) +//@PrepareForTest({EPUserUtils.class}) +//public class WidgetsCatalogControllerTest { +// +// @Mock +// ConsulHealthService consulHealthService = new ConsulHealthServiceImpl(); +// +// @Mock +// MicroserviceService microserviceService = new MicroserviceServiceImpl(); +// +// @Mock +// WidgetParameterService widgetParameterService = new WidgetParameterServiceImpl(); +// +// @InjectMocks +// WidgetsCatalogController widgetsCatalogController = new WidgetsCatalogController(); +// +// @Before +// public void setup() { +// MockitoAnnotations.initMocks(this); +// } +// +// MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); +// +// HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); +// HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); +// +// NullPointerException nullPointerException = new NullPointerException(); +// +// MockEPUser mockUser = new MockEPUser(); +// +// /*public List<WidgetCatalog> getUserWidgetCatalog(HttpServletRequest request, HttpServletResponse response, +// @PathVariable("loginName") String loginName) throws RestClientException, Exception { +// List<WidgetCatalog> widgets = new ArrayList<>(); +// try { +// CustomLoggingFilter d; +// ResponseEntity<ArrayList> ans = template.exchange( +// EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, +// SystemProperties.getProperty("microservices.widget.local.port")) +// + "/widget/microservices/widgetCatalog/" + loginName, +// HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), ArrayList.class); +// widgets = ans.getBody(); +// } catch (Exception e) { +// logger.error(EELFLoggerDelegate.errorLogger, "getUserWidgetCatalog failed", e); +// // returning null because null help check on the UI if there was a +// // communication problem with Microservice. +// return null; +// } +// return widgets; +// } +// +// @Test +// public void getWidgetDataTest(){ +// +// String resourceType = null; +// List<WidgetCatalog> expectedData = new ArrayList<WidgetCatalog>(); +// expectedData.setStatus(PortalRestStatusEnum.ERROR); +// expectedData.setMessage("Unexpected resource type null"); +// expectedData.setResponse(null); +// +// PortalRestResponse<CommonWidgetMeta> actualResponse = dashboardController.getWidgetData(mockedRequest, resourceType); +// assertEquals(expectedData,actualResponse); +// +// +// }*/ +//} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogMarkupControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogMarkupControllerTest.java new file mode 100644 index 00000000..bba49f71 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/controller/WidgetsCatalogMarkupControllerTest.java @@ -0,0 +1,72 @@ +package org.openecomp.portalapp.portal.controller; + +import static org.junit.Assert.assertTrue; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.controller.WidgetsCatalogMarkupController; +import org.openecomp.portalapp.portal.domain.WidgetServiceHeaders; +import org.openecomp.portalapp.portal.service.ConsulHealthService; +import org.openecomp.portalapp.portal.service.ConsulHealthServiceImpl; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(WidgetServiceHeaders.class) +public class WidgetsCatalogMarkupControllerTest extends MockitoTestSuite { + + @InjectMocks + WidgetsCatalogMarkupController widgetsCatalogMarkupController = new WidgetsCatalogMarkupController(); + + @Mock + ConsulHealthService consulHealthService = new ConsulHealthServiceImpl(); + + @Mock + RestTemplate template = new RestTemplate(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + @Mock + CipherUtil cipherUtil= new CipherUtil(); + + @Mock + EcompPortalUtils EcompPortalUtils =new EcompPortalUtils(); + + @Mock + WidgetServiceHeaders WidgetServiceHeaders ; + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + + @SuppressWarnings("static-access") + @Test + public void getWidgetMarkupTest() throws RestClientException, Exception + { + String whatService = "widgets-service"; + PowerMockito.mockStatic(WidgetServiceHeaders.class); + Mockito.when(template.getForObject(EcompPortalUtils.widgetMsProtocol() + "://" + consulHealthService.getServiceLocation(whatService, null) + "/widget/microservices/markup/" + 1, String.class, + WidgetServiceHeaders.getInstance())).thenReturn("Success"); + String response = widgetsCatalogMarkupController.getWidgetMarkup(mockedRequest, mockedResponse, 1); + assertTrue(response.equals("Success")); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/core/MockEPUser.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/core/MockEPUser.java new file mode 100644 index 00000000..9c220ce6 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/core/MockEPUser.java @@ -0,0 +1,84 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.core; + +import java.util.Date; + +import org.openecomp.portalapp.portal.domain.EPUser; + +public class MockEPUser { + + public EPUser mockEPUser() { + + EPUser ePUser = new EPUser(); + ePUser.setOrgId(null); + ePUser.setManagerId(null); + ePUser.setFirstName("test"); + ePUser.setLastName("test"); + ePUser.setMiddleInitial(null); + ePUser.setPhone(null); + ePUser.setFax(null); + ePUser.setCellular(null); + ePUser.setEmail(null); + ePUser.setAddressId(null); + ePUser.setAlertMethodCd(null); + ePUser.setHrid(null); + ePUser.setOrgUserId("guestT"); + ePUser.setOrgCode(null); + ePUser.setAddress1(null); + ePUser.setAddress2(null); + ePUser.setCity(null); + ePUser.setState(null); + ePUser.setZipCode(null); + ePUser.setCountry(null); + ePUser.setOrgManagerUserId(null); + ePUser.setLocationClli(null); + ePUser.setBusinessCountryCode(null); + ePUser.setBusinessCountryName(null); + ePUser.setBusinessUnit(null); + ePUser.setBusinessUnitName(null); + ePUser.setDepartment(null); + ePUser.setDepartmentName(null); + ePUser.setCompanyCode(null); + ePUser.setCompany(null); + ePUser.setZipCodeSuffix(null); + ePUser.setJobTitle(null); + ePUser.setCommandChain(null); + ePUser.setSiloStatus(null); + ePUser.setCostCenter(null); + ePUser.setFinancialLocCode(null); + + ePUser.setLoginId(null); + ePUser.setLoginPwd(null); + Date date = new Date(); + ePUser.setLastLoginDate(date); + ePUser.setActive(true); + ePUser.setInternal(false); + ePUser.setSelectedProfileId(null); + ePUser.setTimeZoneId(null); + ePUser.setOnline(true); + ePUser.setChatId(null); + ePUser.setUserApps(null); + ePUser.setPseudoRoles(null); + + ePUser.setId((long) -1); + return ePUser; + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/core/PopulateSampleTestData.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/core/PopulateSampleTestData.java new file mode 100644 index 00000000..2458f471 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/core/PopulateSampleTestData.java @@ -0,0 +1,66 @@ +///*- +// * ================================================================================ +// * 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.core; +// +//import java.sql.Connection; +//import java.sql.SQLException; +// +//import javax.sql.DataSource; +// +//import org.junit.Before; +//import org.junit.Test; +//import org.openecomp.portalapp.framework.ApplicationCommonContextTestSuite; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.core.io.ClassPathResource; +//import org.springframework.jdbc.datasource.DataSourceUtils; +//import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +// +//public class PopulateSampleTestData extends ApplicationCommonContextTestSuite { +// +// @Autowired +// DataSource dataSource; +// +// @Before +// public void populateTestData() throws SQLException { +// +// String sql = "PopulateTestData.sql"; +// createConnection(sql); +// } +// +// public void createConnection(String sql) { +// Connection connection = null; +// ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); +// populator.addScript(new ClassPathResource(sql)); +// try { +// connection = DataSourceUtils.getConnection(dataSource); +// populator.populate(connection); +// } finally { +// if (connection != null) { +// DataSourceUtils.releaseConnection(connection, dataSource); +// } +// } +// } +// +// @Test +// public void populateTest() { +// assert (true); +// } +// +//} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/core/RemoveSampleTestData.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/core/RemoveSampleTestData.java new file mode 100644 index 00000000..1e20cd16 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/core/RemoveSampleTestData.java @@ -0,0 +1,65 @@ +///*- +// * ================================================================================ +// * ECOMP Portal +// * ================================================================================ +// * Copyright (C) 2017 AT&T Intellectual Property +// * ================================================================================ +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// * ================================================================================ +// */ +//package org.openecomp.portalapp.portal.core; +// +//import java.sql.Connection; +//import java.sql.SQLException; +// +//import javax.sql.DataSource; +// +//import org.junit.After; +//import org.junit.Test; +//import org.openecomp.portalapp.framework.ApplicationCommonContextTestSuite; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.core.io.ClassPathResource; +//import org.springframework.jdbc.datasource.DataSourceUtils; +//import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; +// +//public class RemoveSampleTestData extends ApplicationCommonContextTestSuite { +// @Autowired +// DataSource dataSource; +// +// public static int count = 0; +// +// @After +// public void removeTestData() throws SQLException { +// String sql = "RemoveTestData.sql"; +// createConnection(sql); +// } +// +// public void createConnection(String sql) { +// Connection connection = null; +// ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); +// populator.addScript(new ClassPathResource(sql)); +// try { +// connection = DataSourceUtils.getConnection(dataSource); +// populator.populate(connection); +// } finally { +// if (connection != null) { +// DataSourceUtils.releaseConnection(connection, dataSource); +// } +// } +// } +// +// @Test +// public void removeTest() { +// assert (true); +// } +//} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/core/RestURLsTestSuite.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/core/RestURLsTestSuite.java new file mode 100644 index 00000000..4ff2b8da --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/core/RestURLsTestSuite.java @@ -0,0 +1,334 @@ +///*- +// * ================================================================================ +// * 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.core; +// +//import static org.junit.Assert.assertEquals; +//import static org.junit.Assert.assertTrue; +// +//import java.io.IOException; +//import java.nio.charset.Charset; +//import java.util.ArrayList; +// +//import org.junit.Assert; +//import org.junit.Test; +//import org.openecomp.portalapp.framework.ApplicationCommonContextTestSuite; +//import org.openecomp.portalapp.portal.domain.EPUser; +//import org.openecomp.portalapp.portal.test.core.MockEPUser; +//import org.openecomp.portalapp.portal.transport.AppNameIdIsAdmin; +//import org.openecomp.portalapp.portal.transport.AppsListWithAdminRole; +//import org.openecomp.portalsdk.core.util.SystemProperties; +//import org.springframework.http.MediaType; +//import org.springframework.test.web.servlet.ResultActions; +//import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +//import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +// +//import com.fasterxml.jackson.annotation.JsonInclude; +//import com.fasterxml.jackson.databind.ObjectMapper; +// +///** +// * +// * Use RestURLsTestSuite to test Rest API URL's +// */ +//public class RestURLsTestSuite extends ApplicationCommonContextTestSuite { +// +// public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), +// MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); +// +// String url = null; +// +// MockEPUser mockUser = new MockEPUser(); +// +// public byte[] convertObjectToJsonBytes(Object object) throws IOException { +// ObjectMapper mapper = new ObjectMapper(); +// mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); +// return mapper.writeValueAsBytes(object); +// } +// +// public void requestBuilder(String url) throws Exception { +// EPUser user = mockUser.mockEPUser(); +// +// MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(url); +// requestBuilder.sessionAttr(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user); +// ResultActions ra = getMockMvc().perform(requestBuilder); +// assertData(ra); +// } +// +// public void assertData(ResultActions ra) { +// Assert.assertEquals("application/json", ra.andReturn().getResponse().getContentType()); +// Assert.assertEquals(200, ra.andReturn().getResponse().getStatus()); +// +// } +// +// @Test +// public void getMenuItemsTest() throws Exception { +// url = "/portalApi/functionalMenu"; +// requestBuilder(url); +// } +// +// @Test +// public void getMenuItemsForNotificationsTest() throws Exception { +// url = "/portalApi/functionalMenuForNotificationTree"; +// requestBuilder(url); +// } +// +// @Test +// public void getUserAppsTestnew() throws Exception { +// url = "/portalApi/userApps"; +// requestBuilder(url); +// } +// +// @Test +// public void getPersUserAppsTest() throws Exception { +// url = "/portalApi/persUserApps"; +// requestBuilder(url); +// } +// +// @Test +// public void getAppCatalogTest() throws Exception { +// url = "/portalApi/appCatalog"; +// requestBuilder(url); +// } +// +// @Test +// public void getAppListNewTest() throws Exception { +// ResultActions ra = getMockMvc() +// .perform(MockMvcRequestBuilders.get("/portalApi/userApplicationRoles").param("userId", "guest")); +// assertData(ra); +// } +// +// @Test +// public void getAvailableAppListTest() throws Exception { +// url = "/portalApi/availableApps"; +// requestBuilder(url); +// } +// +// @Test +// public void getAllAppsTest() throws Exception { +// url = "/portalApi/allAvailableApps"; +// requestBuilder(url); +// } +// +// @Test +// public void getUserProfileTest() throws Exception { +// url = "/portalApi/userProfile"; +// requestBuilder(url); +// } +// +// @Test +// public void getRolesByAppTest() throws Exception { +// EPUser user = mockUser.mockEPUser(); +// MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/portalApi/adminAppsRoles/550"); +// requestBuilder.sessionAttr(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user); +// ResultActions ra = getMockMvc().perform(requestBuilder); +// assertData(ra); +// } +// +// @Test +// public void getAppsWithAdminRoleStateForUserTest() throws Exception { +// url = "/portalApi/adminAppsRoles?user=guest"; +// requestBuilder(url); +// +// } +// +// @Test +// public void getUsersFromAppEndpointTest() throws Exception { +// url = "/portalApi/app/550/users"; +// requestBuilder(url); +// } +// +// @Test +// public void getOnboardingAppsTest() throws Exception { +// url = "/portalApi/onboardingApps"; +// requestBuilder(url); +// } +// +// @Test +// public void getMenuItemsForAuthUserTest() throws Exception { +// url = "/portalApi/functionalMenuForAuthUser"; +// requestBuilder(url); +// } +// +// @Test +// public void getMenuItemsForEditingTest() throws Exception { +// url = "/portalApi/functionalMenuForEditing"; +// requestBuilder(url); +// } +// +// @Test +// public void getAppRolesTest() throws Exception { +// url = "/portalApi/appRoles/455"; +// requestBuilder(url); +// } +// +// @Test +// public void regenerateAncestorTableTest() throws Exception { +// +// EPUser user = mockUser.mockEPUser(); +// +// MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders +// .get("/portalApi/regenerateFunctionalMenuAncestors"); +// requestBuilder.sessionAttr(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user); +// ResultActions ra = getMockMvc().perform(requestBuilder); +// assertEquals("application/json;charset=UTF-8", ra.andReturn().getResponse().getContentType()); +// Assert.assertEquals(200, ra.andReturn().getResponse().getStatus()); +// +// } +// +// @Test +// public void getAppListTest() throws Exception { +// url = "/portalApi/getAppList"; +// requestBuilder(url); +// } +// +// @Test +// public void getFavoritesForUserTest() throws Exception { +// url = "/portalApi/getFavoriteItems"; +// requestBuilder(url); +// } +// +// @Test +// public void getManifestTest() throws Exception { +// url = "/portalApi/manifest"; +// requestBuilder(url); +// } +// +// @Test +// public void getActiveUsersTest() throws Exception { +// url = "/portalApi/dashboard/activeUsers"; +// requestBuilder(url); +// } +// +// @Test +// public void searchPortalTest() throws Exception { +// EPUser user = mockUser.mockEPUser(); +// MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/portalApi/dashboard/search") +// .param("searchString", "guest"); +// requestBuilder.sessionAttr(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user); +// ResultActions ra = getMockMvc().perform(requestBuilder); +// assertData(ra); +// } +// +// @Test +// public void getWidgetDataTest() throws Exception { +// EPUser user = mockUser.mockEPUser(); +// MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/portalApi/dashboard/widgetData") +// .param("resourceType", "guest"); +// requestBuilder.sessionAttr(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user); +// ResultActions ra = getMockMvc().perform(requestBuilder); +// assertData(ra); +// } +// +// @Test +// public void getAppsAndContactsTest() throws Exception { +// url = "/portalApi/contactus/allapps"; +// requestBuilder(url); +// } +// +// @Test +// public void getPortalDetailsTest() throws Exception { +// url = "/portalApi/contactus/feedback"; +// requestBuilder(url); +// } +// +// @Test +// public void getAppCategoryFunctionsTest() throws Exception { +// url = "/portalApi/contactus/functions"; +// requestBuilder(url); +// } +// +// @Test +// public void getOnlineUserUpdateRateTest() throws Exception { +// url = "/portalApi/dashboard/onlineUserUpdateRate"; +// requestBuilder(url); +// } +// +// @Test +// public void getMenuIdRoleIdTest() throws Exception { +// url = "/portalApi/getFunctionalMenuRole"; +// requestBuilder(url); +// } +// +// @Test +// public void getNotificationsTest() throws Exception { +// url = "/portalApi/getNotifications"; +// requestBuilder(url); +// } +// +// @Test +// public void getAdminNotificationsTest() throws Exception { +// url = "/portalApi/getAdminNotifications"; +// requestBuilder(url); +// } +// +// @Test +// public void getNotificationAppRolesTest() throws Exception { +// url = "/portalApi/getNotificationAppRoles"; +// requestBuilder(url); +// } +// +// @Test +// public void getNotificationUpdateRateTest() throws Exception { +// url = "/portalApi/notificationUpdateRate"; +// requestBuilder(url); +// } +// +// @Test +// public void notificationReadTest() throws Exception { +// url = "/portalApi/notificationRead?notificationId=262"; +// requestBuilder(url); +// } +// +// @Test +// public void testGetRolesTest() throws Exception { +// url = "/portalApi/notificationRole/248/roles"; +// requestBuilder(url); +// } +// +// @Test +// public void putAppsWithAdminRoleStateForUserTest() throws Exception { +// +// AppsListWithAdminRole appsListWithAdminRole = new AppsListWithAdminRole(); +// appsListWithAdminRole.setOrgUserId("guest"); +// ArrayList<AppNameIdIsAdmin> appsRoles = new ArrayList<AppNameIdIsAdmin>(); +// AppNameIdIsAdmin appNameIdIsAdmin = new AppNameIdIsAdmin(); +// appNameIdIsAdmin.setId((long) 455); +// appNameIdIsAdmin.setAppName("CCD"); +// appNameIdIsAdmin.setIsAdmin(true); +// appNameIdIsAdmin.setRestrictedApp(false); +// appsRoles.add(appNameIdIsAdmin); +// appsListWithAdminRole.setAppsRoles(appsRoles); +// EPUser user = mockUser.mockEPUser(); +// MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.put("/portalApi/adminAppsRoles") +// .contentType(APPLICATION_JSON_UTF8).content(convertObjectToJsonBytes(appsListWithAdminRole)); +// +// requestBuilder.sessionAttr(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user); +// ResultActions ra = getMockMvc().perform(requestBuilder); +// assertData(ra); +// } +// +// @Test +// public void ticketEventControllerForExternalSystem() throws Exception { +// String ticketEventJson = "{\"application\": \"cbus\",\"event\": {\"body\": {\"ticketStatePhrase\": \"We recently detected a problem with the equipment at your site. The event is in queue for immediate work.\", \"ivrNotificationFlag\": \"1\",\"expectedRestoreDate\": 0,\"bridgeTransport\": \"AOTS\", \"reptRequestType\": 0,\"ticketNum\": \"000002000857405\",\"assetID\": \"CISCO_1921C1_ISR_G2\", \"eventDate\": 1490545134601,\"eventAbstract\": \"ospfIfConfigError trap received from Cisco_1921c1_ISR_G2 with arguments: ospfRouterId=Cisco_1921c1_ISR_G2; ospfIfIpAddress=1921c1_288266; ospfAddressLessIf=0; ospfPacketSrc=172.17.0.11; ospfConfigErrorType=2; ospfPacketType=1\",\"severity\": \"2 - Major\",\"ticketPriority\": \"3\",\"reportedCustomerImpact\": 0,\"testAutoIndicator\": 0,\"supportGroupName\": \"US-TEST-ORT\",\"lastModifiedDate\": \"1487687703\",\"messageGroup\": \"SNMP\",\"csi\": 0,\"mfabRestoredTime\": 0},\"header\": {\"timestamp\": \"2017-02-21T14:35:05.219+0000\",\"eventSource\": \"aotstm\",\"entityId\": \"000002000857405\", \"sequenceNumber\": 2 },\"blinkMsgId\": \"f38c071e-1a47-4b55-9e72-1db830100a61\",\"sourceIP\": \"130.4.165.158\"},\"SubscriberInfo\": {\"UserList\": [\"hk8777\"] }}"; +// MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/auxapi/ticketevent") +// .contentType(APPLICATION_JSON_UTF8).content(ticketEventJson); +// ResultActions ra = getMockMvc().perform(requestBuilder); +// assertTrue(ra.andReturn().getResponse().getContentType().contains("application/json")); +// } +//} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/AdminUserAppTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/AdminUserAppTest.java new file mode 100644 index 00000000..8e56a770 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/AdminUserAppTest.java @@ -0,0 +1,36 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.AdminUserApp; + +public class AdminUserAppTest { + + public AdminUserApp mockAdminUserApp(){ + + AdminUserApp adminUserApp = new AdminUserApp(); + + adminUserApp.setUserId((long)1); + adminUserApp.setFirstName("test"); + adminUserApp.setLastName("test"); + adminUserApp.setOrgUserId("test"); + adminUserApp.setAppId((long)1); + adminUserApp.setAppName("test"); + + return adminUserApp; + } + + @Test + public void adminUserAppTest(){ + AdminUserApp adminUserApp = mockAdminUserApp(); + + assertEquals(adminUserApp.getUser_Id(), new Long(1)); + assertEquals(adminUserApp.getFirstName(), "test"); + assertEquals(adminUserApp.getLastName(), "test"); + assertEquals(adminUserApp.getOrgUserId(), "test"); + assertEquals(adminUserApp.getAppName(), "test"); + assertEquals(adminUserApp.getAppId(), new Long(1)); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/AdminUserApplicationsTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/AdminUserApplicationsTest.java new file mode 100644 index 00000000..2c3c9303 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/AdminUserApplicationsTest.java @@ -0,0 +1,57 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import javax.persistence.Column; +import javax.persistence.Id; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.AdminUserApp; +import org.openecomp.portalapp.portal.domain.AdminUserApplications; + +public class AdminUserApplicationsTest { + + public AdminUserApplications mockAdminUserApplications(){ + + AdminUserApp adminUserApp = new AdminUserApp(); + + adminUserApp.setUserId((long)1); + adminUserApp.setFirstName("test"); + adminUserApp.setLastName("test"); + adminUserApp.setOrgUserId("test"); + adminUserApp.setAppId((long)1); + adminUserApp.setAppName("test"); + + AdminUserApplications adminUserApplications = new AdminUserApplications(adminUserApp); + + adminUserApplications.setUser_Id((long)1); + adminUserApplications.setFirstName("test"); + adminUserApplications.setLastName("test"); + adminUserApplications.setOrgUserId("test"); + return adminUserApplications; + } + + @Test + public void adminUserAppTest(){ + AdminUserApplications adminUserApplications = mockAdminUserApplications(); + AdminUserApp adminUserApp = new AdminUserApp(); + + adminUserApp.setUserId((long)1); + adminUserApp.setFirstName("test"); + adminUserApp.setLastName("test"); + adminUserApp.setOrgUserId("test"); + adminUserApp.setAppId((long)1); + adminUserApp.setAppName("test"); + AdminUserApplications adminUserApplications1 = new AdminUserApplications(adminUserApp); + + assertEquals(adminUserApplications.getUser_Id(), new Long(1)); + assertEquals(adminUserApplications.getFirstName(), "test"); + assertEquals(adminUserApplications.getLastName(), "test"); + assertEquals(adminUserApplications.getOrgUserId(), "test"); + + + assertEquals(adminUserApplications1.getApps().get(0).getAppId(),adminUserApp.getAppId()); + assertEquals(adminUserApplications1.getApps().get(0).getAppName(),adminUserApp.getAppName()); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/AppContactUsTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/AppContactUsTest.java new file mode 100644 index 00000000..474434d1 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/AppContactUsTest.java @@ -0,0 +1,32 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.AppContactUs; + +public class AppContactUsTest { + + public AppContactUs mockAppContactUs(){ + AppContactUs appContactUs = new AppContactUs(); + appContactUs.setDescription("test"); + appContactUs.setContactEmail("test"); + appContactUs.setContactName("test"); + appContactUs.setUrl("test"); + appContactUs.setActiveYN("test"); + + return appContactUs; + } + + @Test + public void mockAppContactUsTest(){ + AppContactUs appContactUs = mockAppContactUs(); + + assertEquals(appContactUs.getDescription(), "test"); + assertEquals(appContactUs.getContactEmail(), "test"); + assertEquals(appContactUs.getContactName(), "test"); + assertEquals(appContactUs.getUrl(), "test"); + assertEquals(appContactUs.getActiveYN(), "test"); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/CentralRoleFunctionTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/CentralRoleFunctionTest.java new file mode 100644 index 00000000..4c05160d --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/CentralRoleFunctionTest.java @@ -0,0 +1,31 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.CentralRoleFunction; + +public class CentralRoleFunctionTest { + + public CentralRoleFunction mockCentralRoleFunction(){ + + CentralRoleFunction centralRoleFunction = new CentralRoleFunction(); + + centralRoleFunction.setCode("test"); + centralRoleFunction.setName("test"); + centralRoleFunction.setAppId((long)1); + centralRoleFunction.setEditUrl("test"); + + return centralRoleFunction; + } + + @Test + public void centralRoleFunctionTest(){ + CentralRoleFunction centralRoleFunction = mockCentralRoleFunction(); + + assertEquals(centralRoleFunction.getAppId(), new Long(1)); + assertEquals(centralRoleFunction.getCode(), "test"); + assertEquals(centralRoleFunction.getName(), "test"); + assertEquals(centralRoleFunction.getEditUrl(), "test"); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPAppRoleFunctionTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPAppRoleFunctionTest.java new file mode 100644 index 00000000..864b6aa6 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPAppRoleFunctionTest.java @@ -0,0 +1,27 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.EPAppRoleFunction; + +public class EPAppRoleFunctionTest { + + public EPAppRoleFunction mockEPAppRoleFunction(){ + EPAppRoleFunction epAppRoleFunction = new EPAppRoleFunction(); + epAppRoleFunction.setRoleId((long)1); + epAppRoleFunction.setAppId((long)1); + epAppRoleFunction.setCode("test"); + + return epAppRoleFunction; + } + + @Test + public void epAppRoleFunctionTest(){ + EPAppRoleFunction epAppRoleFunction = mockEPAppRoleFunction(); + + assertEquals(epAppRoleFunction.getRoleId(), new Long(1)); + assertEquals(epAppRoleFunction.getAppId(), new Long(1)); + assertEquals(epAppRoleFunction.getCode(), "test"); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPAppTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPAppTest.java new file mode 100644 index 00000000..eb92b889 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPAppTest.java @@ -0,0 +1,61 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.EPApp; + +public class EPAppTest { + + public EPApp mockEPApp(){ + EPApp epApp = new EPApp(); + + epApp.setName("test"); + epApp.setImageUrl("test"); + epApp.setDescription("test"); + epApp.setNotes("test"); + epApp.setUrl("test"); + epApp.setAlternateUrl("test"); + epApp.setAppRestEndpoint("test"); + epApp.setMlAppName("test"); + epApp.setMlAppAdminId("test"); + epApp.setMotsId((long)1); + epApp.setUsername("test"); + epApp.setAppPassword("test"); + epApp.setOpen(false); + epApp.setEnabled(false); + epApp.setUebTopicName("test"); + epApp.setUebSecret("test"); + epApp.setAppType(1); + epApp.setCentralAuth(false); + epApp.setNameSpace("test"); + + return epApp; + } + + @Test + public void epAppTest(){ + EPApp epApp = mockEPApp(); + + assertEquals(epApp.getName(), "test"); + assertEquals(epApp.getImageUrl(), "test"); + assertEquals(epApp.getDescription(), "test"); + assertEquals(epApp.getNotes(), "test"); + assertEquals(epApp.getUrl(), "test"); + assertEquals(epApp.getAlternateUrl(), "test"); + assertEquals(epApp.getAppRestEndpoint(), "test"); + assertEquals(epApp.getMlAppName(), "test"); + assertEquals(epApp.getMlAppAdminId(), "test"); + assertEquals(epApp.getMotsId(), new Long(1)); + assertEquals(epApp.getUsername(), "test"); + assertEquals(epApp.getAppPassword(), "test"); + assertEquals(epApp.getOpen(), false); + assertEquals(epApp.getEnabled(), false); + assertEquals(epApp.getUebTopicName(), "test"); + assertEquals(epApp.getUebSecret(), "test"); + assertEquals(epApp.getAppType(), Integer.valueOf(1)); + assertEquals(epApp.getCentralAuth(), false); + assertEquals(epApp.getNameSpace(), "test"); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPEndpointAccountTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPEndpointAccountTest.java new file mode 100644 index 00000000..c19ecf8b --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPEndpointAccountTest.java @@ -0,0 +1,29 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.EPEndpointAccount; + +public class EPEndpointAccountTest { + + public EPEndpointAccount mockEPEndpointAccount(){ + EPEndpointAccount epEndpointAccount = new EPEndpointAccount(); + + epEndpointAccount.setEp_id((long)1); + epEndpointAccount.setAccount_id((long)1); + epEndpointAccount.setId((long)1); + + return epEndpointAccount; + } + + @Test + public void epEndpointAccount(){ + EPEndpointAccount epEndpointAccount = mockEPEndpointAccount(); + assertEquals(epEndpointAccount.getEp_id(), new Long(1)); + assertEquals(epEndpointAccount.getAccount_id(), new Long(1)); + assertEquals(epEndpointAccount.getId(), new Long(1)); + + assertEquals(epEndpointAccount.toString(), "EPEndpointAccount [id=1, ep_id=1, account_id=1]"); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPEndpointTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPEndpointTest.java new file mode 100644 index 00000000..45184de4 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPEndpointTest.java @@ -0,0 +1,27 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.EPEndpoint; + +public class EPEndpointTest { + + public EPEndpoint mockEPEndpoint(){ + EPEndpoint epEndpoint = new EPEndpoint(); + + epEndpoint.setId((long)1); + epEndpoint.setName("test"); + + return epEndpoint; + } + + @Test + public void epEndpointTest(){ + EPEndpoint epEndpoint = mockEPEndpoint(); + + assertEquals(epEndpoint.getId(), new Long(1)); + assertEquals(epEndpoint.getName(), "test"); + assertEquals("EPEndpoint [id=1, name=test]", epEndpoint.toString()); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPRoleTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPRoleTest.java new file mode 100644 index 00000000..830eaa5b --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPRoleTest.java @@ -0,0 +1,36 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.EPRole; + +public class EPRoleTest { + + public EPRole mockEPRole(){ + EPRole epRole = new EPRole(); + + epRole.setName("test"); + epRole.setActive(false); + epRole.setPriority(1); + epRole.setAppId((long)1); + epRole.setAppRoleId((long)1); + + return epRole; + } + + @Test + public void epRoleTest(){ + EPRole epRole = mockEPRole(); + + assertEquals(epRole.getName(), "test"); + assertEquals(epRole.getActive(), false); + assertEquals(epRole.getPriority().toString(),"1"); + assertEquals(epRole.getAppId(), new Long(1)); + assertEquals(epRole.getAppRoleId(), new Long(1)); + + assertEquals(epRole.toString(), "[Id = null, name = test]"); + + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserAppCatalogRolesTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserAppCatalogRolesTest.java new file mode 100644 index 00000000..40bb16c1 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserAppCatalogRolesTest.java @@ -0,0 +1,32 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.EPUserAppCatalogRoles; + +public class EPUserAppCatalogRolesTest { + + public EPUserAppCatalogRoles mockEPUserAppCatalogRoles(){ + EPUserAppCatalogRoles epUserAppCatalogRoles = new EPUserAppCatalogRoles(); + + epUserAppCatalogRoles.setRequestedRoleId((long)1); + epUserAppCatalogRoles.setRolename("test"); + epUserAppCatalogRoles.setRequestStatus("status"); + epUserAppCatalogRoles.setAppId((long)1); + + return epUserAppCatalogRoles; + } + + @Test + public void epUserAppCatalogRolesTest(){ + EPUserAppCatalogRoles epUserAppCatalogRoles = mockEPUserAppCatalogRoles(); + + assertEquals(epUserAppCatalogRoles.getRequestedRoleId(), new Long(1)); + assertEquals(epUserAppCatalogRoles.getRolename(), "test"); + assertEquals(epUserAppCatalogRoles.getRequestStatus(), "status"); + assertEquals(epUserAppCatalogRoles.getAppId(), new Long(1)); + + assertEquals("EPUserAppCatalogRoles [requestedRoleId=1, rolename=test, requestStatus=status, appId=1]", epUserAppCatalogRoles.toString()); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesRequestDetailTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesRequestDetailTest.java new file mode 100644 index 00000000..fec58dbf --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesRequestDetailTest.java @@ -0,0 +1,54 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import java.util.Date; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequest; +import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequestDetail; + +public class EPUserAppRolesRequestDetailTest { + + public EPUserAppRolesRequestDetail mockEPUserAppRolesRequestDetail(){ + + EPUserAppRolesRequest epUserAppRolesRequest = new EPUserAppRolesRequest(); + epUserAppRolesRequest.setUserId((long)1); + epUserAppRolesRequest.setAppId((long)1); + epUserAppRolesRequest.setCreated(new Date()); + epUserAppRolesRequest.setUpdatedDate(new Date()); + epUserAppRolesRequest.setRequestStatus("test"); + + EPUserAppRolesRequestDetail epUserAppRolesRequestDetail = new EPUserAppRolesRequestDetail(); + epUserAppRolesRequestDetail.setReqRoleId((long)1); + epUserAppRolesRequestDetail.setReqType("test"); + epUserAppRolesRequestDetail.setEpRequestIdData(epUserAppRolesRequest); + + return epUserAppRolesRequestDetail; + } + + @Test + public void epUserAppRolesRequestDetailTest(){ + + EPUserAppRolesRequest epUserAppRolesRequest = new EPUserAppRolesRequest(); + epUserAppRolesRequest.setUserId((long)1); + epUserAppRolesRequest.setAppId((long)1); + epUserAppRolesRequest.setCreated(new Date()); + epUserAppRolesRequest.setUpdatedDate(new Date()); + epUserAppRolesRequest.setRequestStatus("test"); + + EPUserAppRolesRequestDetail epUserAppRolesRequestDetail = mockEPUserAppRolesRequestDetail(); + + EPUserAppRolesRequestDetail epUserAppRolesRequestDetail1 = new EPUserAppRolesRequestDetail(); + epUserAppRolesRequestDetail1.setReqRoleId((long)1); + epUserAppRolesRequestDetail1.setReqType("test"); + epUserAppRolesRequestDetail1.setEpRequestIdData(epUserAppRolesRequest); + + assertEquals(epUserAppRolesRequestDetail.getReqRoleId(), new Long(1)); + assertEquals(epUserAppRolesRequestDetail.getReqType(), "test"); + assertEquals(epUserAppRolesRequestDetail.getEpRequestIdData(), epUserAppRolesRequest); +// assertEquals(epUserAppRolesRequestDetail.hashCode(), epUserAppRolesRequestDetail1.hashCode()); + + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesTest.java new file mode 100644 index 00000000..b13ae14a --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserAppRolesTest.java @@ -0,0 +1,28 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.EPUserAppRoles; + +public class EPUserAppRolesTest { + + public EPUserAppRoles mockEPUserAppRoles(){ + EPUserAppRoles epUserAppRoles = new EPUserAppRoles(); + + epUserAppRoles.setRoleId((long)1); + epUserAppRoles.setAppId((long)1); + + return epUserAppRoles; + } + + @Test + public void epUserAppRolesTest(){ + EPUserAppRoles epUserAppRoles = mockEPUserAppRoles(); + + assertEquals(epUserAppRoles.getRoleId(), new Long(1)); + assertEquals(epUserAppRoles.getAppId(), new Long(1)); + assertEquals("EpUserAppRoles [roleId=1, appId=1]", epUserAppRoles.toString()); + } +} + diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserAppTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserAppTest.java new file mode 100644 index 00000000..0de0b590 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserAppTest.java @@ -0,0 +1,85 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.domain.EPUserApp; + +public class EPUserAppTest { + + public EPUserApp mockEPUserApp(){ + + EPApp epApp = new EPApp(); + epApp.setName("test"); + epApp.setImageUrl("test"); + epApp.setDescription("test"); + epApp.setNotes("test"); + epApp.setUrl("test"); + epApp.setAlternateUrl("test"); + epApp.setAppRestEndpoint("test"); + epApp.setMlAppName("test"); + epApp.setMlAppAdminId("test"); + epApp.setMotsId((long)1); + epApp.setUsername("test"); + epApp.setAppPassword("test"); + + + //Role + EPRole epRole = new EPRole(); + epRole.setName("test"); + epRole.setActive(false); + epRole.setPriority(1); + epRole.setAppId((long)1); + epRole.setAppRoleId((long)1); + + EPUserApp user = new EPUserApp(); + user.setUserId((long)1); + user.setApp(epApp); + user.setRole(epRole); + user.setPriority((short)32767); + + + return user; + } + + @Test + public void userTest(){ + EPUserApp user = mockEPUserApp(); + + EPApp epApp = new EPApp(); + epApp.setName("test"); + epApp.setImageUrl("test"); + epApp.setDescription("test"); + epApp.setNotes("test"); + epApp.setUrl("test"); + epApp.setAlternateUrl("test"); + epApp.setAppRestEndpoint("test"); + epApp.setMlAppName("test"); + epApp.setMlAppAdminId("test"); + epApp.setMotsId((long)1); + epApp.setUsername("test"); + epApp.setAppPassword("test"); + user.setApp(epApp); + + //Role + EPRole epRole = new EPRole(); + epRole.setName("test"); + epRole.setActive(false); + epRole.setPriority(1); + epRole.setAppId((long)1); + epRole.setAppRoleId((long)1); + + + assertEquals(user.getUserId(),Long.valueOf(1)); + assertEquals(user.getApp(), epApp); + assertEquals(user.getPriority().getClass(), Short.class); + + assertEquals(user.toString(), "[u: 1; a: null, r: null; appRoleId: 1]"); + + assertEquals(user.hashCode(), user.hashCode()); + + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserAppsManualSortPreferenceTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserAppsManualSortPreferenceTest.java new file mode 100644 index 00000000..0f4bb62e --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserAppsManualSortPreferenceTest.java @@ -0,0 +1,29 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.EPUserAppsManualSortPreference; + +public class EPUserAppsManualSortPreferenceTest { + + public EPUserAppsManualSortPreference mockEPUserAppsManualSortPreference(){ + + EPUserAppsManualSortPreference epUserAppsManualSortPreference = new EPUserAppsManualSortPreference(); + epUserAppsManualSortPreference.setUserId(1); + epUserAppsManualSortPreference.setAppId((long)1); + epUserAppsManualSortPreference.setAppManualSortOrder(1); + + return epUserAppsManualSortPreference; + } + + @Test + public void epUserAppsManualSortPreferenceTest(){ + + EPUserAppsManualSortPreference epUserAppsManualSortPreference = mockEPUserAppsManualSortPreference(); + + assertEquals(epUserAppsManualSortPreference.getUserId(), 1); + assertEquals(epUserAppsManualSortPreference.getAppId(), new Long(1)); + assertEquals(epUserAppsManualSortPreference.getAppManualSortOrder(), 1); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserAppsSortPreferenceTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserAppsSortPreferenceTest.java new file mode 100644 index 00000000..4f70ea78 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserAppsSortPreferenceTest.java @@ -0,0 +1,43 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import java.util.Date; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.EPUserAppsSortPreference; + +public class EPUserAppsSortPreferenceTest { + + public EPUserAppsSortPreference mockEPUserAppsSortPreferenceTest(){ + + EPUserAppsSortPreference epUserAppsSortPreference = new EPUserAppsSortPreference(); + epUserAppsSortPreference.setUserId(1); + epUserAppsSortPreference.setSortPref("test"); + epUserAppsSortPreference.setId((long)1); + epUserAppsSortPreference.setCreated(new Date()); + epUserAppsSortPreference.setModified(new Date()); + epUserAppsSortPreference.setModifiedId((long)1); + epUserAppsSortPreference.setRowNum((long)1); + epUserAppsSortPreference.setAuditTrail(null); + + return epUserAppsSortPreference; + } + + @Test + public void epUserAppsSortPreferenceTest() { + EPUserAppsSortPreference epUserAppsSortPreference = mockEPUserAppsSortPreferenceTest(); + + assertEquals(epUserAppsSortPreference.getUserId(), 1); + assertEquals(epUserAppsSortPreference.getSortPref(), "test"); + assertEquals(epUserAppsSortPreference.getId(), new Long(1)); +// assertEquals(epUserAppsSortPreference.getCreated(), new Date()); +// assertEquals(epUserAppsSortPreference.getModified(), new Date()); + assertEquals(epUserAppsSortPreference.getModifiedId(), new Long(1)); + assertEquals(epUserAppsSortPreference.getRowNum(), new Long(1)); + assertEquals(epUserAppsSortPreference.getAuditTrail(), null); + + + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserNotificationTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserNotificationTest.java new file mode 100644 index 00000000..e896d081 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserNotificationTest.java @@ -0,0 +1,34 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import java.util.Date; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.EPUserNotification; + +public class EPUserNotificationTest { + + public EPUserNotification mockEPUserNotification(){ + + EPUserNotification epUserNotification = new EPUserNotification(); + + epUserNotification.setUserId((long)1); + epUserNotification.setNotificationId((long)1); + epUserNotification.setViewed("test"); + epUserNotification.setUpdateTime(new Date()); + + return epUserNotification; + } + + @Test + public void epUserNotificationTest(){ + EPUserNotification epUserNotification = mockEPUserNotification(); + + assertEquals(epUserNotification.getUserId(), new Long(1)); + assertEquals(epUserNotification.getNotificationId(), new Long(1)); + assertEquals(epUserNotification.getViewed(), "test"); + // assertEquals(epUserNotification.getUpdateTime(), new Date()); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserTest.java new file mode 100644 index 00000000..98065a2b --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPUserTest.java @@ -0,0 +1,114 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import java.util.Date; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.EPUser; + +public class EPUserTest { + + public EPUser mockEPUser(){ + + EPUser epUser = new EPUser(); + + epUser.setId((long)1); + epUser.setManagerId((long) 1234); + epUser.setFirstName("test"); + epUser.setLastName("test"); + epUser.setMiddleInitial("test"); + epUser.setPhone("test"); + epUser.setFax("test"); + epUser.setCellular("test"); + epUser.setEmail("test"); + epUser.setAddressId((long) 123); + epUser.setAlertMethodCd("test"); + epUser.setHrid("test"); + epUser.setOrgUserId("test"); + epUser.setOrgCode("test"); + epUser.setAddress1("test"); + epUser.setAddress2("test"); + epUser.setCity("test"); + epUser.setState("test"); + epUser.setZipCode("test"); + epUser.setCountry("test"); + epUser.setOrgManagerUserId("test"); + epUser.setLocationClli("test"); + epUser.setBusinessCountryCode("test"); + epUser.setBusinessCountryName("test"); + epUser.setBusinessUnit("test"); + epUser.setBusinessUnitName("test"); + epUser.setDepartment("test"); + epUser.setDepartmentName("test"); + epUser.setCompanyCode("test"); + epUser.setCompany("test"); + epUser.setZipCodeSuffix("test"); + epUser.setJobTitle("test"); + epUser.setCommandChain("test"); + epUser.setSiloStatus("test"); + epUser.setCostCenter("test"); + epUser.setFinancialLocCode("test"); + epUser.setLoginId("test"); + epUser.setLoginPwd("test"); + epUser.setLastLoginDate(new Date()); + epUser.setActive(false); + epUser.setInternal(false); + epUser.setSelectedProfileId((long) 12345); + epUser.setTimeZoneId((long) 12345); + epUser.setOnline(false); + epUser.setChatId("test"); + return epUser; + + } + + @Test + public void userTest(){ + EPUser user = mockEPUser(); + + assertEquals(user.getId(), new Long(1)); + assertEquals(user.getManagerId(), new Long(1234)); + assertEquals(user.getFirstName(), "test"); + assertEquals(user.getLastName(), "test"); + assertEquals(user.getMiddleInitial(), "test"); + assertEquals(user.getPhone(), "test"); + assertEquals(user.getFax(), "test"); + assertEquals(user.getCellular(), "test"); + assertEquals(user.getEmail(), "test"); + assertEquals(user.getAddressId(), new Long(123) ); + assertEquals(user.getAlertMethodCd(), "test"); + assertEquals(user.getHrid(), "test"); + assertEquals(user.getOrgUserId(), "test"); + assertEquals(user.getOrgCode(), "test"); + assertEquals(user.getAddress1(), "test"); + assertEquals(user.getAddress2(), "test"); + assertEquals(user.getState(), "test"); + assertEquals(user.getZipCode(), "test"); + assertEquals(user.getCountry(), "test"); + assertEquals(user.getOrgManagerUserId(), "test"); + assertEquals(user.getLocationClli(), "test"); + assertEquals(user.getBusinessCountryCode(), "test"); + assertEquals(user.getBusinessCountryName(), "test"); + assertEquals(user.getBusinessUnit(), "test"); + assertEquals(user.getBusinessUnitName(), "test"); + assertEquals(user.getDepartment(), "test"); + assertEquals(user.getDepartmentName(), "test"); + assertEquals(user.getCompanyCode(), "test"); + assertEquals(user.getCompany(), "test"); + assertEquals(user.getZipCodeSuffix(), "test"); + assertEquals(user.getJobTitle(), "test"); + assertEquals(user.getCommandChain(), "test"); + assertEquals(user.getSiloStatus(), "test"); + assertEquals(user.getFinancialLocCode(), "test"); + assertEquals(user.getLoginId(), "test"); + assertEquals(user.getLoginPwd(), "test"); + assertEquals(user.getActive(), false); + assertEquals(user.getInternal(), false); + assertEquals(user.getSelectedProfileId(), new Long (12345)); + assertEquals(user.getTimeZoneId(), new Long (12345)); + assertEquals(user.getChatId(), "test"); + + //assertEquals(user.toString(), "EPUser [orgId=null, managerId=1234, firstName=test, middleInitial=test, lastName=test, phone=test, fax=test, cellular=test, email=test, addressId=123, alertMethodCd=test, hrid=test, orgUserId=test, orgCode=test, address1=test, address2=test, city=test, state=test, zipCode=test, country=test, orgManagerUserId=test, locationClli=test, businessCountryCode=test, businessCountryName=test, businessUnit=test, businessUnitName=test, department=test, departmentName=test, companyCode=test, company=test, zipCodeSuffix=test, jobTitle=test, commandChain=test, siloStatus=test, costCenter=test, financialLocCode=test, loginId=test, loginPwd=test, lastLoginDate=Tue Sep 05 11:04:49 EDT 2017, active=false, internal=false, selectedProfileId=12345, timeZoneId=12345, online=false, chatId=test, isGuest=false, userApps=[], pseudoRoles=[]]"); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPWidgetsManualSortPreferenceTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPWidgetsManualSortPreferenceTest.java new file mode 100644 index 00000000..fd7cb76f --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EPWidgetsManualSortPreferenceTest.java @@ -0,0 +1,36 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.EPWidgetsManualSortPreference; + +public class EPWidgetsManualSortPreferenceTest { + + public EPWidgetsManualSortPreference mockEPWidgetsManualSortPreference(){ + EPWidgetsManualSortPreference epWidgetsManualSortPreference = new EPWidgetsManualSortPreference(); + + epWidgetsManualSortPreference.setUserId(1); + epWidgetsManualSortPreference.setWidgetId((long)1); + epWidgetsManualSortPreference.setWidgetRow(1); + epWidgetsManualSortPreference.setWidgetCol(1); + epWidgetsManualSortPreference.setWidgetWidth(1); + epWidgetsManualSortPreference.setWidgetHeight(1); + + return epWidgetsManualSortPreference; + } + + @Test + public void epWidgetsManualSortPreferenceTest(){ + EPWidgetsManualSortPreference epWidgetsManualSortPreference = mockEPWidgetsManualSortPreference(); + + assertEquals(epWidgetsManualSortPreference.getWidgetId(), new Long(1)); + assertEquals(epWidgetsManualSortPreference.getUserId(), 1); + assertEquals(epWidgetsManualSortPreference.getWidgetRow(), 1); + assertEquals(epWidgetsManualSortPreference.getWidgetCol(), 1); + assertEquals(epWidgetsManualSortPreference.getWidgetHeight(), 1); + assertEquals(epWidgetsManualSortPreference.getWidgetWidth(), 1); + + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EcompAppRoleIdTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EcompAppRoleIdTest.java new file mode 100644 index 00000000..bca8c491 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EcompAppRoleIdTest.java @@ -0,0 +1,33 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.EcompAppRoleId; + +public class EcompAppRoleIdTest { + + public EcompAppRoleId mockEcompAppRoleId(){ + + EcompAppRoleId ecompAppRoleId = new EcompAppRoleId(); + + ecompAppRoleId.setAppId((long)1); + ecompAppRoleId.setAppName("test"); + ecompAppRoleId.setRoleId(1); + ecompAppRoleId.setRoleName("test"); + + return ecompAppRoleId; + } + + @Test + public void ecompAppRoleIdTest(){ + + EcompAppRoleId ecompAppRoleId = mockEcompAppRoleId(); + + assertEquals(ecompAppRoleId.getAppId(), new Long(1)); + assertEquals(ecompAppRoleId.getAppName(), "test"); + assertEquals(ecompAppRoleId.getRoleId().toString(), "1"); + assertEquals(ecompAppRoleId.getRoleName(), "test"); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EcompAppRoleTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EcompAppRoleTest.java new file mode 100644 index 00000000..fc2c7b07 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/EcompAppRoleTest.java @@ -0,0 +1,31 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.EcompAppRole; + +public class EcompAppRoleTest { + + public EcompAppRole mockEcompAppRole(){ + EcompAppRole ecompAppRole = new EcompAppRole(); + + ecompAppRole.setAppId((long)1); + ecompAppRole.setAppName("test"); + ecompAppRole.setRoleId(1); + ecompAppRole.setRoleName("test"); + + return ecompAppRole; + } + + @Test + public void ecompAppRoleTest(){ + EcompAppRole ecompAppRole = mockEcompAppRole(); + + assertEquals(ecompAppRole.getAppId(), new Long(1)); + assertEquals(ecompAppRole.getAppName(), "test"); + assertEquals(ecompAppRole.getRoleId().toString(), "1"); + assertEquals(ecompAppRole.getRoleName(), "test"); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/ExternalRoleDetailsTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/ExternalRoleDetailsTest.java new file mode 100644 index 00000000..5d62d34e --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/ExternalRoleDetailsTest.java @@ -0,0 +1,59 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.EPAppRoleFunction; +import org.openecomp.portalapp.portal.domain.ExternalRoleDetails; + +public class ExternalRoleDetailsTest { + + public ExternalRoleDetails mockExternalRoleDetails(){ + + List<EPAppRoleFunction> epAppRoleFunctionList = new ArrayList<EPAppRoleFunction>(); + + EPAppRoleFunction epAppRoleFunction = new EPAppRoleFunction(); + epAppRoleFunction.setRoleId((long)1); + epAppRoleFunction.setAppId((long)1); + epAppRoleFunction.setCode("test"); + + epAppRoleFunctionList.add(epAppRoleFunction); + + ExternalRoleDetails externalRoleDetails = new ExternalRoleDetails(); + + externalRoleDetails.setName("test"); + externalRoleDetails.setActive(false); + externalRoleDetails.setPriority(1); + externalRoleDetails.setAppId((long)1); + externalRoleDetails.setAppRoleId((long)1); + externalRoleDetails.setPerms(epAppRoleFunctionList); + + return externalRoleDetails; + } + + @Test + public void externalRoleDetailsTest(){ + + List<EPAppRoleFunction> epAppRoleFunctionList = new ArrayList<EPAppRoleFunction>(); + + EPAppRoleFunction epAppRoleFunction = new EPAppRoleFunction(); + epAppRoleFunction.setRoleId((long)1); + epAppRoleFunction.setAppId((long)1); + epAppRoleFunction.setCode("test"); + + epAppRoleFunctionList.add(epAppRoleFunction); + + ExternalRoleDetails externalRoleDetails = mockExternalRoleDetails(); + + assertEquals(externalRoleDetails.getAppId(), new Long(1)); + assertEquals(externalRoleDetails.getAppRoleId(), new Long(1)); + assertEquals(externalRoleDetails.getPriority().toString(), "1"); + assertEquals(externalRoleDetails.getName(), "test"); + assertEquals(externalRoleDetails.getPriority().toString(), "1"); + assertEquals(externalRoleDetails.getPerms().size(), epAppRoleFunctionList.size()); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/ExternalSystemAccessTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/ExternalSystemAccessTest.java new file mode 100644 index 00000000..aea2c426 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/ExternalSystemAccessTest.java @@ -0,0 +1,27 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.ExternalSystemAccess; + +public class ExternalSystemAccessTest { + + public ExternalSystemAccess mockExternalSystemAccess(){ + ExternalSystemAccess externalSystemAccess = new ExternalSystemAccess("test", false); + + externalSystemAccess.setKey("test"); + externalSystemAccess.setAccessValue(false); + + return externalSystemAccess; + } + + @Test + public void externalSystemAccessTest(){ + ExternalSystemAccess externalSystemAccess = mockExternalSystemAccess(); + + assertEquals(externalSystemAccess.getKey(), "test"); + assertEquals(externalSystemAccess.getAccessValue(), false); + } +} + diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/ExternalSystemRoleApprovalTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/ExternalSystemRoleApprovalTest.java new file mode 100644 index 00000000..b014b66f --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/ExternalSystemRoleApprovalTest.java @@ -0,0 +1,23 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval; + +public class ExternalSystemRoleApprovalTest { + + public ExternalSystemRoleApproval mockExternalSystemRoleApproval(){ + ExternalSystemRoleApproval externalSystemRoleApproval = new ExternalSystemRoleApproval(); + externalSystemRoleApproval.setRoleName("test"); + + return externalSystemRoleApproval; + } + + @Test + public void externalSystemRoleApprovalTest(){ + ExternalSystemRoleApproval externalSystemRoleApproval = mockExternalSystemRoleApproval(); + + assertEquals(externalSystemRoleApproval.getRoleName(), "test"); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/FunctionalMenuItemWithAppIDTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/FunctionalMenuItemWithAppIDTest.java new file mode 100644 index 00000000..0e5bf9c5 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/FunctionalMenuItemWithAppIDTest.java @@ -0,0 +1,28 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.FunctionalMenuItemWithAppID; + +public class FunctionalMenuItemWithAppIDTest { + + public FunctionalMenuItemWithAppID mockFunctionalMenuItemWithAppID(){ + FunctionalMenuItemWithAppID functionalMenuItemWithAppID = new FunctionalMenuItemWithAppID(); + + functionalMenuItemWithAppID.setRestrictedApp(false); + functionalMenuItemWithAppID.setUrl("test"); + + + return functionalMenuItemWithAppID; + } + + @Test + public void functionalMenuItemWithAppIDTest(){ + FunctionalMenuItemWithAppID functionalMenuItemWithAppID = mockFunctionalMenuItemWithAppID(); + + assertEquals(functionalMenuItemWithAppID.toString(), "FunctionalMenuItem [menuId=null, column=null, text=null, parentMenuId=null, url=test, active_yn=null, appid=null, roles=null, restrictedApp=false]"); + + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/GetAccessResultIdTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/GetAccessResultIdTest.java new file mode 100644 index 00000000..004d06b5 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/GetAccessResultIdTest.java @@ -0,0 +1,29 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.GetAccessResultId; + +public class GetAccessResultIdTest { + + public GetAccessResultId mockGetAccessResultId(){ + + GetAccessResultId getAccessResultIdObj = new GetAccessResultId(); + getAccessResultIdObj.setEcompFunction("test"); + getAccessResultIdObj.setAppName("test"); + getAccessResultIdObj.setRoleName("test"); + + return getAccessResultIdObj; + } + + @Test + public void getAccessResultIdObjTest(){ + GetAccessResultId getAccessResultIdObj = mockGetAccessResultId(); + + assertEquals(getAccessResultIdObj.getEcompFunction(), "test"); + assertEquals(getAccessResultIdObj.getAppName(), "test"); + assertEquals(getAccessResultIdObj.getRoleName(), "test"); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/MicroserviceDataTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/MicroserviceDataTest.java new file mode 100644 index 00000000..94014614 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/MicroserviceDataTest.java @@ -0,0 +1,57 @@ +package org.openecomp.portalapp.portal.domain; + +import java.util.ArrayList; +import java.util.List; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.MicroserviceData; +import org.openecomp.portalapp.portal.domain.MicroserviceParameter; + +public class MicroserviceDataTest { + + public MicroserviceData mockMicroserviceData(){ + + MicroserviceData microserviceData= new MicroserviceData(); + + List<MicroserviceParameter> parameterList = new ArrayList<MicroserviceParameter>(); + + MicroserviceParameter microserviceParameter = new MicroserviceParameter(); + microserviceParameter.setId((long)1); + microserviceParameter.setServiceId((long)1); + microserviceParameter.setPara_key("test"); + microserviceParameter.setPara_value("test"); + parameterList.add(microserviceParameter); + + microserviceData.setId((long)1); + microserviceData.setName("test"); + microserviceData.setActive("test"); + microserviceData.setDesc("test"); + microserviceData.setAppId((long)1); + microserviceData.setUrl("test"); + microserviceData.setSecurityType("test"); + microserviceData.setUsername("test"); + microserviceData.setPassword("test"); + + + return microserviceData; + } + + @Test + public void microserviceDataTest(){ + MicroserviceData microserviceData= mockMicroserviceData(); + + assertEquals(microserviceData.getId(), new Long(1)); + assertEquals(microserviceData.getName(), "test"); + assertEquals(microserviceData.getActive(), "test"); + assertEquals(microserviceData.getDesc(), "test"); + // assertEquals(microserviceData.getAppId(), new long(1)); + assertEquals(microserviceData.getUrl(), "test"); + assertEquals(microserviceData.getSecurityType(), "test"); + assertEquals(microserviceData.getUsername(), "test"); + assertEquals(microserviceData.getPassword(), "test"); + + assertEquals(microserviceData.toString(), "MicroserviceData [id=1, name=test, desc=test, appId=1, " + + "url=test, securityType=test, username=test, password=test, parameterList=null]"); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/MicroserviceParameterTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/MicroserviceParameterTest.java new file mode 100644 index 00000000..bcd3ff36 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/MicroserviceParameterTest.java @@ -0,0 +1,31 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.MicroserviceParameter; + +public class MicroserviceParameterTest { + + public MicroserviceParameter mockMicroserviceParameter(){ + MicroserviceParameter microserviceParameter = new MicroserviceParameter(); + + microserviceParameter.setId((long)1); + microserviceParameter.setServiceId((long)1); + microserviceParameter.setPara_key("test"); + microserviceParameter.setPara_value("test"); + + return microserviceParameter; + } + + @Test + public void microserviceParameterTest(){ + MicroserviceParameter microserviceParameter = mockMicroserviceParameter(); + assertEquals(microserviceParameter.getId(), new Long(1)); + assertEquals(microserviceParameter.getServiceId(),(long)1); + assertEquals(microserviceParameter.getPara_key(), "test"); + assertEquals(microserviceParameter.getPara_value(), "test"); + + assertEquals(microserviceParameter.toString(), "MicroserviceParameter [id=1, serviceId=1, para_key=test, para_value=test]"); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/PersUserAppSelectionTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/PersUserAppSelectionTest.java new file mode 100644 index 00000000..3aff8cce --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/PersUserAppSelectionTest.java @@ -0,0 +1,35 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.PersUserAppSelection; + +public class PersUserAppSelectionTest { + + public PersUserAppSelection mockPersUserAppSelection(){ + + PersUserAppSelection persUserAppSelection = new PersUserAppSelection(); + persUserAppSelection.setUserId((long)1); + persUserAppSelection.setAppId((long)1); + persUserAppSelection.setStatusCode("test"); + + return persUserAppSelection; + } + + @Test + public void persUserAppSelectionTest(){ + + PersUserAppSelection persUserAppSelection1 = new PersUserAppSelection((long)1, (long)1, (long)1,"test"); + + PersUserAppSelection persUserAppSelection = mockPersUserAppSelection(); + + assertEquals(persUserAppSelection.getUserId(), new Long(1)); + assertEquals(persUserAppSelection.getAppId(), new Long(1)); + assertEquals(persUserAppSelection.getStatusCode(), "test"); + assertEquals(persUserAppSelection1.hashCode(), new PersUserAppSelection((long)1, (long)1, (long)1,"test").hashCode()); + assertEquals(persUserAppSelection1, new PersUserAppSelection((long)1, (long)1, (long)1,"test")); + assertTrue(persUserAppSelection1.equals(new PersUserAppSelection((long)1, (long)1, (long)1,"test"))); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/PersUserWidgetSelectionTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/PersUserWidgetSelectionTest.java new file mode 100644 index 00000000..da480134 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/PersUserWidgetSelectionTest.java @@ -0,0 +1,36 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.PersUserWidgetSelection; + +public class PersUserWidgetSelectionTest { + + public PersUserWidgetSelection mockPersUserWidgetSelection(){ + + PersUserWidgetSelection persUserWidgetSelection = new PersUserWidgetSelection(); + + persUserWidgetSelection.setUserId((long)1); + persUserWidgetSelection.setWidgetId((long)1); + persUserWidgetSelection.setStatusCode("test"); + + return persUserWidgetSelection; + } + + @Test + public void persUserWidgetSelectionTest(){ + PersUserWidgetSelection persUserWidgetSelection = mockPersUserWidgetSelection(); + + PersUserWidgetSelection persUserWidgetSelection1 = new PersUserWidgetSelection((long)1, (long)1, (long)1, "test"); + + assertEquals(persUserWidgetSelection.getUserId(), new Long(1)); + assertEquals(persUserWidgetSelection.getWidgetId(), new Long(1)); + assertEquals(persUserWidgetSelection.getStatusCode(), "test"); + assertEquals(persUserWidgetSelection1, new PersUserWidgetSelection((long)1, (long)1, (long)1, "test")); + assertTrue(persUserWidgetSelection1.equals(new PersUserWidgetSelection((long)1, (long)1, (long)1,"test"))); + assertEquals(persUserWidgetSelection.hashCode(), persUserWidgetSelection1.hashCode()); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/ResultTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/ResultTest.java new file mode 100644 index 00000000..19991b51 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/ResultTest.java @@ -0,0 +1,29 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.model.Result; + +public class ResultTest { + + public Result mockResult(){ + + Result result= new Result("test"); + + result.setResult("test"); + return result; + } + + @Test + public void resultTest(){ + + Result result = mockResult(); + result.setResult("test"); + + assertEquals(result.getResult(), "test"); + + } + + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/SharedContextTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/SharedContextTest.java new file mode 100644 index 00000000..8e2ff420 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/SharedContextTest.java @@ -0,0 +1,36 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import java.util.Date; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.SharedContext; + +public class SharedContextTest { + + public SharedContext mockSharedContext(){ + + SharedContext sharedContext = new SharedContext(); + sharedContext.setId((long)1); + sharedContext.setCreate_time(new Date()); + sharedContext.setContext_id("test"); + sharedContext.setCkey("test"); + sharedContext.setCvalue("test"); + + return sharedContext; + } + + @Test + public void sharedContextTest(){ + SharedContext sharedContext = mockSharedContext(); + + assertEquals(sharedContext.getId(), new Long(1)); + // assertEquals(sharedContext.getCreate_time(), new Date()); + assertEquals(sharedContext.getContext_id(), "test"); + assertEquals(sharedContext.getCkey(), "test"); + assertEquals(sharedContext.getCvalue(), "test"); + + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/UserIdRoleIdTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/UserIdRoleIdTest.java new file mode 100644 index 00000000..b41bcadb --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/UserIdRoleIdTest.java @@ -0,0 +1,29 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.UserIdRoleId; + +public class UserIdRoleIdTest { + + public UserIdRoleId mockUserIdRoleId(){ + UserIdRoleId userIdRoleId = new UserIdRoleId(); + userIdRoleId.setUser_Id("test"); + userIdRoleId.setRoleId("test"); + userIdRoleId.setOrgUserId("test"); + userIdRoleId.setAppId("test"); + + return userIdRoleId; + } + + @Test + public void userIdRoleIdTest(){ + UserIdRoleId userIdRoleId = mockUserIdRoleId(); + + assertEquals(userIdRoleId.getUser_Id(), "test"); + assertEquals(userIdRoleId.getRoleId(), "test"); + assertEquals(userIdRoleId.getOrgUserId(), "test"); + assertEquals(userIdRoleId.getAppId(), "test"); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/WidgetCatalogParameterTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/WidgetCatalogParameterTest.java new file mode 100644 index 00000000..7db79b80 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/WidgetCatalogParameterTest.java @@ -0,0 +1,33 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.WidgetCatalogParameter; + +public class WidgetCatalogParameterTest { + + public WidgetCatalogParameter mockWidgetCatalogParameter(){ + WidgetCatalogParameter widgetCatalogParameter = new WidgetCatalogParameter(); + + widgetCatalogParameter.setId((long)1); + widgetCatalogParameter.setWidgetId((long)1); + widgetCatalogParameter.setUserId((long)1); + widgetCatalogParameter.setParamId((long)1); + widgetCatalogParameter.setUser_value("test"); + + return widgetCatalogParameter; + } + + @Test + public void widgetCatalogParameterTest(){ + WidgetCatalogParameter widgetCatalogParameter = mockWidgetCatalogParameter(); + + assertEquals(widgetCatalogParameter.getId(), new Long(1)); + assertEquals(widgetCatalogParameter.getWidgetId(), new Long(1)); + assertEquals(widgetCatalogParameter.getUserId(), new Long(1)); + assertEquals(widgetCatalogParameter.getParamId(), new Long(1)); + assertEquals(widgetCatalogParameter.getUser_value(), "test"); + assertEquals(widgetCatalogParameter.toString(), "WidgetCatalogParameter [id=1, widgetId=1, userId=1, paramId=1, user_value=test]"); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/WidgetCatalogTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/WidgetCatalogTest.java new file mode 100644 index 00000000..9e606fc3 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/WidgetCatalogTest.java @@ -0,0 +1,84 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.App; +import org.openecomp.portalapp.portal.domain.RoleApp; +import org.openecomp.portalapp.portal.domain.WidgetCatalog; + +public class WidgetCatalogTest { + + public WidgetCatalog mockWidgetCatalog() { + + WidgetCatalog widgetCatalog = new WidgetCatalog(); + + Set<RoleApp> roleAppSet = new HashSet<RoleApp>(); + // App + App app = new App(); + app.setAppId((long) 1); + app.setAppName("test"); + + // RoleApp + RoleApp roleApp = new RoleApp(); + roleApp.setRoleId((long) 1); + roleApp.setRoleName("test"); + roleApp.setApp(app); + roleApp.setWidgets(null); + + roleAppSet.add(roleApp); + + widgetCatalog.setId((long) 1); + widgetCatalog.setName("test"); + widgetCatalog.setDesc("test"); + widgetCatalog.setFileLocation("test"); + widgetCatalog.setAllowAllUser("test"); + widgetCatalog.setServiceId((long) 1); + widgetCatalog.setSortOrder("test"); + widgetCatalog.setStatusCode("test"); + + widgetCatalog.setWidgetRoles(roleAppSet); + + return widgetCatalog; + + } + + @Test + public void widgetCatalogTest() { + + // App + App app = new App(); + app.setAppId((long) 1); + app.setAppName("test"); + + Set<RoleApp> roleAppSet = new HashSet<RoleApp>(); + // RoleApp + RoleApp roleApp = new RoleApp(); + roleApp.setRoleId((long) 1); + roleApp.setRoleName("test"); + roleApp.setApp(app); + roleApp.setWidgets(null); + + roleAppSet.add(roleApp); + + WidgetCatalog widgetCatalog = mockWidgetCatalog(); + + + assertEquals(widgetCatalog.getId(), (long)1); + assertEquals(widgetCatalog.getName(), "test"); + assertEquals(widgetCatalog.getDesc(), "test"); + assertEquals(widgetCatalog.getFileLocation(), "test"); + assertEquals(widgetCatalog.getAllowAllUser(), "test"); + assertEquals(widgetCatalog.getServiceId(), new Long (1)); + assertEquals(widgetCatalog.getSortOrder(), "test"); + assertEquals(widgetCatalog.getStatusCode(), "test"); + assertEquals(widgetCatalog.getWidgetRoles().size(),1); + + assertEquals("WidgetCatalog [id=1, name=test, desc=test, fileLocation=test, allowAllUser=test]", widgetCatalog.toString()); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/WidgetParameterResultTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/WidgetParameterResultTest.java new file mode 100644 index 00000000..4e80bdb9 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/WidgetParameterResultTest.java @@ -0,0 +1,33 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.WidgetParameterResult; + +public class WidgetParameterResultTest { + + public WidgetParameterResult mockWidgetParameterResult(){ + + WidgetParameterResult widgetParameterResult = new WidgetParameterResult(); + widgetParameterResult.setParam_id((long)1); + widgetParameterResult.setParam_key("test"); + widgetParameterResult.setUser_value("test"); + widgetParameterResult.setDefault_value("test"); + + return widgetParameterResult; + } + + @Test + public void widgetParameterResultTest(){ + + WidgetParameterResult widgetParameterResult = mockWidgetParameterResult(); + + assertEquals(widgetParameterResult.getParam_key(), "test"); + assertEquals(widgetParameterResult.getParam_id(), new Long(1)); + assertEquals(widgetParameterResult.getUser_value(), "test"); + assertEquals(widgetParameterResult.getDefault_value(), "test"); + + assertEquals("WidgetParameterResult [param_id=1, param_key=test, user_value=test, default_value=test]", widgetParameterResult.toString()); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/WidgetTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/WidgetTest.java new file mode 100644 index 00000000..bb75836c --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/domain/WidgetTest.java @@ -0,0 +1,34 @@ +package org.openecomp.portalapp.portal.domain; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.Widget; + +public class WidgetTest { + + public Widget mockWidget(){ + + Widget widget = new Widget(); + widget.setName("test"); + widget.setWidth(100); + widget.setHeight(100); + widget.setUrl("test"); + widget.setAppId((long)1); + + return widget; + } + + @Test + public void widgetTest(){ + Widget widget = mockWidget(); + + assertEquals(widget.getName(), "test"); + assertTrue(widget.getWidth() == 100); + assertTrue(widget.getHeight() == 100); + assertEquals(widget.getUrl(), "test"); + assertEquals(widget.getAppId(), new Long(1)); + + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/exceptions/NoHealthyServiceExceptionTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/exceptions/NoHealthyServiceExceptionTest.java new file mode 100644 index 00000000..71f620f3 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/exceptions/NoHealthyServiceExceptionTest.java @@ -0,0 +1,23 @@ +package org.openecomp.portalapp.portal.exceptions; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.exceptions.NoHealthyServiceException; + +public class NoHealthyServiceExceptionTest { + + public NoHealthyServiceException mockNoHealthyServiceException(){ + NoHealthyServiceException noHealthyServiceException = new NoHealthyServiceException("test"); + + return noHealthyServiceException; + } + + @Test + public void noHealthyServiceExceptionTest(){ + NoHealthyServiceException noHealthyServiceException = mockNoHealthyServiceException(); + + // assertEquals(noHealthyServiceException, new NoHealthyServiceException("test")); + assertEquals(noHealthyServiceException.toString(), "NoHealthyServiceException [] test"); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/framework/ApplicationCommonContextTestSuite.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/framework/ApplicationCommonContextTestSuite.java new file mode 100644 index 00000000..96d7f310 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/framework/ApplicationCommonContextTestSuite.java @@ -0,0 +1,172 @@ +///*- +// * ================================================================================ +// * 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.framework; +// +//import java.io.IOException; +// +//import org.junit.Before; +//import org.junit.runner.RunWith; +//import org.openecomp.portalsdk.core.conf.AppConfig; +////import org.openecomp.portalapp.conf.ExternalAppConfig; +////import org.openecomp.portalapp.conf.HibernateMappingLocations; +//import org.openecomp.portalsdk.core.conf.HibernateConfiguration; +//import org.openecomp.portalsdk.core.conf.HibernateMappingLocatable; +//import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; +//import org.openecomp.portalsdk.core.util.CacheManager; +//import org.openecomp.portalsdk.core.util.SystemProperties; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.context.annotation.Bean; +//import org.springframework.context.annotation.ComponentScan; +//import org.springframework.context.annotation.Configuration; +//import org.springframework.context.annotation.FilterType; +//import org.springframework.context.annotation.Profile; +//import org.springframework.core.io.ClassPathResource; +//import org.springframework.core.io.Resource; +//import org.springframework.test.context.ActiveProfiles; +//import org.springframework.test.context.ContextConfiguration; +//import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +//import org.springframework.test.context.web.AnnotationConfigWebContextLoader; +//import org.springframework.test.context.web.WebAppConfiguration; +//import org.springframework.test.web.servlet.MockMvc; +//import org.springframework.test.web.servlet.setup.MockMvcBuilders; +//import org.springframework.web.context.WebApplicationContext; +//import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +// +///** +// * +// * In order to write a unit test, 1. inherit this class 2. place the "war" +// * folder on your test class's classpath 3. run the test with the following VM +// * argument; This is important because when starting the application from +// * Container, the System Properties file (SystemProperties.java) can have the +// * direct path but, when running from the Mock Junit container, the path should +// * be prefixed with "classpath" to enable the mock container to search for the +// * file in the classpath -Dcontainer.classpath="classpath:" +// */ +// +//@SuppressWarnings("deprecation") +//@RunWith(SpringJUnit4ClassRunner.class) +//@WebAppConfiguration +//@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class, classes = { MockAppConfig.class }) +//@ActiveProfiles(value = "test") +//public class ApplicationCommonContextTestSuite { +// +// @Autowired +// public WebApplicationContext wac; +// +// private MockMvc mockMvc; +// +// @Before +// public void setup() { +// if (mockMvc == null) { +// this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); +// +// } +// } +// +// public Object getBean(String name) { +// return this.wac.getBean(name); +// } +// +// public MockMvc getMockMvc() { +// return mockMvc; +// } +// +// public void setMockMvc(MockMvc mockMvc) { +// this.mockMvc = mockMvc; +// } +// +// public WebApplicationContext getWebApplicationContext() { +// return wac; +// } +// +//} +// +//@Configuration +//@ComponentScan(basePackages = "org.openecomp", excludeFilters = { +// // the following source configurations should not be scanned; instead of +// // using Exclusion filter, we can use the @Profile annotation to exclude +// // them +// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.openecomp.portalsdk.core.controller.LogoutController*"), +// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.openecomp.portalsdk.core.controller.SDKLoginController*"), +// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.openecomp.portalapp.conf.ExternalAppConfig*"), +// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.openecomp.*.*InitUebHandler*") }) +//@Profile("test") +//class MockAppConfig extends AppConfig { +// +// @Bean +// HibernateMappingLocatable locatable() { +// return new MockHibernateMappingLocations(); +// } +// +// @Bean +// HibernateConfiguration hibConfiguration() { +// return new HibernateConfiguration(); +// } +// +// @Bean +// public SystemProperties systemProperties() { +// return new MockSystemProperties(); +// } +// +// @Bean +// public AbstractCacheManager cacheManager() { +// return new CacheManager() { +// +// public void configure() throws IOException { +// +// } +// }; +// } +// +// public String[] tileDefinitions() { +// return new String[] { "classpath:/WEB-INF/fusion/defs/definitions.xml", +// "classpath:/WEB-INF/defs/definitions.xml" }; +// } +// +// public void addInterceptors(InterceptorRegistry registry) { +// // registry.addInterceptor(new +// // SessionTimeoutInterceptor()).excludePathPatterns(getExcludeUrlPathsForSessionTimeout()); +// // registry.addInterceptor(resourceInterceptor()); +// } +// +// public static class MockSystemProperties extends SystemProperties { +// +// public MockSystemProperties() { +// } +// +// } +// +//} +// +//@Profile("test") +//class MockHibernateMappingLocations implements HibernateMappingLocatable { +// +// public Resource[] getMappingLocations() { +// return new Resource[] { new ClassPathResource("WEB-INF/fusion/orm/Fusion.hbm.xml"), +// new ClassPathResource("WEB-INF/fusion/orm/EP.hbm.xml"), +// new ClassPathResource("WEB-INF/fusion/orm/Workflow.hbm.xml") }; +// +// } +// +// public String[] getPackagesToScan() { +// return new String[] { "org.openecomp", "src" }; +// } +// +//} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/framework/MockitoTestSuite.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/framework/MockitoTestSuite.java new file mode 100644 index 00000000..ccda5f3e --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/framework/MockitoTestSuite.java @@ -0,0 +1,76 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.framework; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class MockitoTestSuite { + + + public MockHttpServletRequestWrapper mockedRequest = new MockHttpServletRequestWrapper( + Mockito.mock(HttpServletRequest.class)); + public HttpServletResponse mockedResponse = Mockito.mock(HttpServletResponse.class); + + public MockHttpServletRequestWrapper getMockedRequest() { + return mockedRequest; + } + + public HttpServletResponse getMockedResponse() { + return mockedResponse; + } + + public class MockHttpServletRequestWrapper extends HttpServletRequestWrapper { + + HttpSession session = Mockito.mock(HttpSession.class); + + public MockHttpServletRequestWrapper(HttpServletRequest request) { + super(request); + + } + + @Override + public HttpSession getSession() { + + return session; + } + + @Override + public HttpSession getSession(boolean create) { + + return session; + } + + } + + @Test + public void test() + { + assert(true); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/lm/FusionLicenseManagerImplTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/lm/FusionLicenseManagerImplTest.java new file mode 100644 index 00000000..6c1e52f7 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/lm/FusionLicenseManagerImplTest.java @@ -0,0 +1,29 @@ +package org.openecomp.portalapp.portal.lm; + +import static org.junit.Assert.assertEquals; + +import java.util.Date; + +import org.junit.Test; +import org.openecomp.portalapp.lm.FusionLicenseManagerImpl; + +public class FusionLicenseManagerImplTest { + + + @Test + public void FusionLicenseManagerImplTest(){ + FusionLicenseManagerImpl fusionLicenseManagerImpl = new FusionLicenseManagerImpl(); + + String nvlReturn = null; + + int installLicenseInt = fusionLicenseManagerImpl.installLicense(); + nvlReturn = fusionLicenseManagerImpl.nvl("test"); + Date expiredDateReturn = fusionLicenseManagerImpl.getExpiredDate(); + + assertEquals(installLicenseInt, 0); + assertEquals(nvlReturn, null); + assertEquals(expiredDateReturn, null); + + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/lm/LicenseableClassImplTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/lm/LicenseableClassImplTest.java new file mode 100644 index 00000000..b57291ee --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/lm/LicenseableClassImplTest.java @@ -0,0 +1,31 @@ +package org.openecomp.portalapp.portal.lm; + +import static org.junit.Assert.assertEquals; + +import java.io.FileNotFoundException; + +import org.junit.Test; +import org.openecomp.portalapp.lm.LicenseableClassImpl; + +public class LicenseableClassImplTest { + + @Test + public void licenseableClassImplTest() throws FileNotFoundException{ + LicenseableClassImpl licenseableClassImpl = new LicenseableClassImpl(); + + String appNameReturn = licenseableClassImpl.getApplicationName(); + java.io.InputStream inputStream = licenseableClassImpl.getPublicKeystoreAsInputStream(); + String aliasReturn = licenseableClassImpl.getAlias(); + String pswdReturn = licenseableClassImpl.getKeyPasswd(); + String pkPswd = licenseableClassImpl.getPublicKeystorePassword(); + String cpPswd = licenseableClassImpl.getCipherParamPassword(); + + assertEquals(appNameReturn, ""); + assertEquals(inputStream, null); + assertEquals(aliasReturn, ""); + assertEquals(pswdReturn, ""); + assertEquals(pkPswd, ""); + assertEquals(cpPswd, ""); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/model/AppCatalogItemTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/model/AppCatalogItemTest.java new file mode 100644 index 00000000..5b8440b8 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/model/AppCatalogItemTest.java @@ -0,0 +1,35 @@ +package org.openecomp.portalapp.portal.model; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.openecomp.portalapp.portal.ecomp.model.AppCatalogItem; + +public class AppCatalogItemTest { + + public AppCatalogItem mockAppCatalogItem(){ + AppCatalogItem appCatalogItem = new AppCatalogItem(); + + appCatalogItem.setAlternateUrl("test"); + appCatalogItem.setMlAppName("test"); + + return appCatalogItem; + } + + @Test + public void appCatalogItemTest(){ + AppCatalogItem appCatalogItem = mockAppCatalogItem(); + + AppCatalogItem appCatalogItem1 = new AppCatalogItem(); + appCatalogItem1.setAlternateUrl("test"); + appCatalogItem1.setMlAppName("test"); + + assertEquals(appCatalogItem.getAlternateUrl(), appCatalogItem1.getAlternateUrl()); + assertEquals(appCatalogItem.getMlAppName(), appCatalogItem1.getMlAppName()); + + assertEquals(appCatalogItem.toString(), "AppCatalogItem [id=null, name=null, access=null, select=null, pending=null]"); + assertEquals(appCatalogItem.hashCode(), appCatalogItem1.hashCode()); + assertTrue(appCatalogItem.equals(appCatalogItem1)); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/model/AppCategoryFunctionsItemTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/model/AppCategoryFunctionsItemTest.java new file mode 100644 index 00000000..817f5e13 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/model/AppCategoryFunctionsItemTest.java @@ -0,0 +1,42 @@ +package org.openecomp.portalapp.portal.model; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.openecomp.portalapp.portal.ecomp.model.AppCategoryFunctionsItem; + +public class AppCategoryFunctionsItemTest { + + public AppCategoryFunctionsItem mockAppCategoryFunctionsItem(){ + AppCategoryFunctionsItem appCategoryFunctionsItem = new AppCategoryFunctionsItem(); + + appCategoryFunctionsItem.setRowId("test"); + appCategoryFunctionsItem.setAppId("test"); + appCategoryFunctionsItem.setApplication("test"); + appCategoryFunctionsItem.setFunctions("test"); + + return appCategoryFunctionsItem; + } + + @Test + public void appCategoryFunctionsItemTest(){ + AppCategoryFunctionsItem appCategoryFunctionsItem = mockAppCategoryFunctionsItem(); + + AppCategoryFunctionsItem appCategoryFunctionsItem1 = new AppCategoryFunctionsItem(); + + appCategoryFunctionsItem1.setRowId("test"); + appCategoryFunctionsItem1.setAppId("test"); + appCategoryFunctionsItem1.setApplication("test"); + appCategoryFunctionsItem1.setFunctions("test"); + + assertEquals(appCategoryFunctionsItem.getRowId(), appCategoryFunctionsItem1.getRowId()); + assertEquals(appCategoryFunctionsItem.getAppId(), appCategoryFunctionsItem1.getAppId()); + assertEquals(appCategoryFunctionsItem.getApplication(), appCategoryFunctionsItem1.getApplication()); + assertEquals(appCategoryFunctionsItem.getFunctions(), appCategoryFunctionsItem1.getFunctions()); + assertEquals(appCategoryFunctionsItem.toString(), "AppCategoryFunctionsItem [rowId=test, appId=test, application=test, category=null, functions=test]"); + assertEquals(appCategoryFunctionsItem.hashCode(), appCategoryFunctionsItem1.hashCode()); + assertTrue(appCategoryFunctionsItem.equals(appCategoryFunctionsItem1)); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/model/AppContactUsItemTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/model/AppContactUsItemTest.java new file mode 100644 index 00000000..1e286208 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/model/AppContactUsItemTest.java @@ -0,0 +1,49 @@ +package org.openecomp.portalapp.portal.model; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.openecomp.portalapp.portal.ecomp.model.AppContactUsItem; + +public class AppContactUsItemTest { + + public AppContactUsItem mockAppContactUsItem(){ + AppContactUsItem appContactUsItem = new AppContactUsItem(); + + appContactUsItem.setAppId((long)1); + appContactUsItem.setAppName("test"); + appContactUsItem.setDescription("test"); + appContactUsItem.setContactName("test"); + appContactUsItem.setContactEmail("test"); + appContactUsItem.setUrl("test"); + appContactUsItem.setActiveYN("test"); + + return appContactUsItem; + } + + @Test + public void appContactUsItemTest(){ + AppContactUsItem appContactUsItem = mockAppContactUsItem(); + + AppContactUsItem appContactUsItem1 = new AppContactUsItem(); + appContactUsItem1.setAppId((long)1); + appContactUsItem1.setAppName("test"); + appContactUsItem1.setDescription("test"); + appContactUsItem1.setContactName("test"); + appContactUsItem1.setContactEmail("test"); + appContactUsItem1.setUrl("test"); + appContactUsItem1.setActiveYN("test"); + + assertEquals(appContactUsItem.getAppId(), appContactUsItem1.getAppId()); + assertEquals(appContactUsItem.getAppName(), appContactUsItem1.getAppName()); + assertEquals(appContactUsItem.getDescription(), appContactUsItem1.getDescription()); + assertEquals(appContactUsItem.getContactName(), appContactUsItem1.getContactName()); + assertEquals(appContactUsItem.getContactEmail(), appContactUsItem1.getContactEmail()); + assertEquals(appContactUsItem.getUrl(), appContactUsItem1.getUrl()); + assertEquals(appContactUsItem.getActiveYN(), appContactUsItem1.getActiveYN()); + assertEquals(appContactUsItem.toString(), "AppContactUsItem [appId=1, appName=test, description=test, contactName=test, contactEmail=test, url=test, activeYN=test]"); + assertEquals(appContactUsItem.hashCode(), appContactUsItem1.hashCode()); + assertTrue(appContactUsItem.equals(appContactUsItem1)); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/model/SearchResultItemTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/model/SearchResultItemTest.java new file mode 100644 index 00000000..84527d09 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/model/SearchResultItemTest.java @@ -0,0 +1,41 @@ +package org.openecomp.portalapp.portal.model; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem; + +public class SearchResultItemTest { + + public SearchResultItem mockSearchResultItem(){ + SearchResultItem searchResultItem = new SearchResultItem(); + + searchResultItem.setRowId("test"); + searchResultItem.setCategory("test"); + searchResultItem.setName("test"); + searchResultItem.setTarget("test"); + searchResultItem.setUuid("test"); + + return searchResultItem; + } + + @Test + public void searchResultItemTest(){ + SearchResultItem searchResultItem = mockSearchResultItem(); + + SearchResultItem searchResultItem1 = new SearchResultItem(); + searchResultItem1.setRowId("test"); + searchResultItem1.setCategory("test"); + searchResultItem1.setName("test"); + searchResultItem1.setTarget("test"); + searchResultItem1.setUuid("test"); + + assertEquals(searchResultItem.getRowId(), searchResultItem.getRowId()); + assertEquals(searchResultItem.getCategory(), searchResultItem.getCategory()); + assertEquals(searchResultItem.getName(), searchResultItem.getName()); + assertEquals(searchResultItem.getTarget(), searchResultItem.getTarget()); + assertEquals(searchResultItem.getUuid(), searchResultItem.getUuid()); + assertEquals(searchResultItem.toString(), searchResultItem.toString()); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/AppContactUsServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/AppContactUsServiceImplTest.java new file mode 100644 index 00000000..5c6d04f5 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/AppContactUsServiceImplTest.java @@ -0,0 +1,147 @@ +package org.openecomp.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.domain.AppContactUs; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.ecomp.model.AppCategoryFunctionsItem; +import org.openecomp.portalapp.portal.ecomp.model.AppContactUsItem; +import org.openecomp.portalapp.portal.service.AppContactUsService; +import org.openecomp.portalapp.portal.service.AppContactUsServiceImpl; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.service.DataAccessServiceImpl; + +public class AppContactUsServiceImplTest { + + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Mock + AppContactUsService AppContactUsService = new AppContactUsServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + AppContactUsServiceImpl appContactUsServiceImpl = new AppContactUsServiceImpl(); + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + + + public EPApp getApp() { + EPApp app = new EPApp(); + app.setName("Test"); + app.setImageUrl("test"); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 1); + app.setAppRestEndpoint("test"); + app.setAlternateUrl("test"); + app.setName("test"); + app.setMlAppName("test"); + app.setMlAppAdminId("test"); + app.setUsername("test"); + app.setAppPassword("test"); + app.setOpen(true); + app.setEnabled(false); + app.setUebKey("test"); + app.setUebSecret("test"); + app.setUebTopicName("test"); + app.setAppType(1); + return app; + } + @Test + public void getAppContactUsTest() throws Exception + { + + List<AppContactUsItem> contactUsItemList = new ArrayList<>(); + AppContactUsItem appContactUsItem= new AppContactUsItem(); + appContactUsItem.setAppName("testNew"); + contactUsItemList.add(appContactUsItem); + AppContactUsItem appContactUsItem1= new AppContactUsItem(); + appContactUsItem1.setAppName("test"); + contactUsItemList.add(appContactUsItem1); + Mockito.when(dataAccessService.executeNamedQuery("getAppContactUsItems", null, null)).thenReturn(contactUsItemList); + List<AppContactUsItem> expectedcontactUsItemList = appContactUsServiceImpl.getAppContactUs(); + assertEquals(expectedcontactUsItemList, contactUsItemList); + } + + @Test + public void getAppsAndContactsTest() throws Exception + { + List<AppContactUsItem> contactUsItemList = new ArrayList<>(); + AppContactUsItem appContactUsItem= new AppContactUsItem(); + appContactUsItem.setAppName("testNew"); + contactUsItemList.add(appContactUsItem); + AppContactUsItem appContactUsItem1= new AppContactUsItem(); + appContactUsItem1.setAppName("test"); + contactUsItemList.add(appContactUsItem1); + Mockito.when(dataAccessService.executeNamedQuery("getAppsAndContacts", null, null)).thenReturn(contactUsItemList); + List<AppContactUsItem> expectedcontactUsItemList = appContactUsServiceImpl.getAppsAndContacts(); + assertEquals(expectedcontactUsItemList, contactUsItemList); + } + + @Test + public void getAppCategoryFunctionsTest() throws Exception + { + List<AppCategoryFunctionsItem> list = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("getAppCategoryFunctions", null, null)).thenReturn(list); + List<AppCategoryFunctionsItem> expectedlist = appContactUsServiceImpl.getAppCategoryFunctions(); + assertEquals(list, expectedlist); + } + + @Test(expected = java.lang.Exception.class) + public void saveAppContactUsTest() throws Exception + { + HashMap<String, Object> map = new HashMap<String, Object>(); + List<AppContactUsItem> contactUsModelList = new ArrayList<>(); + AppContactUsItem appContactUsItem= new AppContactUsItem(); + appContactUsItem.setAppId((long) 1); + contactUsModelList.add(appContactUsItem); + AppContactUs appContact = new AppContactUs(); + Mockito.when(dataAccessService.getDomainObject(AppContactUs.class, 1, map)).thenReturn(appContact); + EPApp app = getApp(); + Mockito.when(dataAccessService.getDomainObject(EPApp.class, 1, new HashMap<String, Object>())).thenReturn(app); + AppContactUs contactUs = new AppContactUs(); + contactUs.setApp(app); + contactUs.setDescription(appContactUsItem.getDescription()); + contactUs.setContactName(appContactUsItem.getContactName()); + contactUs.setContactEmail(appContactUsItem.getContactEmail()); + contactUs.setActiveYN(appContactUsItem.getActiveYN()); + contactUs.setUrl(appContactUsItem.getUrl()); + Mockito.doNothing().when(dataAccessService).saveDomainObject(contactUs,map); + appContactUsServiceImpl.saveAppContactUs(contactUsModelList); + } + + @Test(expected = java.lang.NullPointerException.class) + public void deleteContactUsTest() throws Exception + { + HashMap<String, Object> map = new HashMap<String, Object>(); + AppContactUs contactUs = new AppContactUs(); + Mockito.when((AppContactUs) dataAccessService.getDomainObject(AppContactUs.class, 1, map)).thenReturn(contactUs); + appContactUsServiceImpl.deleteContactUs((long) 1); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/DashboardSearchServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/DashboardSearchServiceImplTest.java new file mode 100644 index 00000000..d67f8773 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/DashboardSearchServiceImplTest.java @@ -0,0 +1,114 @@ +package org.openecomp.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.ecomp.model.SearchResultItem; +import org.openecomp.portalapp.portal.service.DashboardSearchServiceImpl; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.portal.transport.CommonWidget; +import org.openecomp.portalapp.portal.transport.CommonWidgetMeta; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalsdk.core.service.DataAccessService; + +public class DashboardSearchServiceImplTest { + + @Mock + DataAccessService dataAccessService; + + @InjectMocks + DashboardSearchServiceImpl dashboardSearchServiceImpl = new DashboardSearchServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + NullPointerException nullPointerException = new NullPointerException(); + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + MockEPUser mockUser = new MockEPUser(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + + @Test + public void searchResultsTest() + { + Map<String, String> params = new HashMap<>(); + params.put("userId", "guestT"); + params.put("searchQuery", "test"); + + List<SearchResultItem> list = new ArrayList<>(); + SearchResultItem searchResultItem= new SearchResultItem(); + searchResultItem.setCategory("test"); + list.add(searchResultItem); + Mockito.when(dataAccessService.executeNamedQuery("searchPortal", params, null)).thenReturn(list); + Map<String, List<SearchResultItem>> result = dashboardSearchServiceImpl.searchResults("guestT", "test"); + assertTrue(result.keySet().contains("test")); + } + + @Test + public void getRelatedUsersTest() + { + List<String> activeUsers = new ArrayList<>(); + Map<String, String> params = new HashMap<>(); + params.put("userId", "guestT"); + Mockito.when(dataAccessService.executeNamedQuery("relatedUsers", params, null)).thenReturn(activeUsers); + List<String> expectedActiveUsers = dashboardSearchServiceImpl.getRelatedUsers("guestT"); + assertEquals(expectedActiveUsers,activeUsers); + } + @Test + public void getWidgetDataTest() + { + CommonWidgetMeta CommonWidgetMeta = null; + Map<String, String> params = new HashMap<>(); + params.put("cat", "test"); + @SuppressWarnings("unchecked") + List<CommonWidget> widgetItems = new ArrayList<>(); + CommonWidget commonWidget = new CommonWidget(); + widgetItems.add(commonWidget); + Mockito.when(dataAccessService.executeNamedQuery("getCommonWidgetItem", params, null)).thenReturn(widgetItems); + CommonWidgetMeta expectedCommonWidgetMeta =dashboardSearchServiceImpl.getWidgetData("test"); + assertEquals(expectedCommonWidgetMeta.getCategory(), "test"); + } + + @Test + public void saveWidgetDataBulkTest() + { + CommonWidgetMeta CommonWidgetMeta = new CommonWidgetMeta(); + List<CommonWidget> widgetList = new ArrayList<>(); + CommonWidget commonWidget = new CommonWidget(); + widgetList.add(commonWidget); + CommonWidgetMeta.setItems(widgetList); + Mockito.doNothing().when(dataAccessService).saveDomainObject(commonWidget, null); + assertEquals(dashboardSearchServiceImpl.saveWidgetDataBulk(CommonWidgetMeta), "success"); + } + + @Test + public void saveWidgetDataTest() + { + CommonWidget commonWidget = new CommonWidget(); + Mockito.doNothing().when(dataAccessService).saveDomainObject(commonWidget, null); + assertEquals(dashboardSearchServiceImpl.saveWidgetData(commonWidget), "success"); + } + + @Test + public void deleteWidgetDataTest() + { + CommonWidget commonWidget = new CommonWidget(); + Mockito.doNothing().when(dataAccessService).deleteDomainObject(commonWidget, null); + assertEquals(dashboardSearchServiceImpl.deleteWidgetData(commonWidget), "success"); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/EPRoleFunctionServiceCentralizedImplTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/EPRoleFunctionServiceCentralizedImplTest.java new file mode 100644 index 00000000..789f2bfd --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/EPRoleFunctionServiceCentralizedImplTest.java @@ -0,0 +1,89 @@ +package org.openecomp.portalapp.portal.service; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.hibernate.SessionFactory; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.domain.CentralRoleFunction; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.service.EPRoleFunctionServiceCentralizedImpl; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalsdk.core.domain.RoleFunction; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(SystemProperties.class) +public class EPRoleFunctionServiceCentralizedImplTest { + + + @Mock + DataAccessService dataAccessService; + + @Mock + SessionFactory sessionFactory; + + @InjectMocks + EPRoleFunctionServiceCentralizedImpl ePRoleFunctionServiceCentralizedImpl = new EPRoleFunctionServiceCentralizedImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + NullPointerException nullPointerException = new NullPointerException(); + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + MockEPUser mockUser = new MockEPUser(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + + @Test + public void getRoleFunctions() + { + List<CentralRoleFunction> getRoleFuncList = new ArrayList<>(); + CentralRoleFunction centralRoleFunction = new CentralRoleFunction(); + getRoleFuncList.add(centralRoleFunction); + List<RoleFunction> getRoleFuncListOfPortal = new ArrayList<>(); + RoleFunction roleFunction = new RoleFunction(); + getRoleFuncListOfPortal.add(roleFunction); + final Map<String, Long> params = new HashMap<>(); + params.put("appId", (long) 1); + Mockito.when(dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null)).thenReturn(getRoleFuncList); + List<RoleFunction> expectedGetRoleFuncListOfPortal = ePRoleFunctionServiceCentralizedImpl.getRoleFunctions(); + assertEquals(expectedGetRoleFuncListOfPortal.size(),getRoleFuncListOfPortal.size()); + } + + @Test + public void getRoleFunctionsNewTest() + { + HttpSession session = mockedRequest.getSession(); + EPUser user = mockUser.mockEPUser(); + user.setId((long) 1); + String userId = user.getId().toString(); + final Map<String, String> params = new HashMap<>(); + params.put("userId", userId); + @SuppressWarnings("unused") + List getRoleFuncListOfPortal = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("getRoleFunctionsOfUser", params, null)).thenReturn(getRoleFuncListOfPortal); + Set<String> getRoleFuncListOfPortalSet = ePRoleFunctionServiceCentralizedImpl.getRoleFunctions(mockedRequest, user); + assertTrue(getRoleFuncListOfPortalSet.size() == 0); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/EPRoleFunctionServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/EPRoleFunctionServiceImplTest.java new file mode 100644 index 00000000..07eeed7e --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/EPRoleFunctionServiceImplTest.java @@ -0,0 +1,98 @@ +package org.openecomp.portalapp.portal.service; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.SortedSet; +import java.util.TreeSet; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.service.EPRoleFunctionServiceImpl; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.domain.RoleFunction; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ SystemProperties.class, EPUserUtils.class }) +public class EPRoleFunctionServiceImplTest { + + @Mock + DataAccessService dataAccessService; + + @InjectMocks + EPRoleFunctionServiceImpl ePRoleFunctionServiceImpl = new EPRoleFunctionServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + NullPointerException nullPointerException = new NullPointerException(); + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + MockEPUser mockUser = new MockEPUser(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + + @Test + public void getRoleFunctionsTest() { + List<RoleFunction> functions = new ArrayList<>(); + Mockito.when(dataAccessService.getList(RoleFunction.class, null)).thenReturn(functions); + List<RoleFunction> expectedFunctions = ePRoleFunctionServiceImpl.getRoleFunctions(); + assertEquals(expectedFunctions, functions); + } + + @Test + public void getRoleFunctionsRequestTest() { + EPUser user = mockUser.mockEPUser(); + HashSet roleFunctions = new HashSet<>(); + PowerMockito.mockStatic(SystemProperties.class); + HttpSession session = mockedRequest.getSession(); + Mockito.when(session.getAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME))) + .thenReturn(roleFunctions); + HashSet expectedRoleFunctions = (HashSet) ePRoleFunctionServiceImpl.getRoleFunctions(mockedRequest, user); + assertEquals(expectedRoleFunctions, roleFunctions); + } + + @SuppressWarnings("unchecked") + @Test + public void getRoleFunctionsRequestIfNullTest() { + EPUser user = mockUser.mockEPUser(); + HashSet roleFunctions = null; + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + HttpSession session = mockedRequest.getSession(); + Mockito.when(session.getAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME))) + .thenReturn(roleFunctions); + HashMap roles = new HashMap<>(); + EPRole role = new EPRole(); + SortedSet<RoleFunction> roleFunctionSet = new TreeSet<RoleFunction>(); + RoleFunction rolefun = new RoleFunction(); + roleFunctionSet.add(rolefun); + role.setRoleFunctions(roleFunctionSet); + roles.put((long) 1, role); + Mockito.when(EPUserUtils.getRoles(mockedRequest)).thenReturn(roles); + HashSet expectedRoleFunctions = (HashSet) ePRoleFunctionServiceImpl.getRoleFunctions(mockedRequest, user); + assertTrue(expectedRoleFunctions.size() == 1); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/EPRoleServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/EPRoleServiceImplTest.java new file mode 100644 index 00000000..766d51be --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/EPRoleServiceImplTest.java @@ -0,0 +1,208 @@ +package org.openecomp.portalapp.portal.service; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.service.EPRoleServiceImpl; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalsdk.core.domain.RoleFunction; +import org.openecomp.portalsdk.core.service.DataAccessService; + +public class EPRoleServiceImplTest { + + @Mock + DataAccessService dataAccessService; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + EPRoleServiceImpl ePRoleServiceImpl = new EPRoleServiceImpl(); + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + MockEPUser mockUser = new MockEPUser(); + + @Test + public void getRoleFunctionsTest() { + List<RoleFunction> roleFunctionList = new ArrayList<>(); + Mockito.when(dataAccessService.getList(RoleFunction.class, null)).thenReturn(roleFunctionList); + List<RoleFunction> expectedRoleFunctionList = ePRoleServiceImpl.getRoleFunctions(); + assertEquals(roleFunctionList, expectedRoleFunctionList); + } + + @Test + public void getAvailableChildRolesIfRoleIdIsNullTest() { + List<EPRole> roleList = new ArrayList<>(); + EPRole role = new EPRole(); + EPRole role1 = new EPRole(); + role.addChildRole(role1); + roleList.add(role); + Mockito.when(dataAccessService.getList(EPRole.class, null)).thenReturn(roleList); + List<EPRole> expectedRoleList = ePRoleServiceImpl.getAvailableChildRoles(null); + assertEquals(roleList, expectedRoleList); + } + + // @Test + // public void getAvailableChildRolesIfRoleIdNotNullTest() + // { + // List<EPRole> roleList = new ArrayList<>(); + // EPRole role = new EPRole(); + // EPRole role1= new EPRole(); + // role.addChildRole(role1); + // roleList.add(role); + // Mockito.when(dataAccessService.getDomainObject(EPRole.class, 1, + // null)).thenReturn(role); + // Mockito.when(dataAccessService.getList(EPRole.class, + // null)).thenReturn(roleList); + // + // List<EPRole> expectedRoleList = + // ePRoleServiceImpl.getAvailableChildRoles((long) 1); + // System.out.println(expectedRoleList); + // assertEquals(roleList,expectedRoleList); + // } + // + @Test + public void getRoleFunctionTest() { + RoleFunction roleFunction = new RoleFunction(); + Mockito.when(dataAccessService.getDomainObject(RoleFunction.class, "test", null)).thenReturn(roleFunction); + RoleFunction expectedRoleFunction = ePRoleServiceImpl.getRoleFunction("test"); + assertEquals(expectedRoleFunction, roleFunction); + } + + @Test + public void saveRoleFunctionTest() { + EPRole role = new EPRole(); + Mockito.doNothing().when(dataAccessService).saveDomainObject(role, null); + ePRoleServiceImpl.saveRole(role); + } + + @Test + public void deleteRoleFunctionTest() { + RoleFunction roleFunction = new RoleFunction(); + Mockito.doNothing().when(dataAccessService).deleteDomainObject(roleFunction, null); + ePRoleServiceImpl.deleteRoleFunction(roleFunction); + } + + @Test + public void getRoleTest() { + EPRole role = null; + Mockito.when(dataAccessService.getDomainObject(EPRole.class, 1, null)).thenReturn(role); + EPRole expectedRole = ePRoleServiceImpl.getRole((long) 1); + assertEquals(expectedRole, role); + } + + @Test + public void getRoleIfappIdNullTest() { + assertNull(ePRoleServiceImpl.getRole(null, null)); + + } + + @Test + public void getRoleIfappIdNotNullTest() { + List<EPRole> roles = new ArrayList<>(); + EPRole role = new EPRole(); + roles.add(role); + String sql = "SELECT * FROM fn_role where APP_ID = 1 AND APP_ROLE_ID = 1"; + Mockito.when(dataAccessService.executeSQLQuery(sql, EPRole.class, null)).thenReturn(roles); + EPRole expectedRole = ePRoleServiceImpl.getRole((long) 1, (long) 1); + assertEquals(expectedRole, role); + + } + + @Test + public void getRoleIfListSizeIsMoreThan1Test() { + List<EPRole> roles = new ArrayList<>(); + EPRole role = new EPRole(); + EPRole role1 = new EPRole(); + roles.add(role); + roles.add(role1); + String sql = "SELECT * FROM fn_role where APP_ID = 1 AND APP_ROLE_ID = 1"; + Mockito.when(dataAccessService.executeSQLQuery(sql, EPRole.class, null)).thenReturn(roles); + EPRole expectedRole = ePRoleServiceImpl.getRole((long) 1, (long) 1); + assertEquals(expectedRole, role); + + } + + @Test + public void getRoleIfListSizeIsEmptyTest() { + List<EPRole> roles = new ArrayList<>(); + String sql = "SELECT * FROM fn_role where APP_ID = 1 AND APP_ROLE_ID = 1"; + Mockito.when(dataAccessService.executeSQLQuery(sql, EPRole.class, null)).thenReturn(roles); + assertNull(ePRoleServiceImpl.getRole((long) 1, (long) 1)); + + } + + @Test + public void saveRoleTest() { + EPRole role = new EPRole(); + Mockito.doNothing().when(dataAccessService).saveDomainObject(role, null); + ePRoleServiceImpl.saveRole(role); + } + + @Test + public void deleteRoleTest() { + EPRole role = new EPRole(); + Mockito.doNothing().when(dataAccessService).deleteDomainObject(role, null); + ePRoleServiceImpl.deleteRole(role); + } + + @Test + public void getAvailableRolesTest() { + List<EPRole> roleList = new ArrayList<>(); + Mockito.when(dataAccessService.getList(EPRole.class, null)).thenReturn(roleList); + List<EPRole> expectedRoleList = ePRoleServiceImpl.getAvailableRoles(); + assertEquals(expectedRoleList, roleList); + } + + @Test + public void getAppRolesTest() { + final Map<String, String> portalParams = null; + List<EPRole> roleList = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("getPortalAppRoles", portalParams, null)).thenReturn(roleList); + assertNull(ePRoleServiceImpl.getAppRole("test", (long) 1)); + + } + + @SuppressWarnings("unchecked") + @Test + public void getAppRolesIfNotPortalTest() { + final Map<String, String> params = null; + List<EPRole> roleList = new ArrayList<>(); + EPRole role = new EPRole(); + EPRole role1 = new EPRole(); + roleList.add(role); + roleList.add(role1); + Mockito.when((List<EPRole>) dataAccessService.executeNamedQuery("getAppRoles", params, null)) + .thenReturn(roleList); + List<EPRole> expectedRoleList = (List<EPRole>) ePRoleServiceImpl.getAppRole("test", (long) 10); + System.out.println(expectedRoleList); + + } + + @Test + public void saveRoleFunction() { + RoleFunction domainRoleFunction = new RoleFunction(); + Mockito.doNothing().when(dataAccessService).saveDomainObject(domainRoleFunction, null); + ePRoleServiceImpl.saveRoleFunction(domainRoleFunction); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java new file mode 100644 index 00000000..4c67fa06 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java @@ -0,0 +1,391 @@ +package org.openecomp.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.portal.domain.CentralRoleFunction; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPAppRoleFunction; +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalapp.portal.transport.EcompUserRoles; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.restful.domain.EcompUser; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.service.DataAccessServiceImpl; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestTemplate; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ EcompPortalUtils.class, SystemProperties.class, EPCommonSystemProperties.class }) +public class ExternalAccessRolesServiceImplTest { + @Mock + DataAccessService dataAccessService1 = new DataAccessServiceImpl(); + + @Mock + RestTemplate template = new RestTemplate(); + + @InjectMocks + ExternalAccessRolesServiceImpl externalAccessRolesServiceImpl = new ExternalAccessRolesServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + MockEPUser mockUser = new MockEPUser(); + String uebKey = "test-ueb-key"; + + public EPApp mockApp() { + EPApp app = new EPApp(); + app.setName("Test"); + app.setImageUrl("test"); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 10); + app.setAppRestEndpoint("test"); + app.setAlternateUrl("test"); + app.setName("test"); + app.setMlAppName("test"); + app.setMlAppAdminId("test"); + app.setUsername("test"); + app.setAppPassword("test"); + app.setOpen(false); + app.setEnabled(false); + app.setUebKey("test"); + app.setUebSecret("test"); + app.setUebTopicName("test"); + app.setAppType(1); + return app; + } + + @Test + public void getAppRolesIfAppIsPortalTest() throws Exception { + List<EPRole> applicationRoles = new ArrayList<>(); + Mockito.when(dataAccessService1.getList(EPRole.class, "test", null, null)).thenReturn(applicationRoles); + List<EPRole> expectedApplicationRoles = externalAccessRolesServiceImpl.getAppRoles((long) 1); + assertEquals(expectedApplicationRoles, applicationRoles); + } + + @Test + public void getAppRolesTest() throws Exception { + List<EPRole> applicationRoles = new ArrayList<>(); + Mockito.when(dataAccessService1.getList(EPRole.class, "test", null, null)).thenReturn(applicationRoles); + List<EPRole> expectedApplicationRoles = externalAccessRolesServiceImpl.getAppRoles((long) 10); + assertEquals(expectedApplicationRoles, applicationRoles); + } + + // @SuppressWarnings("null") + // @Test(expected = java.lang.Exception.class) + // public void getAppRolesExceptionTest() throws Exception{ + // List<EPRole> applicationRoles = new ArrayList<>(); + // DataAccessService dataAccessService = null ; + // Mockito.when(dataAccessService.getList(EPRole.class, "where app_id = 10", + // null, null)).thenThrow(nullPointerException); + // List<EPRole> expectedApplicationRoles = + // externalAccessRolesServiceImpl.getAppRoles((long) 10); + // assertEquals(expectedApplicationRoles,applicationRoles); + // } + + @Test(expected = java.lang.Exception.class) + public void getAppExceptionTest() throws Exception { + List<EPApp> app = new ArrayList<>(); + Mockito.when(dataAccessService1.getList(EPApp.class, " where ueb_key = '" + uebKey + "'", null, null)) + .thenReturn(app); + List<EPApp> expectedapp = externalAccessRolesServiceImpl.getApp(uebKey); + assertEquals(app, expectedapp); + } + + @Test(expected = java.lang.Exception.class) + public void getAppTest() throws Exception { + List<EPApp> appList = new ArrayList<>(); + EPApp app = mockApp(); + appList.add(app); + Mockito.when(dataAccessService1.getList(EPApp.class, " where ueb_key = '" + uebKey + "'", null, null)) + .thenReturn(appList); + List<EPApp> expectedapp = externalAccessRolesServiceImpl.getApp(uebKey); + } + + @Test + public void getAppErrorTest() throws Exception { + List<EPApp> appList = new ArrayList<>(); + EPApp app = mockApp(); + app.setId((long) 1); + appList.add(app); + Mockito.when(dataAccessService1.getList(EPApp.class, " where ueb_key = '" + uebKey + "'", null, null)) + .thenReturn(appList); + List<EPApp> expectedapp = externalAccessRolesServiceImpl.getApp(uebKey); + assertEquals(appList, expectedapp); + } + + @Test + public void addRoleTest() throws Exception { + HttpHeaders headers = new HttpHeaders(); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + String uebKey = "test-ueb-key"; + Role role = new Role(); + role.setId((long) 25); + EPApp app = mockApp(); + app.setEnabled(true); + app.setId((long) 10); + app.setNameSpace("test_namesapce"); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + List<EPApp> appList = new ArrayList<>(); + appList.add(app); + List<EPRole> roleList = new ArrayList<>(); + EPRole ePRole = new EPRole(); + role.setName("Test Role"); + roleList.add(ePRole); + Mockito.when(dataAccessService1.getList(EPApp.class, " where ueb_key = '" + uebKey + "'", null, null)) + .thenReturn(appList); + Mockito.when(dataAccessService1.getList(EPRole.class, " where app_role_id = " + role.getId() + " and app_id ="+app.getId(), null, null)).thenReturn(roleList); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)) + .thenReturn("Testurl"); + ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); + + assertTrue(externalAccessRolesServiceImpl.addRole(role, uebKey)); + } + + + @Test + public void addRoleMethodNotAllowedTest() throws Exception { + HttpHeaders headers = new HttpHeaders(); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + Role role = new Role(); + role.setId((long) 25); + EPApp app = mockApp(); + app.setEnabled(true); + app.setId((long) 10); + app.setNameSpace("test_namesapce"); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + List<EPApp> appList = new ArrayList<>(); + appList.add(app); + List<EPRole> roleList = new ArrayList<>(); + EPRole ePRole = new EPRole(); + role.setName("Test Role"); + roleList.add(ePRole); + Mockito.when(dataAccessService1.getList(EPApp.class, " where ueb_key = '" + uebKey + "'", null, null)) + .thenReturn(appList); + + Mockito.when(dataAccessService1.getList(EPRole.class, " where app_role_id = " + role.getId() + " and app_id ="+app.getId(), null, null)).thenReturn(roleList); +// Mockito.when(dataAccessService1.getList(EPRole.class, " where app_role_id = " + role.getId(), null, null)) +// .thenReturn(roleList); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)) + .thenReturn("Testurl"); + ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.METHOD_NOT_ALLOWED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); + + assertFalse(externalAccessRolesServiceImpl.addRole(role, uebKey)); + } + + public EPApp getApp() { + EPApp app = new EPApp(); + app.setName("Test"); + app.setImageUrl("test"); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 1); + app.setAppRestEndpoint("test"); + app.setAlternateUrl("test"); + app.setName("test"); + app.setMlAppName("test"); + app.setMlAppAdminId("test"); + app.setUsername("test"); + app.setAppPassword("test"); + app.setOpen(true); + app.setEnabled(false); + app.setUebKey("test"); + app.setUebSecret("test"); + app.setUebTopicName("test"); + app.setAppType(1); + return app; + } + + @Test + public void deleteCentralRoleFunctionTest() throws Exception { + final Map<String, String> params = new HashMap<>(); + EPApp app = mockApp(); + params.put("functionCode", "menu_fun_code"); + params.put("appId", String.valueOf(10)); + List<CentralRoleFunction> centralRoleFunctionList = new ArrayList<>(); + CentralRoleFunction domainCentralRoleFunction = new CentralRoleFunction(); + domainCentralRoleFunction.setCode("menu_fun_code"); + centralRoleFunctionList.add(domainCentralRoleFunction); + Mockito.when(dataAccessService1.executeNamedQuery("getRoleFunction", params, null)) + .thenReturn(centralRoleFunctionList); + ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); + HttpHeaders headers = new HttpHeaders(); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + + Mockito.doNothing().when(dataAccessService1).deleteDomainObjects(EPAppRoleFunction.class, + "app_id = " + app.getId() + " and function_cd = '" + "menu_fun_code" + "'", null); + + assertTrue(externalAccessRolesServiceImpl.deleteCentralRoleFunction("menu_fun_code", app)); + } + @Test + public void deleteCentralRoleFunctionFailTest() throws Exception { + final Map<String, String> params = new HashMap<>(); + EPApp app = mockApp(); + params.put("functionCode", "menu_fun_code"); + params.put("appId", String.valueOf(10)); + List<CentralRoleFunction> centralRoleFunctionList = new ArrayList<>(); + CentralRoleFunction domainCentralRoleFunction = new CentralRoleFunction(); + domainCentralRoleFunction.setCode("menu_fun_code"); + centralRoleFunctionList.add(domainCentralRoleFunction); + HttpClientErrorException httpClientErrorException = new HttpClientErrorException(HttpStatus.NOT_FOUND); + Mockito.when(dataAccessService1.executeNamedQuery("getRoleFunction", params, null)) + .thenReturn(centralRoleFunctionList); + ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.NOT_FOUND); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenThrow(httpClientErrorException); + HttpHeaders headers = new HttpHeaders(); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + + Mockito.doNothing().when(dataAccessService1).deleteDomainObjects(EPAppRoleFunction.class, + "app_id = " + app.getId() + " and function_cd = '" + "menu_fun_code" + "'", null); + + assertTrue(externalAccessRolesServiceImpl.deleteCentralRoleFunction("menu_fun_code", app)); + } + + @Test + public void deleteCentralRoleFunctionExceptionTest() { + final Map<String, String> params = new HashMap<>(); + EPApp app = mockApp(); + params.put("functionCd", "menu_fun_code"); + params.put("appId", String.valueOf(10)); + List<CentralRoleFunction> centralRoleFunctionList = new ArrayList<>(); + CentralRoleFunction domainCentralRoleFunction = new CentralRoleFunction(); + domainCentralRoleFunction.setCode("menu_fun_code"); + centralRoleFunctionList.add(domainCentralRoleFunction); + Mockito.when(dataAccessService1.executeNamedQuery("getAppFunctionDetails", params, null)) + .thenThrow(nullPointerException); + assertFalse(externalAccessRolesServiceImpl.deleteCentralRoleFunction("menu_fun_code", app)); + } + + @Test + public void getUserTest() { + List<EPUser> userList = new ArrayList<>(); + EPUser user = mockUser.mockEPUser(); + userList.add(user); + Mockito.when(dataAccessService1.getList(EPUser.class, " where org_user_id = '" + "guestT" + "'", null, null)) + .thenReturn(userList); + List<EPUser> expectedUserList = externalAccessRolesServiceImpl.getUser("guestT"); + assertEquals(expectedUserList, userList); + } + + + public void saveCentralRoleFunctionTest() throws Exception { + CentralRoleFunction centralRoleFunction = new CentralRoleFunction(); + centralRoleFunction.setCode("menu_test"); + EPApp app = mockApp(); + app.setId((long) 1); + final Map<String, String> params = new HashMap<>(); + params.put("functionCd", "menu_test"); + params.put("appId", String.valueOf(1)); + PowerMockito.mockStatic(EcompPortalUtils.class); + HttpHeaders headers = new HttpHeaders(); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + List<CentralRoleFunction> appRoleFunc = new ArrayList<>(); + appRoleFunc.add(centralRoleFunction); + Mockito.when(dataAccessService1.executeNamedQuery("getAppFunctionDetails", params, + null)).thenReturn(appRoleFunc); + ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); + } + +// @Test +// public void getAllAppUsersIfAppIsPortalTest() throws Exception +// { +// List<EPApp> expectedapps = new ArrayList<>(); +// EPApp app = new EPApp(); +// app.setEnabled(true); +// app.setId((long) 1); +// expectedapps.add(app); +// List<EPRole> applicationRoles = new ArrayList<>(); +// Mockito.when(dataAccessService1.getList(EPRole.class, "test", null, null)).thenReturn(applicationRoles); +// Mockito.when(dataAccessService1.getList(EPApp.class, " where ueb_key = '" + uebKey + "'", null, null)).thenReturn(expectedapps); +// externalAccessRolesServiceImpl.getAllAppUsers(uebKey); +// } + + + @Test + public void getAllAppUsersTest() throws Exception + { + List<EPApp> expectedapps = new ArrayList<>(); + EPApp app = new EPApp(); + app.setEnabled(true); + app.setId((long) 10); + expectedapps.add(app); + List<EPRole> applicationRoles = new ArrayList<>(); + Mockito.when(dataAccessService1.getList(EPRole.class, "test", null, null)).thenReturn(applicationRoles); + Mockito.when(dataAccessService1.getList(EPApp.class, " where ueb_key = '" + uebKey + "'", null, null)).thenReturn(expectedapps); + final Map<String, Long> appParams = new HashMap<>(); + appParams.put("appId", app.getId()); + List<EcompUserRoles> userList = new ArrayList<>(); + EcompUserRoles ecompUserRoles = new EcompUserRoles(); + ecompUserRoles.setOrgUserId("guestT"); + ecompUserRoles.setRoleId((long) 1); + ecompUserRoles.setRoleName("test"); + + EcompUserRoles ecompUserRoles2 = new EcompUserRoles(); + ecompUserRoles2.setOrgUserId("guestT"); + ecompUserRoles2.setRoleId((long) 2); + ecompUserRoles2.setRoleName("test new"); + userList.add(ecompUserRoles); + userList.add(ecompUserRoles2); + + Mockito.when(dataAccessService1.executeNamedQuery("ApplicationUserRoles", appParams, null)).thenReturn(userList); + List<EcompUser> usersfinalList = externalAccessRolesServiceImpl.getAllAppUsers(uebKey); + assertEquals(usersfinalList.get(0).getRoles().size(), 2); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/FunctionalMenuMockServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/FunctionalMenuMockServiceImplTest.java new file mode 100644 index 00000000..77988aae --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/FunctionalMenuMockServiceImplTest.java @@ -0,0 +1,204 @@ +/*- + * ================================================================================ + * ECOMP Portal + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ================================================================================ + */ +package org.openecomp.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.domain.FunctionalMenuItemWithAppID; +import org.openecomp.portalapp.portal.service.FunctionalMenuService; +import org.openecomp.portalapp.portal.service.FunctionalMenuServiceImpl; +import org.openecomp.portalapp.portal.transport.FavoritesFunctionalMenuItemJson; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItem; +import org.openecomp.portalapp.portal.transport.FunctionalMenuRole; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({SystemProperties.class, EPCommonSystemProperties.class}) +public class FunctionalMenuMockServiceImplTest { + + @Mock + FunctionalMenuService functionalMenuService; + + @Mock + DataAccessService dataAccessService; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + FunctionalMenuServiceImpl functionalMenuServiceImpl= new FunctionalMenuServiceImpl(); + + @Test + public void assignHelpURLsTest(){ + List<FunctionalMenuItem> menuItems = new ArrayList<FunctionalMenuItem>(); + FunctionalMenuItem functionalMenuItem1 = new FunctionalMenuItem(); + functionalMenuItem1.text = "Contact Us"; + FunctionalMenuItem functionalMenuItem2 = new FunctionalMenuItem(); + functionalMenuItem2.text = "Get Access"; + FunctionalMenuItem functionalMenuItem3 = new FunctionalMenuItem(); + functionalMenuItem3.text = "User Guide"; + menuItems.add(functionalMenuItem1); + menuItems.add(functionalMenuItem2); + menuItems.add(functionalMenuItem3); + + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.USER_GUIDE_URL)).thenReturn("http://todo_enter_user_guide_link"); +// Mockito.doNothing().when(functionalMenuServiceImpl).assignHelpURLs(menuItems); + functionalMenuServiceImpl.assignHelpURLs(menuItems); + } + + @Test + public void getFunctionalMenuItemsTest(){ + String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn, r.app_id FROM fn_menu_functional m, " + + "fn_menu_functional_roles r WHERE m.menu_id = r.menu_id AND UPPER(m.active_yn) = 'Y' AND r.role_id != '900' " + + "UNION SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn,-1 app_id FROM fn_menu_functional m " + + "WHERE m.url='' AND UPPER(m.active_yn) = 'Y'"; + List<FunctionalMenuItem> actualResult = new ArrayList<FunctionalMenuItem>(); + List<FunctionalMenuItem> expectedResult = new ArrayList<FunctionalMenuItem>(); + + Mockito.when(dataAccessService.executeSQLQuery(sql, FunctionalMenuItemWithAppID.class, null)).thenReturn(expectedResult); + + actualResult = functionalMenuServiceImpl.getFunctionalMenuItems(true); + assertEquals(actualResult, expectedResult); + } + + @Test + public void getFunctionalMenuItemsNegativeTest(){ + String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn, r.app_id FROM fn_menu_functional m, " + + "fn_menu_functional_roles r WHERE m.menu_id = r.menu_id AND UPPER(m.active_yn) = 'Y' AND r.role_id != '900' " + + "UNION SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn,-1 app_id FROM fn_menu_functional m " + + "WHERE m.url='' AND UPPER(m.active_yn) = 'Y'"; + List<FunctionalMenuItem> actualResult = new ArrayList<FunctionalMenuItem>(); + List<FunctionalMenuItem> expectedResult = new ArrayList<FunctionalMenuItem>(); + + Mockito.when(dataAccessService.executeSQLQuery(sql, FunctionalMenuItemWithAppID.class, null)).thenReturn(expectedResult); + + actualResult = functionalMenuServiceImpl.getFunctionalMenuItems(false); + assertEquals(actualResult, expectedResult); + } + + @Test + public void getFunctionalMenuItemsForNotificationTreeTest(){ + String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn, r.app_id FROM fn_menu_functional m, fn_menu_functional_roles r " + + "WHERE m.menu_id = r.menu_id AND UPPER(m.active_yn) = 'Y' AND r.role_id != '900' UNION SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id," + + " m.url, m.active_yn,-1 app_id FROM fn_menu_functional m WHERE m.url='' AND UPPER(m.active_yn) = 'Y'"; + List<FunctionalMenuItem> actualResult = new ArrayList<FunctionalMenuItem>(); + List<FunctionalMenuItem> expectedResult = new ArrayList<FunctionalMenuItem>(); + + Mockito.when(dataAccessService.executeSQLQuery(sql, FunctionalMenuItemWithAppID.class, null)).thenReturn(expectedResult); + + actualResult = functionalMenuServiceImpl.getFunctionalMenuItemsForNotificationTree(true); + assertEquals(actualResult, expectedResult); + + } + + @Test + public void getFunctionalMenuItemsForNotificationNegativeTreeTest(){ + String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn, r.app_id FROM fn_menu_functional m, fn_menu_functional_roles r " + + "WHERE m.menu_id = r.menu_id AND UPPER(m.active_yn) = 'Y' AND r.role_id != '900' UNION SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id," + + " m.url, m.active_yn,-1 app_id FROM fn_menu_functional m WHERE m.url='' AND UPPER(m.active_yn) = 'Y'"; + List<FunctionalMenuItem> actualResult = new ArrayList<FunctionalMenuItem>(); + List<FunctionalMenuItem> expectedResult = new ArrayList<FunctionalMenuItem>(); + + Mockito.when(dataAccessService.executeSQLQuery(sql, FunctionalMenuItemWithAppID.class, null)).thenReturn(expectedResult); + + actualResult = functionalMenuServiceImpl.getFunctionalMenuItemsForNotificationTree(false); + assertEquals(actualResult, expectedResult); + } + + @Test + public void getFunctionalMenuItemsForAppTest(){ + String sql = "SELECT DISTINCT m1.menu_id, m1.column_num, m1.text, m1.parent_menu_id, m1.url, m.active_yn " + + "FROM fn_menu_functional m, fn_menu_functional m1, fn_menu_functional_ancestors a, fn_menu_functional_roles mr " + + "WHERE mr.app_id='1' AND mr.menu_id = m.menu_id AND UPPER(m.active_yn) = 'Y' AND UPPER(m1.active_yn) ='Y' AND a.menu_id = m.menu_id " + + "AND a.ancestor_menu_id = m1.menu_id"; + Integer appId = 1; + List<FunctionalMenuItem> actualResult = new ArrayList<FunctionalMenuItem>(); + List<FunctionalMenuItem> expectedResult = new ArrayList<FunctionalMenuItem>(); + + Mockito.when(dataAccessService.executeSQLQuery(sql, FunctionalMenuItemWithAppID.class, null)).thenReturn(expectedResult); + + actualResult = functionalMenuServiceImpl.getFunctionalMenuItemsForApp(appId); + assertEquals(actualResult, expectedResult); + } + + @Test + public void getFunctionalMenuItemsForUserTest(){ + String orgUserId = "test"; + String sql = "SELECT DISTINCT m1.menu_id, m1.column_num, m1.text, m1.parent_menu_id, m1.url, m.active_yn " + + "FROM fn_menu_functional m, fn_menu_functional m1, fn_menu_functional_ancestors a, fn_menu_functional_roles mr, fn_user u , fn_user_role ur " + + "WHERE u.org_user_id='test' AND u.user_id = ur.user_id AND ur.app_id = mr.app_id AND (ur.role_id = mr.role_id OR ur.role_id = '999') " + + "AND m.menu_id = mr.menu_id AND UPPER(m.active_yn) = 'Y' AND UPPER(m1.active_yn) ='Y' AND a.menu_id = m.menu_id " + + "AND a.ancestor_menu_id = m1.menu_id UNION select m1.menu_id, m1.column_num, m1.text, m1.parent_menu_id, m1.url, m1.active_yn " + + "FROM fn_menu_functional m, fn_menu_functional_roles mr, fn_menu_functional m1, fn_menu_functional_ancestors a where a.menu_id = m.menu_id AND a.ancestor_menu_id = m1.menu_id AND m.menu_id != m1.menu_id AND m.menu_id = mr.menu_id AND mr.role_id = '900' AND UPPER(m.active_yn) = 'Y' AND UPPER(m1.active_yn) ='Y' UNION SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn FROM fn_menu_functional m WHERE m.text in ('Favorites','Get Access','Contact Us','Support','User Guide','Help')"; + List<FunctionalMenuItem> actualResult = new ArrayList<FunctionalMenuItem>(); + List<FunctionalMenuItem> expectedResult = new ArrayList<FunctionalMenuItem>(); + + Mockito.when(dataAccessService.executeSQLQuery(sql, FunctionalMenuItemWithAppID.class, null)).thenReturn(expectedResult); + + actualResult = functionalMenuServiceImpl.getFunctionalMenuItemsForUser(orgUserId); + assertEquals(actualResult, expectedResult); + } + + @Test + public void getFunctionalMenuItemDetailsTest(){ + Integer menuid = 1; + String sql = "SELECT * FROM fn_menu_functional_roles WHERE menu_id = '1'"; + FunctionalMenuItem actualResult = null; + FunctionalMenuItem expectedResult = null; + List<FunctionalMenuRole> roleItems = new ArrayList<FunctionalMenuRole>(); + Mockito.when(dataAccessService.executeSQLQuery(sql, FunctionalMenuItemWithAppID.class, null)).thenReturn(roleItems); + + actualResult = functionalMenuServiceImpl.getFunctionalMenuItemDetails(menuid); + assertEquals(actualResult, expectedResult); + } + + @Test + public void getFavoriteItemsTest(){ + Long userId = (long)1; + String sql = "SELECT DISTINCT f.user_id,f.menu_id,m.text,m.url " + + "FROM fn_menu_favorites f, fn_menu_functional m, fn_menu_functional_roles mr " + + "WHERE f.user_id='1' AND f.menu_id = m.menu_id AND f.menu_id = mr.menu_id AND mr.role_id != '900' "; + List<FavoritesFunctionalMenuItemJson> actualResult = new ArrayList<FavoritesFunctionalMenuItemJson>(); + List<FavoritesFunctionalMenuItemJson> expectedResult = new ArrayList<FavoritesFunctionalMenuItemJson>(); + + Mockito.when(dataAccessService.executeSQLQuery(sql, FavoritesFunctionalMenuItemJson.class, null)).thenReturn(expectedResult); + + actualResult = functionalMenuServiceImpl.getFavoriteItems(userId); + assertEquals(actualResult, expectedResult); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/FunctionalMenuServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/FunctionalMenuServiceImplTest.java new file mode 100644 index 00000000..71bf067b --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/FunctionalMenuServiceImplTest.java @@ -0,0 +1,73 @@ +///*- +// * ================================================================================ +// * 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.test.service; +// +//import static org.junit.Assert.assertTrue; +// +//import java.util.ArrayList; +//import java.util.HashMap; +//import java.util.List; +//import java.util.Map; +// +//import org.junit.Test; +//import org.openecomp.portalapp.portal.service.FunctionalMenuService; +//import org.openecomp.portalapp.portal.transport.BusinessCardApplicationRole; +//import org.openecomp.portalapp.portal.transport.FunctionalMenuRole; +//import org.openecomp.portalapp.test.framework.ApplicationCommonContextTestSuite; +//import org.springframework.beans.factory.annotation.Autowired; +// +//public class FunctionalMenuServiceImplTest extends ApplicationCommonContextTestSuite { +// +// @Autowired +// FunctionalMenuService functionalMenuService; +// +// @Test +// public void getAppListTestService() throws Exception { +// +// String userId = "guestT"; +// List<BusinessCardApplicationRole> userAppRolesActualResult = null; +// +// List<BusinessCardApplicationRole> userAppRolesExpectedResult = new ArrayList<BusinessCardApplicationRole>(); +// BusinessCardApplicationRole businessCardApplicationRole = new BusinessCardApplicationRole(); +// businessCardApplicationRole.setAppName("ECOMP Portal"); +// businessCardApplicationRole.setRoleName("System Administrator"); +// userAppRolesExpectedResult.add(businessCardApplicationRole); +// Map<String, String> params = new HashMap<String, String>(); +// params.put("userId", userId); +// userAppRolesActualResult = functionalMenuService.getUserAppRolesList(userId); +// assertTrue(userAppRolesActualResult.contains(businessCardApplicationRole)); +// +// } +// +// @Test +// public void getFunctionalMenuRoleTest() throws Exception { +// +// FunctionalMenuRole expectedFunctionalMenuRole = new FunctionalMenuRole(); +// expectedFunctionalMenuRole.setId(new Integer(-1)); +// +// expectedFunctionalMenuRole.setMenuId((long) 137); +// expectedFunctionalMenuRole.setAppId(new Integer(456)); +// expectedFunctionalMenuRole.setRoleId(new Integer(6214)); +// List<FunctionalMenuRole> actualFunctionalMenuRoleList = null; +// actualFunctionalMenuRoleList = functionalMenuService.getFunctionalMenuRole(); +// assertTrue(actualFunctionalMenuRoleList.contains(expectedFunctionalMenuRole)); +// +// } +//} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/GetAccessServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/GetAccessServiceImplTest.java new file mode 100644 index 00000000..84096f13 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/GetAccessServiceImplTest.java @@ -0,0 +1,50 @@ +package org.openecomp.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.GetAccessResult; +import org.openecomp.portalapp.portal.service.GetAccessServiceImpl; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.service.DataAccessServiceImpl; + +public class GetAccessServiceImplTest { + + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + GetAccessServiceImpl getAccessServiceImpl = new GetAccessServiceImpl(); + + MockEPUser mockUser = new MockEPUser(); + + @Test + public void getAppAccessListTest() + { + EPUser user = mockUser.mockEPUser(); + Map<String, Long> params = new HashMap<>(); + params.put("userId", user.getId()); + List<GetAccessResult> appAccessList = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("getAppAccessFunctionRole", params, null)).thenReturn(appAccessList); + + List<GetAccessResult> expectedAppAccessList = getAccessServiceImpl.getAppAccessList(user); + assertEquals(expectedAppAccessList, appAccessList); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/LicenseableClassImplTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/LicenseableClassImplTest.java new file mode 100644 index 00000000..d04355d2 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/LicenseableClassImplTest.java @@ -0,0 +1,61 @@ +package org.openecomp.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.io.IOException; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.lm.LicenseableClassImpl; + +public class LicenseableClassImplTest { + + @InjectMocks + LicenseableClassImpl licenseableClassImpl= new LicenseableClassImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void getApplicationNameTest() + { + assertEquals(licenseableClassImpl.getApplicationName(), ""); + } + @Test + public void getPublicKeystoreAsInputStreamTest() throws IOException + { + assertNull(licenseableClassImpl.getPublicKeystoreAsInputStream()); + } + @Test + public void getAliasTest() + { + assertEquals(licenseableClassImpl.getAlias(), ""); + } + @Test + public void getKeyPasswdTest() + { + assertEquals(licenseableClassImpl.getKeyPasswd(), ""); + } + @Test + public void getPublicKeystorePasswordTest() + { + assertEquals(licenseableClassImpl.getPublicKeystorePassword(), ""); + } + @Test + public void getCipherParamPasswordTest() + { + assertEquals(licenseableClassImpl.getPublicKeystorePassword(), ""); + } + @Test + public void getClassToLicenseTest() + { + assertEquals(licenseableClassImpl.getClassToLicense(), LicenseableClassImpl.class); + } + + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/ManifestServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/ManifestServiceImplTest.java new file mode 100644 index 00000000..1c09a49d --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/ManifestServiceImplTest.java @@ -0,0 +1,55 @@ +package org.openecomp.portalapp.portal.service; + +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.jar.Attributes; + +import javax.servlet.ServletContext; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.service.ManifestServiceImpl; + +public class ManifestServiceImplTest { + + @Mock + ServletContext context; + + @Mock + ServletContext context1 = null; + + @InjectMocks + ManifestServiceImpl manifestServiceImpl = new ManifestServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + NullPointerException nullPointerException = new NullPointerException(); + + @Test + public void getWebappManifestTest() throws IOException { + final String MANIFEST_RESOURCE_PATH = "/META-INF/MANIFEST.MF"; + InputStream inputStream = new ByteArrayInputStream("test data".getBytes()); + Mockito.when(context.getResourceAsStream(MANIFEST_RESOURCE_PATH)).thenReturn(inputStream); + Attributes attributes = manifestServiceImpl.getWebappManifest(); + assertTrue(attributes.size() == 0); + } + + @Test(expected = java.lang.NullPointerException.class) + public void getWebappManifestExceptionTest() throws IOException { + final String MANIFEST_RESOURCE_PATH = "/META-INF/MANIFEST.MF"; + InputStream inputStream = new ByteArrayInputStream("test data".getBytes()); + Mockito.when(context1.getResourceAsStream(MANIFEST_RESOURCE_PATH)).thenThrow(nullPointerException); + Attributes attributes = manifestServiceImpl.getWebappManifest(); + assertTrue(attributes.size() == 0); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/PersUserAppServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/PersUserAppServiceImplTest.java new file mode 100644 index 00000000..7155e146 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/service/PersUserAppServiceImplTest.java @@ -0,0 +1,181 @@ +package org.openecomp.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EPUserApp; +import org.openecomp.portalapp.portal.domain.PersUserAppSelection; +import org.openecomp.portalapp.portal.service.AdminRolesService; +import org.openecomp.portalapp.portal.service.PersUserAppServiceImpl; +import org.openecomp.portalapp.portal.service.UserRolesService; +import org.openecomp.portalapp.portal.core.MockEPUser; +import org.openecomp.portalapp.portal.framework.MockitoTestSuite; +import org.openecomp.portalsdk.core.service.DataAccessService; + +public class PersUserAppServiceImplTest { + + @Mock + DataAccessService dataAccessService; + @Mock + AdminRolesService adminRolesService; + @Mock + UserRolesService userRolesService; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + PersUserAppServiceImpl persUserAppServiceImpl = new PersUserAppServiceImpl(); + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + MockEPUser mockUser = new MockEPUser(); + + public EPApp getApp() { + EPApp app = new EPApp(); + app.setName("Test"); + app.setImageUrl("test"); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 1); + app.setAppRestEndpoint("test"); + app.setAlternateUrl("test"); + app.setName("test"); + app.setMlAppName("test"); + app.setMlAppAdminId("test"); + app.setUsername("test"); + app.setAppPassword("test"); + app.setOpen(true); + app.setEnabled(false); + app.setUebKey("test"); + app.setUebSecret("test"); + app.setUebTopicName("test"); + app.setAppType(1); + return app; + } + + @Test(expected = IllegalArgumentException.class) + public void setPersUserAppValueIfUserNull() { + persUserAppServiceImpl.setPersUserAppValue(null, null, false, false); + } + + @Test + public void setPersUserAppValueTest() { + EPApp app = getApp(); + EPUser user = mockUser.mockEPUser(); + List<PersUserAppSelection> persUserAppSelectionList = new ArrayList<>(); + PersUserAppSelection persUserAppSelection = new PersUserAppSelection(); + persUserAppSelection.setId((long) 1); + persUserAppSelectionList.add(persUserAppSelection); + Mockito.when(dataAccessService.getList(PersUserAppSelection.class, "test", null, null)) + .thenReturn(persUserAppSelectionList); + Mockito.doNothing().when(dataAccessService).deleteDomainObject(persUserAppSelection, null); + persUserAppServiceImpl.setPersUserAppValue(user, app, false, true); + } + + @Test + public void setPersUserAppValueIfSelectTest() { + EPApp app = getApp(); + EPUser user = mockUser.mockEPUser(); + List<PersUserAppSelection> persUserAppSelectionList = new ArrayList<>(); + PersUserAppSelection persUserAppSelection = new PersUserAppSelection(); + persUserAppSelection.setId((long) 1); + persUserAppSelectionList.add(persUserAppSelection); + Mockito.when(dataAccessService.getList(PersUserAppSelection.class, "test", null, null)) + .thenReturn(persUserAppSelectionList); + Mockito.doNothing().when(dataAccessService).saveDomainObject(persUserAppSelection, null); + persUserAppServiceImpl.setPersUserAppValue(user, app, true, true); + } + + @Test + public void setPersUserAppValueIfOpenTest() { + EPApp app = getApp(); + app.setOpen(false); + EPUser user = mockUser.mockEPUser(); + List<PersUserAppSelection> persUserAppSelectionList = new ArrayList<>(); + PersUserAppSelection persUserAppSelection = new PersUserAppSelection(); + persUserAppSelection.setId((long) 1); + persUserAppSelectionList.add(persUserAppSelection); + Mockito.when(dataAccessService.getList(PersUserAppSelection.class, "test", null, null)) + .thenReturn(persUserAppSelectionList); + Mockito.doNothing().when(dataAccessService).saveDomainObject(persUserAppSelection, null); + persUserAppServiceImpl.setPersUserAppValue(user, app, true, true); + } + + @Test + public void setPersUserAppValueIfAppNotOpenTest() { + EPApp app = getApp(); + app.setOpen(false); + EPUser user = mockUser.mockEPUser(); + List<PersUserAppSelection> persUserAppSelectionList = new ArrayList<>(); + PersUserAppSelection persUserAppSelection = new PersUserAppSelection(); + persUserAppSelection.setId((long) 1); + persUserAppSelectionList.add(persUserAppSelection); + Mockito.when(dataAccessService.getList(PersUserAppSelection.class, "test", null, null)) + .thenReturn(persUserAppSelectionList); + Mockito.doNothing().when(dataAccessService).saveDomainObject(persUserAppSelection, null); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + List<EPUserApp> roles = new ArrayList<>(); + EPUserApp epUserApp = new EPUserApp(); + roles.add(epUserApp); + Mockito.when(userRolesService.getCachedAppRolesForUser(app.getId(), user.getId())).thenReturn(roles); + persUserAppServiceImpl.setPersUserAppValue(user, app, true, false); + } + + @Test + public void setPersUserAppValueIfNotPortalAdminTest() { + EPApp app = getApp(); + app.setOpen(false); + EPUser user = mockUser.mockEPUser(); + List<PersUserAppSelection> persUserAppSelectionList = new ArrayList<>(); + PersUserAppSelection persUserAppSelection = new PersUserAppSelection(); + persUserAppSelection.setId((long) 1); + persUserAppSelectionList.add(persUserAppSelection); + Mockito.when(dataAccessService.getList(PersUserAppSelection.class, "test", null, null)) + .thenReturn(persUserAppSelectionList); + Mockito.doNothing().when(dataAccessService).deleteDomainObject(persUserAppSelection, null); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(false); + List<EPUserApp> roles = new ArrayList<>(); + EPUserApp epUserApp = new EPUserApp(); + roles.add(epUserApp); + Mockito.when(userRolesService.getCachedAppRolesForUser(app.getId(), user.getId())).thenReturn(roles); + persUserAppServiceImpl.setPersUserAppValue(user, app, true, false); + } + + @Test + public void setPersUserAppValueNewTest() { + EPApp app = getApp(); + app.setOpen(false); + EPUser user = mockUser.mockEPUser(); + List<PersUserAppSelection> persUserAppSelectionList = new ArrayList<>(); + PersUserAppSelection persUserAppSelection = new PersUserAppSelection(); + persUserAppSelection.setId((long) 1); + persUserAppSelectionList.add(persUserAppSelection); + Mockito.when(dataAccessService.getList(PersUserAppSelection.class, "test", null, null)) + .thenReturn(persUserAppSelectionList); + Mockito.doNothing().when(dataAccessService).saveDomainObject(persUserAppSelection, null); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + List<EPUserApp> roles = new ArrayList<>(); + EPUserApp epUserApp = new EPUserApp(); + roles.add(epUserApp); + Mockito.when(userRolesService.getCachedAppRolesForUser(app.getId(), user.getId())).thenReturn(roles); + persUserAppServiceImpl.setPersUserAppValue(user, app, false, false); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/AnalyticsTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/AnalyticsTest.java new file mode 100644 index 00000000..7fd3c03f --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/AnalyticsTest.java @@ -0,0 +1,33 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.Analytics; + +public class AnalyticsTest { + + public Analytics mockAnalytics(){ + Analytics analytics = new Analytics(); + + analytics.setAction("test"); + analytics.setPage("test"); + analytics.setFunction("test"); + analytics.setUserid("test"); + analytics.setType("test"); + + return analytics; + } + + @Test + public void analyticsTest(){ + Analytics analytics = mockAnalytics(); + + assertEquals(analytics.getAction(), "test"); + assertEquals(analytics.getPage(), "test"); + assertEquals(analytics.getFunction(), "test"); + assertEquals(analytics.getUserid(), "test"); + assertEquals(analytics.getType(), "test"); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/AppCatalogPersonalizationTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/AppCatalogPersonalizationTest.java new file mode 100644 index 00000000..c583c9cd --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/AppCatalogPersonalizationTest.java @@ -0,0 +1,25 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class AppCatalogPersonalizationTest { + + public AppCatalogPersonalization mockAppCatalogPersonalization(){ + AppCatalogPersonalization appCatalogPersonalization = new AppCatalogPersonalization(); + + return appCatalogPersonalization; + } + + @Test + public void appCatalogPersonalizationTest(){ + AppCatalogPersonalization appCatalogPersonalization = mockAppCatalogPersonalization(); + + AppCatalogPersonalization appCatalogPersonalization1 = new AppCatalogPersonalization(); + + assertEquals(appCatalogPersonalization.hashCode(), appCatalogPersonalization1.hashCode()); + assertTrue(appCatalogPersonalization.equals(appCatalogPersonalization1)); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/AppNameIdIsAdminTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/AppNameIdIsAdminTest.java new file mode 100644 index 00000000..a1dffd28 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/AppNameIdIsAdminTest.java @@ -0,0 +1,38 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.AppNameIdIsAdmin; + +public class AppNameIdIsAdminTest { + + public AppNameIdIsAdmin mockAppNameIdIsAdmin(){ + AppNameIdIsAdmin appNameIdIsAdmin = new AppNameIdIsAdmin(); + appNameIdIsAdmin.setId((long)1); + appNameIdIsAdmin.setAppName("test"); + appNameIdIsAdmin.setRestrictedApp(false); + appNameIdIsAdmin.setIsAdmin(false); + return appNameIdIsAdmin; + } + + @Test + public void appNameIdIsAdminTest(){ + AppNameIdIsAdmin appNameIdIsAdmin = mockAppNameIdIsAdmin(); + + AppNameIdIsAdmin appNameIdIsAdmin1 = new AppNameIdIsAdmin(); + appNameIdIsAdmin1.setId((long)1); + appNameIdIsAdmin1.setAppName("test"); + appNameIdIsAdmin1.setRestrictedApp(false); + appNameIdIsAdmin1.setIsAdmin(false); + + assertEquals(appNameIdIsAdmin.getId(), new Long(1)); + assertEquals(appNameIdIsAdmin.getAppName(), "test"); + assertEquals(appNameIdIsAdmin.getRestrictedApp(), false); + assertEquals(appNameIdIsAdmin.getIsAdmin(), false); + + assertEquals(appNameIdIsAdmin.toString(), "AppNameIdIsAdmin [id=1, appName=test, isAdmin=false, restrictedApp=false]"); + assertEquals(appNameIdIsAdmin.hashCode(), appNameIdIsAdmin1.hashCode()); + assertTrue(appNameIdIsAdmin.equals(appNameIdIsAdmin1)); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/AppWithRolesForUserTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/AppWithRolesForUserTest.java new file mode 100644 index 00000000..2a7c343c --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/AppWithRolesForUserTest.java @@ -0,0 +1,32 @@ +package org.openecomp.portalapp.portal.transport; + +import org.junit.Test; +import static org.junit.Assert.assertEquals; +import org.openecomp.portalapp.portal.transport.AppWithRolesForUser; + +public class AppWithRolesForUserTest { + + public AppWithRolesForUser mockAppWithRolesForUser(){ + AppWithRolesForUser appWithRolesForUser = new AppWithRolesForUser(); + + // List<RoleInAppForUser> appRoles = new ArrayList<RoleInAppForUser>(); + + appWithRolesForUser.setOrgUserId("test"); + appWithRolesForUser.setAppId((long)1); + appWithRolesForUser.setAppName("test"); + appWithRolesForUser.setAppRoles(null); + + return appWithRolesForUser; + } + + @Test + public void roleInAppForUserTest(){ + AppWithRolesForUser appWithRolesForUser = mockAppWithRolesForUser(); + + assertEquals(appWithRolesForUser.getOrgUserId(), "test"); + assertEquals(appWithRolesForUser.getAppId(), new Long(1)); + assertEquals(appWithRolesForUser.getAppName(), "test"); + assertEquals(appWithRolesForUser.getAppRoles(), null); + assertEquals(appWithRolesForUser.toString(), "AppWithRolesForUser [orgUserId=test, appId=1, appName=test, appRoles=null]"); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/AppsListWithAdminRoleTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/AppsListWithAdminRoleTest.java new file mode 100644 index 00000000..2c601d3c --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/AppsListWithAdminRoleTest.java @@ -0,0 +1,46 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.*; + +import java.util.ArrayList; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.AppNameIdIsAdmin; +import org.openecomp.portalapp.portal.transport.AppsListWithAdminRole; + +public class AppsListWithAdminRoleTest { + + public AppsListWithAdminRole mockAppsListWithAdminRole(){ + AppsListWithAdminRole appsListWithAdminRole = new AppsListWithAdminRole(); + + ArrayList<AppNameIdIsAdmin> appsRoles = new ArrayList<AppNameIdIsAdmin>(); + AppNameIdIsAdmin appNameIdIsAdmin = new AppNameIdIsAdmin(); + appsRoles.add(appNameIdIsAdmin); + + appsListWithAdminRole.setOrgUserId("test"); + appsListWithAdminRole.setAppsRoles(appsRoles); + + return appsListWithAdminRole; + } + + @Test + public void appsListWithAdminRoleTest(){ + AppsListWithAdminRole appsListWithAdminRole = mockAppsListWithAdminRole(); + + AppsListWithAdminRole appsListWithAdminRole1 = new AppsListWithAdminRole(); + + ArrayList<AppNameIdIsAdmin> appsRoles = new ArrayList<AppNameIdIsAdmin>(); + AppNameIdIsAdmin appNameIdIsAdmin = new AppNameIdIsAdmin(); + appsRoles.add(appNameIdIsAdmin); + + appsListWithAdminRole1.setOrgUserId("test"); + appsListWithAdminRole1.setAppsRoles(appsRoles); + + assertEquals(appsListWithAdminRole.getOrgUserId(), "test"); + assertEquals(appsListWithAdminRole.getAppsRoles(), appsRoles); + + assertTrue(appsListWithAdminRole.equals(appsListWithAdminRole1)); + assertEquals(appsListWithAdminRole.hashCode(), appsListWithAdminRole1.hashCode()); + assertEquals(appsListWithAdminRole.toString(), "AppsListWithAdminRole [orgUserId=test, appsRoles=[AppNameIdIsAdmin [id=null, appName=null, isAdmin=null, restrictedApp=null]]]"); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/BulkUploadRoleFunctionTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/BulkUploadRoleFunctionTest.java new file mode 100644 index 00000000..854afccc --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/BulkUploadRoleFunctionTest.java @@ -0,0 +1,35 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.BulkUploadRoleFunction; + +public class BulkUploadRoleFunctionTest { + + public BulkUploadRoleFunction mockBulkUploadRoleFunction(){ + + BulkUploadRoleFunction bulkUploadRoleFunction = new BulkUploadRoleFunction(); + + bulkUploadRoleFunction.setFunctionName("test"); + bulkUploadRoleFunction.setFunctionCd("test"); + + return bulkUploadRoleFunction; + } + + @Test + public void bulkUploadRoleFunctionTest(){ + BulkUploadRoleFunction bulkUploadRoleFunction = mockBulkUploadRoleFunction(); + + BulkUploadRoleFunction bulkUploadRoleFunction1 = new BulkUploadRoleFunction(); + + bulkUploadRoleFunction1.setFunctionName("test"); + bulkUploadRoleFunction1.setFunctionCd("test"); + + assertEquals(bulkUploadRoleFunction.getFunctionCd(), "test"); + assertEquals(bulkUploadRoleFunction.getFunctionName(), "test"); + assertEquals(bulkUploadRoleFunction.hashCode(), bulkUploadRoleFunction1.hashCode()); + assertTrue(bulkUploadRoleFunction.equals(bulkUploadRoleFunction1)); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/BulkUploadUserRolesTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/BulkUploadUserRolesTest.java new file mode 100644 index 00000000..b2bbba68 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/BulkUploadUserRolesTest.java @@ -0,0 +1,37 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.BulkUploadUserRoles; + +public class BulkUploadUserRolesTest { + + public BulkUploadUserRoles mockBulkUploadUserRoles(){ + BulkUploadUserRoles bulkUploadUserRoles = new BulkUploadUserRoles(); + + bulkUploadUserRoles.setRoleName("test"); + bulkUploadUserRoles.setOrgUserId("test"); + bulkUploadUserRoles.setAppNameSpace("test"); + + return bulkUploadUserRoles; + } + + @Test + public void bulkUploadUserRolesTest(){ + BulkUploadUserRoles bulkUploadUserRoles = mockBulkUploadUserRoles(); + + BulkUploadUserRoles bulkUploadUserRoles1 = new BulkUploadUserRoles(); + + bulkUploadUserRoles1.setRoleName("test"); + bulkUploadUserRoles1.setOrgUserId("test"); + bulkUploadUserRoles1.setAppNameSpace("test"); + + assertEquals(bulkUploadUserRoles.getRoleName(), "test"); + assertEquals(bulkUploadUserRoles.getOrgUserId(), "test"); + assertEquals(bulkUploadUserRoles.getAppNameSpace(), "test"); + + assertEquals(bulkUploadUserRoles.hashCode(), bulkUploadUserRoles1.hashCode()); + assertTrue(bulkUploadUserRoles.equals(bulkUploadUserRoles1)); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/BusinessCardApplicationRoleTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/BusinessCardApplicationRoleTest.java new file mode 100644 index 00000000..0ed06b12 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/BusinessCardApplicationRoleTest.java @@ -0,0 +1,26 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class BusinessCardApplicationRoleTest { + + public BusinessCardApplicationRole mockBusinessCardApplicationRole(){ + BusinessCardApplicationRole businessCardApplicationRole = new BusinessCardApplicationRole(); + + return businessCardApplicationRole; + } + + @Test + public void businessCardApplicationRoleTest(){ + BusinessCardApplicationRole businessCardApplicationRole = mockBusinessCardApplicationRole(); + + BusinessCardApplicationRole businessCardApplicationRole1 = new BusinessCardApplicationRole(); + + assertEquals(businessCardApplicationRole.hashCode(), businessCardApplicationRole1.hashCode()); + assertTrue(businessCardApplicationRole.equals(businessCardApplicationRole1)); + assertEquals(businessCardApplicationRole.toString(), "BusinessCardUserApplicationRoles [appName=null, roleName=null]"); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/BusinessCardApplicationRolesListTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/BusinessCardApplicationRolesListTest.java new file mode 100644 index 00000000..9f5e6785 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/BusinessCardApplicationRolesListTest.java @@ -0,0 +1,26 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class BusinessCardApplicationRolesListTest { + + public BusinessCardApplicationRolesList mockBusinessCardApplicationRolesList(){ + BusinessCardApplicationRolesList businessCardApplicationRolesList = new BusinessCardApplicationRolesList(); + + return businessCardApplicationRolesList; + } + + @Test + public void businessCardApplicationRolesListTest(){ + BusinessCardApplicationRolesList businessCardApplicationRolesList = mockBusinessCardApplicationRolesList(); + + BusinessCardApplicationRolesList businessCardApplicationRolesList1 = new BusinessCardApplicationRolesList(); + + assertEquals(businessCardApplicationRolesList.hashCode(), businessCardApplicationRolesList1.hashCode()); + assertTrue(businessCardApplicationRolesList.equals(businessCardApplicationRolesList1)); + assertEquals(businessCardApplicationRolesList.toString(), "BusinessCardUserAppRoles [appName=null, roleNames=null]"); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/CentralAppTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/CentralAppTest.java new file mode 100644 index 00000000..97c9c59f --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/CentralAppTest.java @@ -0,0 +1,102 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.CentralApp; + +public class CentralAppTest { + + public CentralApp mockCentralApp(){ + CentralApp centralApp = new CentralApp((long)1, null, null, (long)1, (long)1, (long)1, "test", "test", "test", "test", "test", "test", "test", "test", "test", + "test", "test", "test", "test", null, "test", "test", "test", "test"); + + + /* public CentralApp(Long id, Date created, Date modified, Long createdId, Long modifiedId, Long rowNum, String name, + String imageUrl, String description, String notes, String url, String alternateUrl, String restEndpoint, + String mlAppName, String mlAppAdminId, String motsId, String appPassword, String open, String enabled, + byte[] thumbnail, String username, String uebKey, String uebSecret, String uebTopicName)*/ + + centralApp.setId((long)1); + centralApp.setCreatedId((long)1); + centralApp.setModifiedId((long)1); + centralApp.setRowNum((long)1); + centralApp.setName("test"); + centralApp.setImageUrl("test"); + centralApp.setDescription("test"); + centralApp.setNotes("test"); + centralApp.setUrl("test"); + centralApp.setAlternateUrl("test"); + centralApp.setRestEndpoint("test"); + centralApp.setMlAppName("test"); + centralApp.setMlAppAdminId("test"); + centralApp.setMotsId("test"); + centralApp.setAppPassword("test"); + centralApp.setOpen("test"); + centralApp.setEnabled("test"); + centralApp.setUsername("test"); + centralApp.setUebKey("test"); + centralApp.setUebSecret("test"); + centralApp.setUebTopicName("test"); + + return centralApp; + } + + @Test + public void centralAppTest(){ + CentralApp centralApp = mockCentralApp(); + + CentralApp centralApp1 = new CentralApp((long)1, null, null, (long)1, (long)1, (long)1, "test", "test", "test", "test", "test", "test", "test", "test", "test", + "test", "test", "test", "test", null, "test", "test", "test", "test"); + + /*centralApp1.setId((long)1); + centralApp1.setCreatedId((long)1); + centralApp1.setModifiedId((long)1); + centralApp1.setRowNum((long)1); + centralApp1.setName("test"); + centralApp1.setImageUrl("test"); + centralApp1.setDescription("test"); + centralApp1.setNotes("test"); + centralApp1.setUrl("test"); + centralApp1.setAlternateUrl("test"); + centralApp1.setRestEndpoint("test"); + centralApp1.setMlAppName("test"); + centralApp1.setMlAppAdminId("test"); + centralApp1.setMotsId("test"); + centralApp1.setAppPassword("test"); + centralApp1.setOpen("test"); + centralApp1.setEnabled("test"); + centralApp1.setUsername("test"); + centralApp1.setUebKey("test"); + centralApp1.setUebSecret("test"); + centralApp1.setUebTopicName("test");*/ + + assertEquals(centralApp.getId(), new Long(1)); + assertEquals(centralApp.getCreatedId(), new Long(1)); + assertEquals(centralApp.getModifiedId(), new Long(1)); + assertEquals(centralApp.getRowNum(), new Long(1)); + assertEquals(centralApp.getName(), "test"); + assertEquals(centralApp.getImageUrl(), "test"); + assertEquals(centralApp.getDescription(), "test"); + assertEquals(centralApp.getNotes(), "test"); + assertEquals(centralApp.getUrl(), "test"); + assertEquals(centralApp.getAlternateUrl(), "test"); + assertEquals(centralApp.getRestEndpoint(), "test"); + assertEquals(centralApp.getMlAppName(), "test"); + assertEquals(centralApp.getMlAppAdminId(), "test"); + assertEquals(centralApp.getMotsId(), "test"); + assertEquals(centralApp.getAppPassword(), "test"); + assertEquals(centralApp.getOpen(), "test"); + assertEquals(centralApp.getEnabled(), "test"); + assertEquals(centralApp.getUsername(), "test"); + assertEquals(centralApp.getUebKey(), "test"); + assertEquals(centralApp.getUebSecret(), "test"); + assertEquals(centralApp.getUebTopicName(), "test"); + + assertTrue(centralApp.equals(centralApp1)); + assertEquals(centralApp.hashCode(), centralApp1.hashCode()); + /* assertTrue(centralApp.equals(new CentralApp((long)1, null, null, (long)1, (long)1, (long)1, "test", "test", "test", "test", "test", "test", "test", "test", "test", + "test", "test", "test", "test", null, "test", "test", "test", "test")));*/ + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/CentralRoleTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/CentralRoleTest.java new file mode 100644 index 00000000..6ba0a444 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/CentralRoleTest.java @@ -0,0 +1,63 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.*; + +import java.util.Date; +import java.util.SortedSet; + +import org.junit.Test; +import org.openecomp.portalapp.portal.domain.CentralRoleFunction; +import org.openecomp.portalapp.portal.transport.CentralRole; + +public class CentralRoleTest { + + public CentralRole mockCentralRole(){ + CentralRole centralRole = new CentralRole((long)1, null, null, (long)1, (long)1, (long)1, + "test", false, 1, null, null, null); + + centralRole.setId((long)1); + centralRole.setCreatedId((long)1); + centralRole.setModifiedId((long)1); + centralRole.setRowNum((long)1); + centralRole.setName("test"); + centralRole.setActive(false); + centralRole.setPriority(1); + + centralRole.setCreated(null); + centralRole.setModified(null); + centralRole.setRoleFunctions(null); + centralRole.setChildRoles(null); + centralRole.setParentRoles(null); + + return centralRole; + } + + @Test + public void centralRoleTest(){ + CentralRole centralRole = mockCentralRole(); + + CentralRole centralRole1 = new CentralRole((long)1, null, null, (long)1, (long)1, (long)1, + "test", false, 1, null, null, null); + + CentralRole centralRole2 = new CentralRole((long)1, "test"); + + assertEquals(centralRole.getId(), new Long(1)); + assertEquals(centralRole.getCreatedId(), new Long(1)); + assertEquals(centralRole.getModifiedId(), new Long(1)); + assertEquals(centralRole.getRowNum(), new Long(1)); + assertEquals(centralRole.getName(), "test"); + assertEquals(centralRole.isActive(), false); + assertEquals(centralRole.getCreated(), null); + assertEquals(centralRole.getModified(), null); + assertEquals(centralRole.getRoleFunctions(), null); + assertEquals(centralRole.getChildRoles(), null); + assertEquals(centralRole.getParentRoles(), null); + assertEquals(centralRole.getPriority().toString(), "1"); + assertEquals(centralRole.hashCode(), centralRole1.hashCode()); + assertTrue(centralRole.equals(centralRole1)); + assertEquals(centralRole, centralRole1); + assertEquals(centralRole2, new CentralRole((long)1, "test")); + } + + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/CentralUserAppTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/CentralUserAppTest.java new file mode 100644 index 00000000..f3582647 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/CentralUserAppTest.java @@ -0,0 +1,41 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.CentralApp; +import org.openecomp.portalapp.portal.transport.CentralRole; +import org.openecomp.portalapp.portal.transport.CentralUserApp; + +public class CentralUserAppTest { + + public CentralUserApp mockCentralUserApp(){ + CentralUserApp centralUserApp = new CentralUserApp(); + + CentralApp app = new CentralApp((long)1, null, null, (long)1, (long)1, (long)1, "test", "test", "test", "test", "test", "test", "test", "test", "test", + "test", "test", "test", "test", null, "test", "test", "test", "test"); + + CentralRole role = new CentralRole(); + + centralUserApp.setUserId((long)1); + centralUserApp.setApp(app); + centralUserApp.setRole(role); + centralUserApp.setPriority((short) 123); + + return centralUserApp; + } + + @Test + public void centralUserAppTest(){ + CentralUserApp centralUserApp = mockCentralUserApp(); + + CentralApp app1 = new CentralApp((long)1, null, null, (long)1, (long)1, (long)1, "test", "test", "test", "test", "test", "test", "test", "test", "test", + "test", "test", "test", "test", null, "test", "test", "test", "test"); + + CentralRole role1 = new CentralRole(); + + assertEquals(centralUserApp.getUserId(), new Long(1)); + assertEquals(centralUserApp.getPriority(), new Short((short) 123)); + assertEquals(centralUserApp.getApp(), app1); + assertEquals(centralUserApp.getRole(), role1); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/CentralUserTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/CentralUserTest.java new file mode 100644 index 00000000..9df86bc9 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/CentralUserTest.java @@ -0,0 +1,52 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.*; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.CentralRole; +import org.openecomp.portalapp.portal.transport.CentralUser; +import org.openecomp.portalapp.portal.transport.CentralUserApp; + +public class CentralUserTest { + + public CentralUser mockCentralUser(){ + Set<CentralUserApp> userApps = new HashSet<CentralUserApp>(); + Set<CentralRole> pseudoRoles = new HashSet<CentralRole>(); + CentralUser centralUser = new CentralUser((long)1, null, null, (long)1, (long)1, (long)1, (long)1, + (long)1, "test", "test", "test", "test", "test", + "test", "test", (long)1, "test", "test", "test", + "test", "test", "test", "test", "test", "test", "test", + "test", "test", "test", "test", + "test", "test", "test", "test", "test", + "test", "test", "test", "test", "test", + "test", "test", "test", "test", null, + false, false, (long)1, (long)1, false, "test", userApps, pseudoRoles); + + return centralUser; + } + + @Test + public void centralRoleTest(){ + CentralUser centralUser = mockCentralUser(); + + Set<CentralUserApp> userApps = new HashSet<CentralUserApp>(); + Set<CentralRole> pseudoRoles = new HashSet<CentralRole>(); + CentralUser centralUser1 = new CentralUser((long)1, null, null, (long)1, (long)1, (long)1, (long)1, + (long)1, "test", "test", "test", "test", "test", + "test", "test", (long)1, "test", "test", "test", + "test", "test", "test", "test", "test", "test", "test", + "test", "test", "test", "test", + "test", "test", "test", "test", "test", + "test", "test", "test", "test", "test", + "test", "test", "test", "test", null, + false, false, (long)1, (long)1, false, "test", userApps, pseudoRoles); + + + assertEquals(centralUser, centralUser1); + assertEquals(centralUser.hashCode(), centralUser1.hashCode()); + assertTrue(centralUser.equals(centralUser1)); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EPAppsManualPreferenceTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EPAppsManualPreferenceTest.java new file mode 100644 index 00000000..6e8b4018 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EPAppsManualPreferenceTest.java @@ -0,0 +1,47 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.EPAppsManualPreference; + +public class EPAppsManualPreferenceTest { + + public EPAppsManualPreference mockEPAppsManualPreference(){ + EPAppsManualPreference epAppsManualPreference = new EPAppsManualPreference(); + + epAppsManualPreference.setAppid((long)1); + epAppsManualPreference.setCol(1); + epAppsManualPreference.setHeaderText("test"); + epAppsManualPreference.setImageLink("test"); + epAppsManualPreference.setOrder(1); + epAppsManualPreference.setRestrictedApp(false); + epAppsManualPreference.setRow(1); + epAppsManualPreference.setSizeX(1); + epAppsManualPreference.setSizeY(1); + epAppsManualPreference.setSubHeaderText("test"); + epAppsManualPreference.setUrl("test"); + epAppsManualPreference.setAddRemoveApps(false); + + return epAppsManualPreference; + } + + @Test + public void epAppsManualPreferenceTest(){ + + EPAppsManualPreference epAppsManualPreference = mockEPAppsManualPreference(); + + assertEquals(epAppsManualPreference.getAppid(), new Long(1)); + assertEquals(epAppsManualPreference.getCol(), 1); + assertEquals(epAppsManualPreference.getHeaderText(), "test"); + assertEquals(epAppsManualPreference.getImageLink(), "test"); + assertEquals(epAppsManualPreference.getOrder(), 1); + assertEquals(epAppsManualPreference.isRestrictedApp(), false); + assertEquals(epAppsManualPreference.getRow(), 1); + assertEquals(epAppsManualPreference.getSizeX(), 1); + assertEquals(epAppsManualPreference.getSizeY(), 1); + assertEquals(epAppsManualPreference.getSubHeaderText(), "test"); + assertEquals(epAppsManualPreference.getUrl(), "test"); + assertEquals(epAppsManualPreference.isAddRemoveApps(), false); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EPAppsSortPreferenceTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EPAppsSortPreferenceTest.java new file mode 100644 index 00000000..6c67424a --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EPAppsSortPreferenceTest.java @@ -0,0 +1,29 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.EPAppsSortPreference; + +public class EPAppsSortPreferenceTest { + + public EPAppsSortPreference mockEPAppsSortPreference(){ + EPAppsSortPreference epAppsSortPreference = new EPAppsSortPreference(); + + epAppsSortPreference.setIndex(1); + epAppsSortPreference.setValue("test"); + epAppsSortPreference.setTitle("test"); + + return epAppsSortPreference; + } + + @Test + public void epAppsSortPreferenceTest(){ + EPAppsSortPreference epAppsSortPreference = mockEPAppsSortPreference(); + + assertEquals(epAppsSortPreference.getIndex(), 1); + assertEquals(epAppsSortPreference.getValue(), "test"); + assertEquals(epAppsSortPreference.getTitle(), "test"); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EPDeleteAppsManualSortPrefTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EPDeleteAppsManualSortPrefTest.java new file mode 100644 index 00000000..78bb8474 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EPDeleteAppsManualSortPrefTest.java @@ -0,0 +1,29 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.EPDeleteAppsManualSortPref; + +public class EPDeleteAppsManualSortPrefTest { + + public EPDeleteAppsManualSortPref mockEPDeleteAppsManualSortPref(){ + EPDeleteAppsManualSortPref epDeleteAppsManualSortPref = new EPDeleteAppsManualSortPref(); + + epDeleteAppsManualSortPref.setAppId((long)1); + epDeleteAppsManualSortPref.setSelect(false); + epDeleteAppsManualSortPref.setPending(false); + + return epDeleteAppsManualSortPref; + } + + @Test + public void epDeleteAppsManualSortPrefTest(){ + EPDeleteAppsManualSortPref epDeleteAppsManualSortPref = mockEPDeleteAppsManualSortPref(); + + assertEquals(epDeleteAppsManualSortPref.getAppId(), new Long(1)); + assertEquals(epDeleteAppsManualSortPref.isSelect(), false); + assertEquals(epDeleteAppsManualSortPref.isPending(), false); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EPUserAppCurrentRolesTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EPUserAppCurrentRolesTest.java new file mode 100644 index 00000000..9c82ad37 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EPUserAppCurrentRolesTest.java @@ -0,0 +1,41 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.EPUserAppCurrentRoles; + +public class EPUserAppCurrentRolesTest { + + public EPUserAppCurrentRoles mockEPUserAppCurrentRoles(){ + EPUserAppCurrentRoles epUserAppCurrentRoles = new EPUserAppCurrentRoles(); + + epUserAppCurrentRoles.setRoleName("test"); + epUserAppCurrentRoles.setUserId((long)1); + epUserAppCurrentRoles.setPriority("test"); + epUserAppCurrentRoles.setRoleId((long)1); + + return epUserAppCurrentRoles; + } + + @Test + public void epUserAppCurrentRolesTest(){ + EPUserAppCurrentRoles epUserAppCurrentRoles = mockEPUserAppCurrentRoles(); + + EPUserAppCurrentRoles epUserAppCurrentRoles1 = new EPUserAppCurrentRoles(); + + epUserAppCurrentRoles1.setRoleName("test"); + epUserAppCurrentRoles1.setUserId((long)1); + epUserAppCurrentRoles1.setPriority("test"); + epUserAppCurrentRoles1.setRoleId((long)1); + + assertEquals(epUserAppCurrentRoles.getRoleName(), "test"); + assertEquals(epUserAppCurrentRoles.getUserId(), new Long(1)); + assertEquals(epUserAppCurrentRoles.getRoleId(), new Long(1)); + assertEquals(epUserAppCurrentRoles.getPriority(), "test"); + assertEquals(epUserAppCurrentRoles.hashCode(), epUserAppCurrentRoles1.hashCode()); + assertTrue(epUserAppCurrentRoles.equals(epUserAppCurrentRoles1)); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EPWidgetsSortPreferenceTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EPWidgetsSortPreferenceTest.java new file mode 100644 index 00000000..d466d91c --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EPWidgetsSortPreferenceTest.java @@ -0,0 +1,41 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.EPWidgetsSortPreference; + +public class EPWidgetsSortPreferenceTest { + + public EPWidgetsSortPreference mockEPWidgetsSortPreference(){ + EPWidgetsSortPreference epWidgetsSortPreference = new EPWidgetsSortPreference(); + + epWidgetsSortPreference.setSizeX(1); + epWidgetsSortPreference.setSizeY(1); + epWidgetsSortPreference.setHeaderText("test"); + epWidgetsSortPreference.setUrl("test"); + epWidgetsSortPreference.setWidgetid((long)1); + epWidgetsSortPreference.setWidgetIdentifier("test"); + epWidgetsSortPreference.setRow(1); + epWidgetsSortPreference.setCol(1); + + return epWidgetsSortPreference; + } + + @Test + public void epWidgetsSortPreferenceTest(){ + EPWidgetsSortPreference epWidgetsSortPreference = mockEPWidgetsSortPreference(); + + assertEquals(epWidgetsSortPreference.getSizeX(), 1); + assertEquals(epWidgetsSortPreference.getSizeY(), 1); + assertEquals(epWidgetsSortPreference.getHeaderText(), "test"); + assertEquals(epWidgetsSortPreference.getUrl(), "test"); + assertEquals(epWidgetsSortPreference.getWidgetid(), new Long(1)); + assertEquals(epWidgetsSortPreference.getWidgetIdentifier(), "test"); + assertEquals(epWidgetsSortPreference.getRow(), 1); + assertEquals(epWidgetsSortPreference.getRow(), 1); + + } + + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EcompUserAppRolesTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EcompUserAppRolesTest.java new file mode 100644 index 00000000..928c3737 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EcompUserAppRolesTest.java @@ -0,0 +1,33 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.EcompUserAppRoles; + +public class EcompUserAppRolesTest { + + public EcompUserAppRoles mockEcompUserAppRoles(){ + EcompUserAppRoles ecompUserAppRoles = new EcompUserAppRoles(); + + ecompUserAppRoles.setAppId("test"); + ecompUserAppRoles.setUserId((long)1); + ecompUserAppRoles.setPriority("test"); + ecompUserAppRoles.setRoleId((long)1); + ecompUserAppRoles.setRoleName("test"); + + return ecompUserAppRoles; + } + + @Test + public void ecompUserAppRolesTest(){ + + EcompUserAppRoles ecompUserAppRoles = mockEcompUserAppRoles(); + + assertEquals(ecompUserAppRoles.getAppId(), "test"); + assertEquals(ecompUserAppRoles.getPriority(), "test"); + assertEquals(ecompUserAppRoles.getRoleName(), "test"); + assertEquals(ecompUserAppRoles.getUserId(), new Long(1)); + assertEquals(ecompUserAppRoles.getRoleId(), new Long(1)); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EpNotificationItemExtVOTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EpNotificationItemExtVOTest.java new file mode 100644 index 00000000..11fe2cf7 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EpNotificationItemExtVOTest.java @@ -0,0 +1,33 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.EpNotificationItemExtVO; + +public class EpNotificationItemExtVOTest { + + public EpNotificationItemExtVO mockEpNotificationItemExtVO(){ + EpNotificationItemExtVO epNotificationItemExtVO = new EpNotificationItemExtVO(); + + //epNotificationItemExtVO.setActiveYn("abc"); + epNotificationItemExtVO.setMsgHeader("test"); + epNotificationItemExtVO.setMsgDescription("test"); + epNotificationItemExtVO.setPriority(1); + epNotificationItemExtVO.setCreatorId(1); + epNotificationItemExtVO.setLoginId("test"); + + return epNotificationItemExtVO; + } + + @Test + public void epNotificationItemExtVOTest(){ + EpNotificationItemExtVO epNotificationItemExtVO = mockEpNotificationItemExtVO(); + + assertEquals(epNotificationItemExtVO.getMsgHeader(), "test"); + assertEquals(epNotificationItemExtVO.getMsgDescription(), "test"); + assertEquals(epNotificationItemExtVO.getPriority().toString(), "1"); + assertEquals(epNotificationItemExtVO.getCreatorId().toString(), "1"); + assertEquals(epNotificationItemExtVO.getLoginId(), "test"); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EpNotificationItemTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EpNotificationItemTest.java new file mode 100644 index 00000000..6e1e48c6 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EpNotificationItemTest.java @@ -0,0 +1,64 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.EpNotificationItem; + +public class EpNotificationItemTest { + + public EpNotificationItem mockEpNotificationItem(){ + EpNotificationItem epNotificationItem = new EpNotificationItem(); + + epNotificationItem.setNotificationId((long)1); + epNotificationItem.setIsForOnlineUsers("test"); + epNotificationItem.setIsForAllRoles("test"); + epNotificationItem.setActiveYn("test"); + epNotificationItem.setMsgHeader("test"); + epNotificationItem.setMsgDescription("test"); + epNotificationItem.setMsgSource("test"); + + epNotificationItem.setPriority((long)1); + epNotificationItem.setCreatedId((long)1); + epNotificationItem.setNotificationHyperlink("test"); + + return epNotificationItem; + } + + @Test + public void epNotificationItemTest(){ + EpNotificationItem epNotificationItem = mockEpNotificationItem(); + + EpNotificationItem epNotificationItem1 = new EpNotificationItem(); + epNotificationItem1.setNotificationId((long)1); + epNotificationItem1.setIsForOnlineUsers("test"); + epNotificationItem1.setIsForAllRoles("test"); + epNotificationItem1.setActiveYn("test"); + epNotificationItem1.setMsgHeader("test"); + epNotificationItem1.setMsgDescription("test"); + epNotificationItem1.setMsgSource("test"); + + epNotificationItem1.setPriority((long)1); + epNotificationItem1.setCreatedId((long)1); + epNotificationItem1.setNotificationHyperlink("test"); + + assertEquals(epNotificationItem.getNotificationId(), new Long(1)); + assertEquals(epNotificationItem.getIsForOnlineUsers(), "test"); + assertEquals(epNotificationItem.getIsForAllRoles(), "test"); + assertEquals(epNotificationItem.getActiveYn(), "test"); + assertEquals(epNotificationItem.getMsgHeader(), "test"); + assertEquals(epNotificationItem.getMsgDescription(), "test"); + assertEquals(epNotificationItem.getMsgSource(), "test"); + assertEquals(epNotificationItem.getPriority(), new Long(1)); + assertEquals(epNotificationItem.getCreatedId(), new Long(1)); + assertEquals(epNotificationItem.getNotificationHyperlink(), "test"); + + assertEquals(epNotificationItem.toString(), "EpNotificationItem [notificationId=1, isForOnlineUsers=test, isForAllRoles=test, activeYn=test, msgHeader=test, msgDescription=test, msgSource=test, startTime=null, endTime=null, priority=1, creatorId=null, createdDate=null, roles=null, roleIds=null]"); + assertEquals(epNotificationItem.hashCode(), epNotificationItem1.hashCode()); + assertTrue(epNotificationItem.equals(epNotificationItem1)); + + } + +} + + diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EpNotificationItemVOTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EpNotificationItemVOTest.java new file mode 100644 index 00000000..35a11833 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EpNotificationItemVOTest.java @@ -0,0 +1,46 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; + +import java.util.Date; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.EpNotificationItemVO; + +public class EpNotificationItemVOTest { + + public EpNotificationItemVO mockEpNotificationItemVO(){ + EpNotificationItemVO epNotificationItemVO = new EpNotificationItemVO(); + + epNotificationItemVO.setNotificationId(1); + epNotificationItemVO.setIsForOnlineUsers('a'); + epNotificationItemVO.setIsForAllRoles('a'); + epNotificationItemVO.setActiveYn('a'); + epNotificationItemVO.setMsgHeader("test"); + epNotificationItemVO.setMsgDescription("test"); + epNotificationItemVO.setMsgSource("test"); + epNotificationItemVO.setPriority(1); + epNotificationItemVO.setCreatorId(1); + epNotificationItemVO.setLoginId("test"); + epNotificationItemVO.setNotificationHyperlink("test"); + + return epNotificationItemVO; + } + + @Test + public void epNotificationItemVOTest(){ + EpNotificationItemVO epNotificationItemVO = mockEpNotificationItemVO(); + + assertEquals(epNotificationItemVO.getNotificationId().toString(), "1"); + /*assertEquals(epNotificationItemVO.getIsForOnlineUsers(), 'a'); + assertEquals(epNotificationItemVO.getIsForAllRoles(), 'a'); + assertEquals(epNotificationItemVO.getActiveYn(), 'a');*/ + assertEquals(epNotificationItemVO.getMsgHeader(), "test"); + assertEquals(epNotificationItemVO.getMsgDescription(), "test"); + assertEquals(epNotificationItemVO.getMsgSource(), "test"); + assertEquals(epNotificationItemVO.getPriority().toString(), "1"); + assertEquals(epNotificationItemVO.getCreatorId().toString(), "1"); + assertEquals(epNotificationItemVO.getLoginId(), "test"); + assertEquals(epNotificationItemVO.getNotificationHyperlink(), "test"); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EpRoleNotificationItemTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EpRoleNotificationItemTest.java new file mode 100644 index 00000000..beb67ba9 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/EpRoleNotificationItemTest.java @@ -0,0 +1,31 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.EpRoleNotificationItem; + +public class EpRoleNotificationItemTest { + + public EpRoleNotificationItem mockEpRoleNotificationItem(){ + EpRoleNotificationItem epRoleNotificationItem = new EpRoleNotificationItem(); + + epRoleNotificationItem.setId((long)1); + epRoleNotificationItem.setNotificationId((long)1); + epRoleNotificationItem.setRoleId(1); + epRoleNotificationItem.setRecvUserId(1); + + return epRoleNotificationItem; + } + + @Test + public void epRoleNotificationItemTest(){ + EpRoleNotificationItem epRoleNotificationItem = mockEpRoleNotificationItem(); + + assertEquals(epRoleNotificationItem.getId(), new Long(1)); + assertEquals(epRoleNotificationItem.getNotificationId(), new Long(1)); + assertEquals(epRoleNotificationItem.getRoleId().toString(), "1"); + assertEquals(epRoleNotificationItem.getRecvUserId().toString(), "1"); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalAccessPermsDetailTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalAccessPermsDetailTest.java new file mode 100644 index 00000000..f490973a --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalAccessPermsDetailTest.java @@ -0,0 +1,39 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.ExternalAccessPermsDetail; + +public class ExternalAccessPermsDetailTest { + + public ExternalAccessPermsDetail mockExternalAccessPermsDetail(){ + ExternalAccessPermsDetail externalAccessPermsDetail = new ExternalAccessPermsDetail(); + + List<String> roles = new ArrayList<String>(); + + externalAccessPermsDetail.setType("test"); + externalAccessPermsDetail.setInstance("test"); + externalAccessPermsDetail.setAction("test"); + externalAccessPermsDetail.setDescription("test"); + externalAccessPermsDetail.setRoles(roles); + + return externalAccessPermsDetail; + } + + @Test + public void externalAccessPermsDetailTest(){ + ExternalAccessPermsDetail externalAccessPermsDetail = mockExternalAccessPermsDetail(); + + List<String> roles = new ArrayList<String>(); + + assertEquals(externalAccessPermsDetail.getType(), "test"); + assertEquals(externalAccessPermsDetail.getInstance(), "test"); + assertEquals(externalAccessPermsDetail.getAction(), "test"); + assertEquals(externalAccessPermsDetail.getDescription(), "test"); + assertEquals(externalAccessPermsDetail.getRoles(), roles); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalAccessPermsTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalAccessPermsTest.java new file mode 100644 index 00000000..dfae6042 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalAccessPermsTest.java @@ -0,0 +1,42 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.ExternalAccessPerms; + +public class ExternalAccessPermsTest { + + public ExternalAccessPerms mockExternalAccessPerms(){ + ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms(); + + externalAccessPerms.setType("test"); + externalAccessPerms.setInstance("test"); + externalAccessPerms.setAction("test"); + externalAccessPerms.setDescription("test"); + + return externalAccessPerms; + } + + @Test + public void externalAccessPermsTest(){ + ExternalAccessPerms externalAccessPerms = mockExternalAccessPerms(); + + ExternalAccessPerms externalAccessPerms1 = new ExternalAccessPerms("test", "test", "test"); + ExternalAccessPerms externalAccessPerms2 = new ExternalAccessPerms("test", "test", "test", "test"); + ExternalAccessPerms externalAccessPerms3 = new ExternalAccessPerms(); + externalAccessPerms3.setType("test"); + externalAccessPerms3.setInstance("test"); + externalAccessPerms3.setAction("test"); + externalAccessPerms3.setDescription("test"); + + assertEquals(externalAccessPerms.getType(), "test"); + assertEquals(externalAccessPerms.getInstance(), "test"); + assertEquals(externalAccessPerms.getAction(), "test"); + assertEquals(externalAccessPerms.getDescription(), "test"); + assertEquals(externalAccessPerms.hashCode(), externalAccessPerms3.hashCode()); + + assertTrue(externalAccessPerms1.equals(new ExternalAccessPerms("test", "test", "test"))); + assertTrue(externalAccessPerms2.equals(new ExternalAccessPerms("test", "test", "test", "test"))); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalAccessRolePermsTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalAccessRolePermsTest.java new file mode 100644 index 00000000..4e736eba --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalAccessRolePermsTest.java @@ -0,0 +1,35 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.ExternalAccessPerms; +import org.openecomp.portalapp.portal.transport.ExternalAccessRolePerms; + +public class ExternalAccessRolePermsTest { + + public ExternalAccessRolePerms mockExternalAccessRolePerms(){ + ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms(); + externalAccessPerms.setAction("test"); + externalAccessPerms.setDescription("test"); + externalAccessPerms.setInstance("test"); + externalAccessPerms.setType("test"); + ExternalAccessRolePerms ExternalAccessRolePerms = new ExternalAccessRolePerms(externalAccessPerms, "test"); + + return ExternalAccessRolePerms; + } + + @Test + public void externalAccessRolePermsTest(){ + ExternalAccessPerms externalAccessPerms = new ExternalAccessPerms(); + externalAccessPerms.setAction("test"); + externalAccessPerms.setDescription("test"); + externalAccessPerms.setInstance("test"); + externalAccessPerms.setType("test"); + + ExternalAccessRolePerms ExternalAccessRolePerms = mockExternalAccessRolePerms(); + + assertEquals(ExternalAccessRolePerms.getRole(), "test"); + assertEquals(ExternalAccessRolePerms.getPerm(), externalAccessPerms); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalAccessRoleTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalAccessRoleTest.java new file mode 100644 index 00000000..19dee193 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalAccessRoleTest.java @@ -0,0 +1,26 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.ExternalAccessRole; + +public class ExternalAccessRoleTest { + + public ExternalAccessRole mockExternalAccessRole(){ + ExternalAccessRole externalAccessRole = new ExternalAccessRole(); + + externalAccessRole.setName("test"); + externalAccessRole.setDescription("test"); + + return externalAccessRole; + } + + @Test + public void externalAccessRoleTest(){ + ExternalAccessRole externalAccessRole = mockExternalAccessRole(); + + assertEquals(externalAccessRole.getName(), "test"); + assertEquals(externalAccessRole.getDescription(), "test"); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalAccessUserRoleDetailTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalAccessUserRoleDetailTest.java new file mode 100644 index 00000000..6ffab981 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalAccessUserRoleDetailTest.java @@ -0,0 +1,47 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.ExternalAccessUserRoleDetail; +import org.openecomp.portalapp.portal.transport.ExternalRoleDescription; + +public class ExternalAccessUserRoleDetailTest { + + public ExternalAccessUserRoleDetail mockExternalAccessUserRoleDetail(){ + + ExternalRoleDescription externalRoleDescription = new ExternalRoleDescription(); + externalRoleDescription.setId("test"); + externalRoleDescription.setName("test"); + externalRoleDescription.setActive("test"); + externalRoleDescription.setPriority("test"); + externalRoleDescription.setAppId("test"); + externalRoleDescription.setAppRoleId("test"); + + ExternalAccessUserRoleDetail externalAccessUserRoleDetail = new ExternalAccessUserRoleDetail("test", externalRoleDescription); + + externalAccessUserRoleDetail.setName("test"); + externalAccessUserRoleDetail.setDescription(externalRoleDescription); + return externalAccessUserRoleDetail; + } + + @Test + public void externalAccessUserRoleDetailTest(){ + ExternalAccessUserRoleDetail externalAccessUserRoleDetail = mockExternalAccessUserRoleDetail(); + + ExternalRoleDescription externalRoleDescription1 = new ExternalRoleDescription(); + externalRoleDescription1.setId("test"); + externalRoleDescription1.setName("test"); + externalRoleDescription1.setActive("test"); + externalRoleDescription1.setPriority("test"); + externalRoleDescription1.setAppId("test"); + externalRoleDescription1.setAppRoleId("test"); + + ExternalAccessUserRoleDetail externalAccessUserRoleDetail1 = new ExternalAccessUserRoleDetail("test", externalRoleDescription1); + + assertEquals(externalAccessUserRoleDetail.getName(), externalAccessUserRoleDetail1.getName()); + assertEquals(externalAccessUserRoleDetail.getDescription(), externalAccessUserRoleDetail1.getDescription()); + assertEquals(externalAccessUserRoleDetail.hashCode(), externalAccessUserRoleDetail1.hashCode()); + assertTrue(externalAccessUserRoleDetail.equals(externalAccessUserRoleDetail1)); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalAccessUserTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalAccessUserTest.java new file mode 100644 index 00000000..d2be97b1 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalAccessUserTest.java @@ -0,0 +1,24 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.ExternalAccessUser; + +public class ExternalAccessUserTest { + + public ExternalAccessUser mockExternalAccessUser(){ + ExternalAccessUser externalAccessUser = new ExternalAccessUser("test", "test"); + + return externalAccessUser; + } + + @Test + public void externalAccessUserTest(){ + ExternalAccessUser externalAccessUser = mockExternalAccessUser(); + + assertEquals(externalAccessUser.getRole(), "test"); + assertEquals(externalAccessUser.getUser(), "test"); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalRoleDescriptionTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalRoleDescriptionTest.java new file mode 100644 index 00000000..5b6fe825 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/ExternalRoleDescriptionTest.java @@ -0,0 +1,35 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.ExternalRoleDescription; + +public class ExternalRoleDescriptionTest { + + public ExternalRoleDescription mockExternalRoleDescription(){ + + ExternalRoleDescription externalRoleDescription = new ExternalRoleDescription(); + + externalRoleDescription.setId("test"); + externalRoleDescription.setName("test"); + externalRoleDescription.setActive("test"); + externalRoleDescription.setPriority("test"); + externalRoleDescription.setAppId("test"); + externalRoleDescription.setAppRoleId("test"); + + return externalRoleDescription; + } + + @Test + public void externalRoleDescriptionTest(){ + ExternalRoleDescription externalRoleDescription = mockExternalRoleDescription(); + + assertEquals(externalRoleDescription.getId(), "test"); + assertEquals(externalRoleDescription.getName(), "test"); + assertEquals(externalRoleDescription.getActive(), "test"); + assertEquals(externalRoleDescription.getPriority(), "test"); + assertEquals(externalRoleDescription.getAppId(), "test"); + assertEquals(externalRoleDescription.getAppRoleId(), "test"); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/FunctionalMenuItemTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/FunctionalMenuItemTest.java new file mode 100644 index 00000000..7d4b96e5 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/FunctionalMenuItemTest.java @@ -0,0 +1,42 @@ +package org.openecomp.portalapp.portal.transport; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.FunctionalMenuItem; + +public class FunctionalMenuItemTest { + + public FunctionalMenuItem mockFunctionalMenuItem(){ + FunctionalMenuItem functionalMenuItem = new FunctionalMenuItem(); + + List<Integer> roles = new ArrayList<Integer>(); + + functionalMenuItem.setRestrictedApp(false); + functionalMenuItem.setUrl("test"); + functionalMenuItem.setRoles(roles); + + return functionalMenuItem; + } + + @Test + public void functionalMenuItemTest(){ + FunctionalMenuItem functionalMenuItem = mockFunctionalMenuItem(); + + FunctionalMenuItem functionalMenuItem1 = mockFunctionalMenuItem(); + + List<Integer> roles = new ArrayList<Integer>(); + + functionalMenuItem1.setRestrictedApp(false); + functionalMenuItem1.setUrl("test"); + functionalMenuItem1.setRoles(roles); + + assertEquals(functionalMenuItem.getRoles(), functionalMenuItem1.getRoles()); + assertEquals(functionalMenuItem.toString(), "FunctionalMenuItem [menuId=null, column=null, text=null, parentMenuId=null, url=test, active_yn=null, appid=null, roles=[], restrictedApp=false]"); + // assertTrue(functionalMenuItem.normalize(), functionalMenuItem1.normalize()); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/FunctionalMenuRoleTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/FunctionalMenuRoleTest.java new file mode 100644 index 00000000..09f4bc67 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/FunctionalMenuRoleTest.java @@ -0,0 +1,40 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.FunctionalMenuRole; + +public class FunctionalMenuRoleTest { + + public FunctionalMenuRole mockFunctionalMenuRole(){ + FunctionalMenuRole functionalMenuRole = new FunctionalMenuRole(); + + functionalMenuRole.setId(1); + functionalMenuRole.setMenuId((long)1); + functionalMenuRole.setAppId(1); + functionalMenuRole.setRoleId(1); + + return functionalMenuRole; + } + + @Test + public void functionalMenuRoleTest(){ + FunctionalMenuRole functionalMenuRole = mockFunctionalMenuRole(); + + FunctionalMenuRole functionalMenuRole1 = new FunctionalMenuRole(); + functionalMenuRole1.setId(1); + functionalMenuRole1.setMenuId((long)1); + functionalMenuRole1.setAppId(1); + functionalMenuRole1.setRoleId(1); + + assertEquals(functionalMenuRole.getId().toString(), "1"); + assertEquals(functionalMenuRole.getMenuId(), new Long(1)); + assertEquals(functionalMenuRole.getAppId().toString(), "1"); + assertEquals(functionalMenuRole.getRoleId().toString(), "1"); + assertEquals(functionalMenuRole.toString(), "FunctionalMenuRole [id=1, menuId=1, appId=1, roleId=1]"); + assertTrue(functionalMenuRole.equals(functionalMenuRole1)); + assertEquals(functionalMenuRole.hashCode(), functionalMenuRole1.hashCode()); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/RemoteUserWithRolesTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/RemoteUserWithRolesTest.java new file mode 100644 index 00000000..ef926f6a --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/RemoteUserWithRolesTest.java @@ -0,0 +1,65 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.RemoteRole; +import org.openecomp.portalapp.portal.transport.RemoteUserWithRoles; + +public class RemoteUserWithRolesTest { + + public RemoteUserWithRoles mockRemoteUserWithRoles(){ + RemoteUserWithRoles remoteUserWithRoles = new RemoteUserWithRoles(); + + List<RemoteRole> roles = new ArrayList<RemoteRole>(); + RemoteRole remoteRole = new RemoteRole(); + remoteRole.setId((long)1); + remoteRole.setName("test"); + roles.add(remoteRole); + + remoteUserWithRoles.setOrgId((long)1); + remoteUserWithRoles.setManagerId((long)1); + remoteUserWithRoles.setFirstName("test"); + remoteUserWithRoles.setMiddleInitial("test"); + remoteUserWithRoles.setLastName("test"); + remoteUserWithRoles.setPhone("test"); + remoteUserWithRoles.setEmail("test"); + remoteUserWithRoles.setHrid("test"); + remoteUserWithRoles.setOrgUserId("test"); + remoteUserWithRoles.setOrgCode("test"); + remoteUserWithRoles.setOrgManagerUserId("test"); + remoteUserWithRoles.setJobTitle("test"); + remoteUserWithRoles.setLoginId("test"); + remoteUserWithRoles.setActive(false); + remoteUserWithRoles.setRoles(roles); + + return remoteUserWithRoles; + } + + @Test + public void remoteUserWithRolesTest(){ + RemoteUserWithRoles remoteUserWithRoles = mockRemoteUserWithRoles(); + + assertEquals(remoteUserWithRoles.getOrgId(), new Long(1)); + assertEquals(remoteUserWithRoles.getManagerId(), new Long(1)); + assertEquals(remoteUserWithRoles.getFirstName(), "test"); + assertEquals(remoteUserWithRoles.getMiddleInitial(), "test"); + assertEquals(remoteUserWithRoles.getLastName(), "test"); + assertEquals(remoteUserWithRoles.getPhone(), "test"); + assertEquals(remoteUserWithRoles.getEmail(), "test"); + assertEquals(remoteUserWithRoles.getHrid(), "test"); + assertEquals(remoteUserWithRoles.getOrgUserId(), "test"); + assertEquals(remoteUserWithRoles.getOrgCode(), "test"); + assertEquals(remoteUserWithRoles.getOrgManagerUserId(), "test"); + assertEquals(remoteUserWithRoles.getJobTitle(), "test"); + assertEquals(remoteUserWithRoles.getLoginId(), "test"); + assertEquals(remoteUserWithRoles.getActive(), false); + assertEquals(remoteUserWithRoles.getRoles().size(), 1); + assertEquals(remoteUserWithRoles.toString(), "RemoteUserWithRoles [orgId=1, managerId=1, firstName=test, middleInitial=test, lastName=test, phone=test, " + + "email=test, hrid=test, orgUserId=test, orgCode=test, orgManagerUserId=test, jobTitle=test, loginId=test, active=false, roles=[RemoteRole [id=1, name=test]]]"); + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/RoleInAppForUserTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/RoleInAppForUserTest.java new file mode 100644 index 00000000..66624c2a --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/RoleInAppForUserTest.java @@ -0,0 +1,37 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.RoleInAppForUser; + +public class RoleInAppForUserTest { + + public RoleInAppForUser mockRoleInAppForUser(){ + RoleInAppForUser roleInAppForUser = new RoleInAppForUser((long)1 , "test"); + roleInAppForUser.setRoleId((long)1); + roleInAppForUser.setRoleName("test"); + roleInAppForUser.setIsApplied(false); + + return roleInAppForUser; + } + + @Test + public void roleInAppForUserTest(){ + RoleInAppForUser roleInAppForUser = mockRoleInAppForUser(); + + RoleInAppForUser roleInAppForUser1 = new RoleInAppForUser((long)1 , "test"); + roleInAppForUser1.setRoleId((long)1); + roleInAppForUser1.setRoleName("test"); + roleInAppForUser1.setIsApplied(false); + + assertEquals(roleInAppForUser.getRoleId(), new Long(1)); + assertEquals(roleInAppForUser.getRoleName(), "test"); + assertEquals(roleInAppForUser.getIsApplied(), false); + + assertEquals(roleInAppForUser.toString(), "RoleInAppForUser [roleId=1, roleName=test, isApplied=false]"); + assertTrue(roleInAppForUser.equals(roleInAppForUser1)); + assertEquals(roleInAppForUser.hashCode(), roleInAppForUser1.hashCode()); + //constructor + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/UserApplicationRolesTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/UserApplicationRolesTest.java new file mode 100644 index 00000000..632eeb4f --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/UserApplicationRolesTest.java @@ -0,0 +1,58 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.RemoteRole; +import org.openecomp.portalapp.portal.transport.UserApplicationRoles; + +public class UserApplicationRolesTest { + + public UserApplicationRoles mockUserApplicationRoles(){ + UserApplicationRoles userApplicationRoles = new UserApplicationRoles(); + + List<RemoteRole> roles = new ArrayList<RemoteRole>(); + RemoteRole remoteRole = new RemoteRole(); + remoteRole.setId((long)1); + remoteRole.setName("test"); + roles.add(remoteRole); + + userApplicationRoles.setAppId((long)1); + userApplicationRoles.setOrgUserId("test"); + userApplicationRoles.setFirstName("test"); + userApplicationRoles.setLastName("test"); + userApplicationRoles.setRoles(roles); + + return userApplicationRoles; + } + + @Test + public void userApplicationRolesTest(){ + UserApplicationRoles userApplicationRoles = mockUserApplicationRoles(); + + UserApplicationRoles userApplicationRoles1 = new UserApplicationRoles(); + + List<RemoteRole> roles = new ArrayList<RemoteRole>(); + RemoteRole remoteRole = new RemoteRole(); + remoteRole.setId((long)1); + remoteRole.setName("test"); + roles.add(remoteRole); + + userApplicationRoles1.setAppId((long)1); + userApplicationRoles1.setOrgUserId("test"); + userApplicationRoles1.setFirstName("test"); + userApplicationRoles1.setLastName("test"); + userApplicationRoles1.setRoles(roles); + + assertEquals(userApplicationRoles.getAppId(), userApplicationRoles1.getAppId()); + assertEquals(userApplicationRoles.getOrgUserId(), userApplicationRoles1.getOrgUserId()); + assertEquals(userApplicationRoles.getFirstName(), userApplicationRoles1.getFirstName()); + assertEquals(userApplicationRoles.getLastName(), userApplicationRoles1.getLastName()); + assertEquals(userApplicationRoles.getRoles(), userApplicationRoles1.getRoles()); + + + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/UserWithNameSurnameTitleTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/UserWithNameSurnameTitleTest.java new file mode 100644 index 00000000..7267dcde --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/UserWithNameSurnameTitleTest.java @@ -0,0 +1,19 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.UserWithNameSurnameTitle; + +public class UserWithNameSurnameTitleTest { + + @Test + public void userWithNameSurnameTitleTest(){ + + UserWithNameSurnameTitle userWithNameSurnameTitle = new UserWithNameSurnameTitle("test", "test", "test", "test"); + + assertEquals(userWithNameSurnameTitle, new UserWithNameSurnameTitle("test", "test", "test", "test")); + assertEquals(userWithNameSurnameTitle.hashCode(), new UserWithNameSurnameTitle("test", "test", "test", "test").hashCode()); + assertTrue(userWithNameSurnameTitle.equals(new UserWithNameSurnameTitle("test", "test", "test", "test"))); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/WidgetCatalogPersonalizationTest.java b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/WidgetCatalogPersonalizationTest.java new file mode 100644 index 00000000..6681d0a4 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/openecomp/portalapp/portal/transport/WidgetCatalogPersonalizationTest.java @@ -0,0 +1,25 @@ +package org.openecomp.portalapp.portal.transport; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.openecomp.portalapp.portal.transport.WidgetCatalogPersonalization; + +public class WidgetCatalogPersonalizationTest { + + public WidgetCatalogPersonalization mockWidgetCatalogPersonalization(){ + WidgetCatalogPersonalization widgetCatalogPersonalization = new WidgetCatalogPersonalization(); + + widgetCatalogPersonalization.setWidgetId((long)1); + widgetCatalogPersonalization.setSelect(false); + return widgetCatalogPersonalization; + } + + @Test + public void widgetCatalogPersonalizationTest(){ + WidgetCatalogPersonalization widgetCatalogPersonalization = mockWidgetCatalogPersonalization(); + + assertEquals(widgetCatalogPersonalization.getWidgetId(), new Long(1)); + assertEquals(widgetCatalogPersonalization.getSelect(), false); + } +} |