Merge "Issue-ID: PORTAL-913 optimization in git clone using --depth"
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / controller / SharedContextRestController.java
index 9a68496..232b691 100644 (file)
@@ -33,7 +33,7 @@
  *
  * ============LICENSE_END============================================
  *
- * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * 
  */
 package org.onap.portalapp.portal.controller;
 
@@ -48,10 +48,13 @@ import javax.servlet.http.HttpServletResponse;
 
 import org.onap.portalapp.controller.EPRestrictedRESTfulBaseController;
 import org.onap.portalapp.portal.domain.SharedContext;
+import org.onap.portalapp.portal.exceptions.NotValidDataException;
 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
 import org.onap.portalapp.portal.service.SharedContextService;
 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
 import org.onap.portalapp.portal.utils.PortalConstants;
+import org.onap.portalapp.validation.DataValidator;
+import org.onap.portalapp.validation.SecureString;
 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Configuration;
@@ -60,6 +63,8 @@ import org.springframework.http.HttpStatus;
 import org.springframework.web.bind.annotation.ExceptionHandler;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.RestController;
@@ -85,37 +90,24 @@ import io.swagger.annotations.ApiOperation;
 @EnableAspectJAutoProxy
 @EPAuditLog
 public class SharedContextRestController extends EPRestrictedRESTfulBaseController {
+       private static final DataValidator dataValidator = new DataValidator();
+       private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextRestController.class);
+       private static final ObjectMapper mapper = new ObjectMapper();
 
-       /**
-        * Model for a one-element JSON object returned by many methods.
-        */
-       class SharedContextJsonResponse {
-               String response;
-       }
-
-       /**
-        * Access to the database
-        */
-       @Autowired
        private SharedContextService contextService;
 
-       /**
-        * Logger for debug etc.
-        */
-       private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextRestController.class);
-
-       /**
-        * Reusable JSON (de)serializer
-        */
-       private final ObjectMapper mapper = new ObjectMapper();
+       @Autowired
+       public SharedContextRestController(SharedContextService contextService) {
+               this.contextService = contextService;
+       }
 
        /**
         * Gets a value for the specified context and key (RESTful service method).
-        * 
+        *
         * @param request
         *            HTTP servlet request
         * @param context_id
-        *            ID that identifies the context, usually the ECOMP Portal
+        *            ID that identifies the context, usually the ONAP Portal
         *            session key.
         * @param ckey
         *            Key for the key-value pair to fetch
@@ -124,16 +116,21 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
         *             on bad arguments
         */
        @ApiOperation(value = "Gets a value for the specified context and key.", response = SharedContext.class)
-       @RequestMapping(value = { "/get" }, method = RequestMethod.GET, produces = "application/json")
+       @GetMapping(value = { "/get" }, produces = "application/json")
        public String getContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey)
                        throws Exception {
-
                logger.debug(EELFLoggerDelegate.debugLogger, "getContext for ID " + context_id + ", key " + ckey);
                if (context_id == null || ckey == null)
                        throw new Exception("Received null for context_id and/or ckey");
+               SecureString secureContextId = new SecureString(context_id);
+               SecureString secureCKey = new SecureString(ckey);
+
+               if(!dataValidator.isValid(secureContextId) || !dataValidator.isValid(secureCKey)){
+                       throw new NotValidDataException("Received not valid for context_id and/or ckey");
+               }
 
                SharedContext context = contextService.getSharedContext(context_id, ckey);
-               String jsonResponse = "";
+               String jsonResponse;
                if (context == null)
                        jsonResponse = convertResponseToJSON(context);
                else
@@ -144,11 +141,11 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
 
        /**
         * Gets user information for the specified context (RESTful service method).
-        * 
+        *
         * @param request
         *            HTTP servlet request
         * @param context_id
-        *            ID that identifies the context, usually the ECOMP Portal
+        *            ID that identifies the context, usually the ONAP Portal
         *            session key.
         * @return List of shared-context objects as JSON; should have user's first
         *         name, last name and email address; null if none found
@@ -156,14 +153,17 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
         *             on bad arguments
         */
        @ApiOperation(value = "Gets user information for the specified context.", response = SharedContext.class, responseContainer = "List")
-       @RequestMapping(value = { "/get_user" }, method = RequestMethod.GET, produces = "application/json")
+       @GetMapping(value = { "/get_user" }, produces = "application/json")
        public String getUserContext(HttpServletRequest request, @RequestParam String context_id) throws Exception {
 
                logger.debug(EELFLoggerDelegate.debugLogger, "getUserContext for ID " + context_id);
                if (context_id == null)
                        throw new Exception("Received null for context_id");
+               SecureString secureContextId = new SecureString(context_id);
+               if (!dataValidator.isValid(secureContextId))
+                       throw new NotValidDataException("context_id is not valid");
 
-               List<SharedContext> listSharedContext = new ArrayList<SharedContext>();
+               List<SharedContext> listSharedContext = new ArrayList<>();
                SharedContext firstNameContext = contextService.getSharedContext(context_id,
                                EPCommonSystemProperties.USER_FIRST_NAME);
                SharedContext lastNameContext = contextService.getSharedContext(context_id,
@@ -179,18 +179,17 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
                        listSharedContext.add(emailContext);
                if (orgUserIdContext != null)
                        listSharedContext.add(orgUserIdContext);
-               String jsonResponse = convertResponseToJSON(listSharedContext);
-               return jsonResponse;
+               return convertResponseToJSON(listSharedContext);
        }
 
        /**
         * Tests for presence of the specified key in the specified context (RESTful
         * service method).
-        * 
+        *
         * @param request
         *            HTTP servlet request
         * @param context_id
-        *            ID that identifies the context, usually the ECOMP Portal
+        *            ID that identifies the context, usually the ONAP Portal
         *            session key.
         * @param ckey
         *            Key for the key-value pair to test
@@ -200,7 +199,7 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
         *             on bad arguments
         */
        @ApiOperation(value = "Tests for presence of the specified key in the specified context.", response = SharedContextJsonResponse.class)
-       @RequestMapping(value = { "/check" }, method = RequestMethod.GET, produces = "application/json")
+       @GetMapping(value = { "/check" }, produces = "application/json")
        public String checkContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey)
                        throws Exception {
 
@@ -208,23 +207,28 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
                if (context_id == null || ckey == null)
                        throw new Exception("Received null for contextId and/or key");
 
+               SecureString secureContextId = new SecureString(context_id);
+               SecureString secureCKey = new SecureString(ckey);
+
+               if (!dataValidator.isValid(secureContextId) || !dataValidator.isValid(secureCKey))
+                       throw new NotValidDataException("Not valid data for contextId and/or key");
+
                String response = null;
                SharedContext context = contextService.getSharedContext(context_id, ckey);
                if (context != null)
                        response = "exists";
 
-               String jsonResponse = convertResponseToJSON(response);
-               return jsonResponse;
+               return convertResponseToJSON(response);
        }
 
        /**
         * Removes the specified key in the specified context (RESTful service
         * method).
-        * 
+        *
         * @param request
         *            HTTP servlet request
         * @param context_id
-        *            ID that identifies the context, usually the ECOMP Portal
+        *            ID that identifies the context, usually the ONAP Portal
         *            session key.
         * @param ckey
         *            Key for the key-value pair to remove
@@ -234,7 +238,7 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
         *             on bad arguments
         */
        @ApiOperation(value = "Removes the specified key in the specified context.", response = SharedContextJsonResponse.class)
-       @RequestMapping(value = { "/remove" }, method = RequestMethod.GET, produces = "application/json")
+       @GetMapping(value = { "/remove" }, produces = "application/json")
        public String removeContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey)
                        throws Exception {
 
@@ -242,6 +246,12 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
                if (context_id == null || ckey == null)
                        throw new Exception("Received null for contextId and/or key");
 
+               SecureString secureContextId = new SecureString(context_id);
+               SecureString secureCKey = new SecureString(ckey);
+
+               if (!dataValidator.isValid(secureContextId) || !dataValidator.isValid(secureCKey))
+                       throw new NotValidDataException("Not valid data for contextId and/or key");
+
                SharedContext context = contextService.getSharedContext(context_id, ckey);
                String response = null;
                if (context != null) {
@@ -249,18 +259,17 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
                        response = "removed";
                }
 
-               String jsonResponse = convertResponseToJSON(response);
-               return jsonResponse;
+               return convertResponseToJSON(response);
        }
 
        /**
         * Clears all key-value pairs in the specified context (RESTful service
         * method).
-        * 
+        *
         * @param request
         *            HTTP servlet request
         * @param context_id
-        *            ID that identifies the context, usually the ECOMP Portal
+        *            ID that identifies the context, usually the ONAP Portal
         *            session key.
         * @return JSON with result indicating the number of key-value pairs
         *         removed.
@@ -268,23 +277,27 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
         *             on bad arguments
         */
        @ApiOperation(value = "Clears all key-value pairs in the specified context.", response = SharedContextJsonResponse.class)
-       @RequestMapping(value = { "/clear" }, method = RequestMethod.GET, produces = "application/json")
+       @GetMapping(value = { "/clear" }, produces = "application/json")
        public String clearContext(HttpServletRequest request, @RequestParam String context_id) throws Exception {
 
                logger.debug(EELFLoggerDelegate.debugLogger, "clearContext for " + context_id);
                if (context_id == null)
                        throw new Exception("clearContext: Received null for contextId");
 
+               SecureString secureContextId = new SecureString(context_id);
+
+               if (!dataValidator.isValid(secureContextId))
+                       throw new NotValidDataException("Not valid data for contextId");
+
                int count = contextService.deleteSharedContexts(context_id);
-               String jsonResponse = convertResponseToJSON(Integer.toString(count));
-               return jsonResponse;
+               return convertResponseToJSON(Integer.toString(count));
        }
 
        /**
         * Sets a context value for the specified context and key (RESTful service
         * method). Creates the context if no context with the specified ID-key pair
         * exists, overwrites the value if it exists already.
-        * 
+        *
         * @param request
         *            HTTP servlet request
         * @param userJson
@@ -300,8 +313,13 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
         *             on bad arguments
         */
        @ApiOperation(value = "Sets a context value for the specified context and key. Creates the context if no context with the specified ID-key pair exists, overwrites the value if it exists already.", response = SharedContextJsonResponse.class)
-       @RequestMapping(value = { "/set" }, method = RequestMethod.POST, produces = "application/json")
+       @PostMapping(value = { "/set" }, produces = "application/json")
        public String setContext(HttpServletRequest request, @RequestBody String userJson) throws Exception {
+               if (userJson !=null){
+               SecureString secureUserJson = new SecureString(userJson);
+               if (!dataValidator.isValid(secureUserJson))
+                       throw new NotValidDataException("Not valid data for userJson");
+               }
 
                @SuppressWarnings("unchecked")
                Map<String, Object> userData = mapper.readValue(userJson, Map.class);
@@ -313,7 +331,7 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
                        throw new Exception("setContext: received null for contextId and/or key");
 
                logger.debug(EELFLoggerDelegate.debugLogger, "setContext: ID " + contextId + ", key " + key + "->" + value);
-               String response = null;
+               String response;
                SharedContext existing = contextService.getSharedContext(contextId, key);
                if (existing == null) {
                        contextService.addSharedContext(contextId, key, value);
@@ -322,53 +340,49 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
                        contextService.saveSharedContext(existing);
                }
                response = existing == null ? "added" : "replaced";
-               String jsonResponse = convertResponseToJSON(response);
-               return jsonResponse;
+               return convertResponseToJSON(response);
        }
 
        /**
         * Creates a two-element JSON object tagged "response".
-        * 
+        *
         * @param responseBody
         * @return JSON object as String
         * @throws JsonProcessingException
         */
        private String convertResponseToJSON(String responseBody) throws JsonProcessingException {
-               Map<String, String> responseMap = new HashMap<String, String>();
+               Map<String, String> responseMap = new HashMap<>();
                responseMap.put("response", responseBody);
-               String response = mapper.writeValueAsString(responseMap);
-               return response;
+               return mapper.writeValueAsString(responseMap);
        }
 
        /**
         * Converts a list of SharedContext objects to a JSON array.
-        * 
+        *
         * @param contextList
         * @return JSON array as String
         * @throws JsonProcessingException
         */
        private String convertResponseToJSON(List<SharedContext> contextList) throws JsonProcessingException {
-               String jsonArray = mapper.writeValueAsString(contextList);
-               return jsonArray;
+               return mapper.writeValueAsString(contextList);
        }
 
        /**
         * Creates a JSON object with the content of the shared context; null is ok.
-        * 
+        *
         * @param context
         * @return tag "response" with collection of context object's fields
         * @throws JsonProcessingException
         */
        private String convertResponseToJSON(SharedContext context) throws JsonProcessingException {
-               Map<String, Object> responseMap = new HashMap<String, Object>();
+               Map<String, Object> responseMap = new HashMap<>();
                responseMap.put("response", context);
-               String responseBody = mapper.writeValueAsString(responseMap);
-               return responseBody;
+               return mapper.writeValueAsString(responseMap);
        }
 
        /**
         * Handles any exception thrown by a method in this controller.
-        * 
+        *
         * @param e
         *            Exception
         * @param response
@@ -382,3 +396,7 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll
        }
 
 }
+class SharedContextJsonResponse {
+       String response;
+}
+