ControllerUtils tests and improvements 82/83082/1
authorMichal Kabaj <michal.kabaj@nokia.com>
Fri, 22 Mar 2019 23:10:14 +0000 (00:10 +0100)
committerMichal Kabaj <michal.kabaj@nokia.com>
Fri, 22 Mar 2019 23:10:14 +0000 (00:10 +0100)
- added junits
- Injecting SystemPropertiesWrapper via constructor
- switched extractUserId is now instance method instead
of static

Change-Id: Ic706b780c64248e44207a1dee723981a4ca7ed74
Issue-ID: VID-449
Signed-off-by: Michal Kabaj <michal.kabaj@nokia.com>
vid-app-common/src/main/java/org/onap/vid/controller/AaiController.java
vid-app-common/src/main/java/org/onap/vid/controller/AsyncInstantiationController.java
vid-app-common/src/main/java/org/onap/vid/controller/ControllersUtils.java
vid-app-common/src/main/java/org/onap/vid/controller/OperationalEnvironmentController.java
vid-app-common/src/test/java/org/onap/vid/controller/ControllersUtilsTest.java [new file with mode: 0644]

index a8e1e2b..e2a9140 100644 (file)
@@ -41,6 +41,7 @@ import org.onap.vid.roles.Role;
 import org.onap.vid.roles.RoleProvider;
 import org.onap.vid.roles.RoleValidator;
 import org.onap.vid.services.AaiService;
+import org.onap.vid.utils.SystemPropertiesWrapper;
 import org.onap.vid.utils.Unchecked;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.HttpStatus;
@@ -96,9 +97,10 @@ public class AaiController extends RestrictedBaseController {
     private AaiService aaiService;
     @Autowired
     private RoleProvider roleProvider;
-
     @Autowired
     private AAIRestInterface aaiRestInterface;
+    @Autowired
+    private SystemPropertiesWrapper systemPropertiesWrapper;
 
     /**
      * Welcome method.
@@ -140,7 +142,7 @@ public class AaiController extends RestrictedBaseController {
     @RequestMapping(value = {"/getuserID"}, method = RequestMethod.GET)
     public ResponseEntity<String> getUserID(HttpServletRequest request) {
 
-        String userId = ControllersUtils.extractUserId(request);
+        String userId = new ControllersUtils(systemPropertiesWrapper).extractUserId(request);
 
         return new ResponseEntity<>(userId, HttpStatus.OK);
     }
index a204d3a..081e3c6 100644 (file)
@@ -31,6 +31,7 @@ import org.onap.vid.model.serviceInstantiation.ServiceInstantiation;
 import org.onap.vid.mso.MsoResponseWrapper2;
 import org.onap.vid.services.AsyncInstantiationBusinessLogic;
 import org.onap.vid.services.AuditService;
+import org.onap.vid.utils.SystemPropertiesWrapper;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
 
@@ -48,6 +49,7 @@ public class AsyncInstantiationController extends VidRestrictedBaseController {
     public static final String ASYNC_INSTANTIATION = "asyncInstantiation";
 
     protected final AsyncInstantiationBusinessLogic asyncInstantiationBL;
+    private final SystemPropertiesWrapper systemPropertiesWrapper;
 
     protected ObjectMapper objectMapper = new ObjectMapper();
 
@@ -55,8 +57,9 @@ public class AsyncInstantiationController extends VidRestrictedBaseController {
     protected AuditService auditService;
 
     @Autowired
-    public AsyncInstantiationController(AsyncInstantiationBusinessLogic asyncInstantiationBL) {
+    public AsyncInstantiationController(AsyncInstantiationBusinessLogic asyncInstantiationBL, SystemPropertiesWrapper systemPropertiesWrapper) {
         this.asyncInstantiationBL = asyncInstantiationBL;
+        this.systemPropertiesWrapper = systemPropertiesWrapper;
     }
 
     @ExceptionHandler(OperationNotAllowedException.class)
@@ -84,7 +87,7 @@ public class AsyncInstantiationController extends VidRestrictedBaseController {
         catch (Exception e) {
             LOGGER.error(EELFLoggerDelegate.errorLogger, "failed to log incoming ServiceInstantiation request ", e);
         }
-        String userId = ControllersUtils.extractUserId(httpServletRequest);
+        String userId = new ControllersUtils(systemPropertiesWrapper).extractUserId(httpServletRequest);
         List<UUID> uuids =  asyncInstantiationBL.pushBulkJob(request, userId);
 
         return new MsoResponseWrapper2(200, uuids);
index 7139b29..befbe03 100644 (file)
@@ -3,13 +3,14 @@
  * VID
  * ================================================================================
  * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nokia. 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.
 
 package org.onap.vid.controller;
 
+import static org.onap.vid.utils.Logging.getMethodCallerName;
+
+import java.util.Optional;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import javax.ws.rs.WebApplicationException;
 import org.apache.commons.lang3.exception.ExceptionUtils;
 import org.onap.portalsdk.core.domain.User;
 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
 import org.onap.portalsdk.core.util.SystemProperties;
 import org.onap.vid.model.ExceptionResponse;
+import org.onap.vid.utils.SystemPropertiesWrapper;
 import org.springframework.http.ResponseEntity;
 
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-import javax.ws.rs.WebApplicationException;
-
-import static org.onap.vid.utils.Logging.getMethodCallerName;
+public final class ControllersUtils {
 
-public class ControllersUtils {
+    private final SystemPropertiesWrapper systemPropertiesWrapper;
 
-
-    public static String extractUserId(HttpServletRequest request) {
-        String userId = "";
-        HttpSession session = request.getSession();
-        if (session != null) {
-            User user = (User) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
-            if (user != null) {
-                //userId = user.getHrid();
-                userId = user.getLoginId();
-                if (userId == null)
-                    userId = user.getOrgUserId();
-            }
-        }
-        return userId;
+    public ControllersUtils(SystemPropertiesWrapper systemPropertiesWrapper) {
+        this.systemPropertiesWrapper = systemPropertiesWrapper;
     }
 
     public static ExceptionResponse handleException(Exception e, EELFLoggerDelegate logger) {
@@ -62,4 +54,12 @@ public class ControllersUtils {
         return ResponseEntity.status(e.getResponse().getStatus()).body(ControllersUtils.handleException(e, logger));
     }
 
+    public String extractUserId(HttpServletRequest request) {
+        Optional<User> user = Optional.ofNullable(request.getSession())
+            .map((HttpSession he) -> (User) he
+                .getAttribute(systemPropertiesWrapper.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)));
+
+        return user.map(User::getLoginId).isPresent()
+            ? user.map(User::getLoginId).orElse("") : user.map(User::getOrgUserId).orElse("");
+    }
 }
index fe94dfd..a6778ad 100644 (file)
@@ -37,6 +37,7 @@ import org.onap.vid.mso.model.OperationalEnvironmentActivateInfo;
 import org.onap.vid.mso.model.OperationalEnvironmentDeactivateInfo;
 import org.onap.vid.mso.rest.OperationalEnvironment.OperationEnvironmentRequestDetails;
 import org.onap.vid.mso.rest.RequestDetails;
+import org.onap.vid.utils.SystemPropertiesWrapper;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.HttpStatus;
 import org.springframework.web.bind.MissingServletRequestParameterException;
@@ -60,20 +61,22 @@ public class OperationalEnvironmentController extends VidRestrictedBaseControlle
 
     private final MsoInterface restMso;
     private final MsoBusinessLogic msoBusinessLogic;
+    private final SystemPropertiesWrapper systemPropertiesWrapper;
 
     private static final Pattern RECOVERY_ACTION_MESSAGE_PATTERN = Pattern.compile("from String \"(.*)\": value not");
 
 
     @Autowired
-    public OperationalEnvironmentController(MsoBusinessLogic msoBusinessLogic, MsoInterface msoClientInterface) {
+    public OperationalEnvironmentController(MsoBusinessLogic msoBusinessLogic, MsoInterface msoClientInterface, SystemPropertiesWrapper systemPropertiesWrapper) {
         this.restMso = msoClientInterface;
         this.msoBusinessLogic = msoBusinessLogic;
+        this.systemPropertiesWrapper = systemPropertiesWrapper;
     }
 
     @RequestMapping(value = "/create", method = RequestMethod.POST)
     public MsoResponseWrapper2 createOperationalEnvironment(HttpServletRequest request, @RequestBody OperationalEnvironmentCreateBody operationalEnvironment) {
         debugStart(operationalEnvironment);
-        String userId = ControllersUtils.extractUserId(request);
+        String userId = new ControllersUtils(systemPropertiesWrapper).extractUserId(request);
         RequestDetailsWrapper<OperationEnvironmentRequestDetails> requestDetailsWrapper = msoBusinessLogic.convertParametersToRequestDetails(operationalEnvironment, userId);
         String path = msoBusinessLogic.getOperationalEnvironmentCreationPath();
 
@@ -94,7 +97,7 @@ public class OperationalEnvironmentController extends VidRestrictedBaseControlle
             throw new BadManifestException("Manifest structure is wrong");
         }
 
-        String userId = ControllersUtils.extractUserId(request);
+        String userId = new ControllersUtils(systemPropertiesWrapper).extractUserId(request);
 
         OperationalEnvironmentActivateInfo activateInfo = new OperationalEnvironmentActivateInfo(activateRequest, userId, operationalEnvironmentId);
         debugStart(activateInfo);
@@ -115,7 +118,7 @@ public class OperationalEnvironmentController extends VidRestrictedBaseControlle
 
         verifyIsNotEmpty(operationalEnvironmentId, "operationalEnvironment");
 
-        String userId = ControllersUtils.extractUserId(request);
+        String userId = new ControllersUtils(systemPropertiesWrapper).extractUserId(request);
 
         OperationalEnvironmentDeactivateInfo deactivateInfo = new OperationalEnvironmentDeactivateInfo(userId, operationalEnvironmentId);
         debugStart(deactivateInfo);
diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/ControllersUtilsTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/ControllersUtilsTest.java
new file mode 100644 (file)
index 0000000..f084b3d
--- /dev/null
@@ -0,0 +1,113 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2019 Nokia.
+ * ================================================================================
+ * 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.onap.vid.controller;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.BDDMockito.given;
+
+import javax.servlet.http.HttpServletRequest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Answers;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.vid.utils.SystemPropertiesWrapper;
+
+@RunWith(MockitoJUnitRunner.class)
+public class ControllersUtilsTest {
+
+    private static final String USER_ATTRIBUTE = "userAttribute";
+    @Mock
+    private SystemPropertiesWrapper systemPropertiesWrapper;
+    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
+    private HttpServletRequest httpServletRequest;
+
+    @Test
+    public void shouldExtractLoginIdAsUserId_fromHttpServletRequest() {
+        // GIVEN
+        String expectedUserId = "rootUser";
+        given(systemPropertiesWrapper.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).willReturn(USER_ATTRIBUTE);
+        User user = new User();
+        user.setLoginId(expectedUserId);
+        given(httpServletRequest.getSession().getAttribute(USER_ATTRIBUTE)).willReturn(user);
+
+        // WHEN
+        String loginId = new ControllersUtils(systemPropertiesWrapper).extractUserId(httpServletRequest);
+
+        // THEN
+        assertThat(loginId).isEqualTo(expectedUserId);
+    }
+
+    @Test
+    public void shouldExtractOrgUserIdAsUserId_fromHttpServletRequest_whenLoginIdIsNull() {
+        // GIVEN
+        String expectedUserId = "secondUser";
+        given(systemPropertiesWrapper.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).willReturn(USER_ATTRIBUTE);
+        User user = new User();
+        user.setOrgUserId(expectedUserId);
+        given(httpServletRequest.getSession().getAttribute(USER_ATTRIBUTE)).willReturn(user);
+
+        // WHEN
+        String loginId = new ControllersUtils(systemPropertiesWrapper).extractUserId(httpServletRequest);
+
+        // THEN
+        assertThat(loginId).isEqualTo(expectedUserId);
+    }
+
+    @Test
+    public void shouldReturnEmptyString_whenBothLoginIdAndOrgUserIdAreNull() {
+        // GIVEN
+        given(systemPropertiesWrapper.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).willReturn(USER_ATTRIBUTE);
+        given(httpServletRequest.getSession().getAttribute(USER_ATTRIBUTE)).willReturn(new User());
+
+        // WHEN
+        String loginId = new ControllersUtils(systemPropertiesWrapper).extractUserId(httpServletRequest);
+
+        // THEN
+        assertThat(loginId).isEmpty();
+    }
+
+    @Test
+    public void shouldReturnEmptyString_whenSessionIsNull() {
+        // GIVEN
+        given(httpServletRequest.getSession()).willReturn(null);
+
+        // WHEN
+        String loginId = new ControllersUtils(systemPropertiesWrapper).extractUserId(httpServletRequest);
+
+        // THEN
+        assertThat(loginId).isEmpty();
+    }
+
+    @Test
+    public void shouldReturnEmptyString_whenUserIsNull() {
+        // GIVEN
+        given(systemPropertiesWrapper.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).willReturn(USER_ATTRIBUTE);
+        given(httpServletRequest.getSession().getAttribute(USER_ATTRIBUTE)).willReturn(null);
+
+        // WHEN
+        String loginId = new ControllersUtils(systemPropertiesWrapper).extractUserId(httpServletRequest);
+
+        // THEN
+        assertThat(loginId).isEmpty();
+    }
+}
\ No newline at end of file