2  * ================================================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017 AT&T Intellectual Property
 
   6  * ================================================================================
 
   7  * Licensed under the Apache License, Version 2.0 (the "License");
 
   8  * you may not use this file except in compliance with the License.
 
   9  * You may obtain a copy of the License at
 
  11  *      http://www.apache.org/licenses/LICENSE-2.0
 
  13  * Unless required by applicable law or agreed to in writing, software
 
  14  * distributed under the License is distributed on an "AS IS" BASIS,
 
  15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  16  * See the License for the specific language governing permissions and
 
  17  * limitations under the License.
 
  18  * ================================================================================
 
  20 package org.openecomp.portalapp.portal.controller;
 
  22 import java.io.IOException;
 
  23 import java.util.ArrayList;
 
  24 import java.util.HashMap;
 
  25 import java.util.List;
 
  28 import javax.servlet.http.HttpServletRequest;
 
  29 import javax.servlet.http.HttpServletResponse;
 
  31 import org.openecomp.portalapp.controller.EPRestrictedRESTfulBaseController;
 
  32 import org.openecomp.portalapp.portal.domain.SharedContext;
 
  33 import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
 
  34 import org.openecomp.portalapp.portal.service.SharedContextService;
 
  35 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
 
  36 import org.openecomp.portalapp.portal.utils.PortalConstants;
 
  37 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
 
  38 import org.springframework.beans.factory.annotation.Autowired;
 
  39 import org.springframework.context.annotation.Configuration;
 
  40 import org.springframework.context.annotation.EnableAspectJAutoProxy;
 
  41 import org.springframework.http.HttpStatus;
 
  42 import org.springframework.web.bind.annotation.ExceptionHandler;
 
  43 import org.springframework.web.bind.annotation.RequestBody;
 
  44 import org.springframework.web.bind.annotation.RequestMapping;
 
  45 import org.springframework.web.bind.annotation.RequestMethod;
 
  46 import org.springframework.web.bind.annotation.RequestParam;
 
  47 import org.springframework.web.bind.annotation.RestController;
 
  49 import com.fasterxml.jackson.core.JsonProcessingException;
 
  50 import com.fasterxml.jackson.databind.ObjectMapper;
 
  52 import io.swagger.annotations.ApiOperation;
 
  55  * The shared-context feature allows onboarded applications to share data among
 
  56  * themselves easily for a given session. It basically implements a Java map:
 
  57  * put or get a key-value pair within a map identified by a session ID.
 
  59  * This REST endpoint listens on the Portal app server and answers requests made
 
  60  * by back-end application servers. Reads and writes values to the database
 
  61  * using a Hibernate service to ensure all servers in a high-availability
 
  62  * cluster see the same data.
 
  66 @RequestMapping(PortalConstants.REST_AUX_API + "/context")
 
  67 @EnableAspectJAutoProxy
 
  69 public class SharedContextRestController extends EPRestrictedRESTfulBaseController {
 
  72          * Model for a one-element JSON object returned by many methods.
 
  74         class SharedContextJsonResponse {
 
  79          * Access to the database
 
  82         private SharedContextService contextService;
 
  85          * Logger for debug etc.
 
  87         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextRestController.class);
 
  90          * Reusable JSON (de)serializer
 
  92         private final ObjectMapper mapper = new ObjectMapper();
 
  95          * Gets a value for the specified context and key (RESTful service method).
 
  98          *            HTTP servlet request
 
 100          *            ID that identifies the context, usually the ECOMP Portal
 
 103          *            Key for the key-value pair to fetch
 
 104          * @return JSON with shared context object; response=null if not found.
 
 108         @ApiOperation(value = "Gets a value for the specified context and key.", response = SharedContext.class)
 
 109         @RequestMapping(value = { "/get" }, method = RequestMethod.GET, produces = "application/json")
 
 110         public String getContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey)
 
 113                 logger.debug(EELFLoggerDelegate.debugLogger, "getContext for ID " + context_id + ", key " + ckey);
 
 114                 if (context_id == null || ckey == null)
 
 115                         throw new Exception("Received null for context_id and/or ckey");
 
 117                 SharedContext context = contextService.getSharedContext(context_id, ckey);
 
 118                 String jsonResponse = "";
 
 120                         jsonResponse = convertResponseToJSON(context);
 
 122                         jsonResponse = mapper.writeValueAsString(context);
 
 128          * Gets user information for the specified context (RESTful service method).
 
 131          *            HTTP servlet request
 
 133          *            ID that identifies the context, usually the ECOMP Portal
 
 135          * @return List of shared-context objects as JSON; should have user's first
 
 136          *         name, last name and email address; null if none found
 
 140         @ApiOperation(value = "Gets user information for the specified context.", response = SharedContext.class, responseContainer = "List")
 
 141         @RequestMapping(value = { "/get_user" }, method = RequestMethod.GET, produces = "application/json")
 
 142         public String getUserContext(HttpServletRequest request, @RequestParam String context_id) throws Exception {
 
 144                 logger.debug(EELFLoggerDelegate.debugLogger, "getUserContext for ID " + context_id);
 
 145                 if (context_id == null)
 
 146                         throw new Exception("Received null for context_id");
 
 148                 List<SharedContext> listSharedContext = new ArrayList<SharedContext>();
 
 149                 SharedContext firstNameContext = contextService.getSharedContext(context_id,
 
 150                                 EPCommonSystemProperties.USER_FIRST_NAME);
 
 151                 SharedContext lastNameContext = contextService.getSharedContext(context_id,
 
 152                                 EPCommonSystemProperties.USER_LAST_NAME);
 
 153                 SharedContext emailContext = contextService.getSharedContext(context_id, EPCommonSystemProperties.USER_EMAIL);
 
 154                 SharedContext attuidContext = contextService.getSharedContext(context_id,
 
 155                                 EPCommonSystemProperties.USER_ORG_USERID);
 
 156                 if (firstNameContext != null)
 
 157                         listSharedContext.add(firstNameContext);
 
 158                 if (lastNameContext != null)
 
 159                         listSharedContext.add(lastNameContext);
 
 160                 if (emailContext != null)
 
 161                         listSharedContext.add(emailContext);
 
 162                 if (attuidContext != null)
 
 163                         listSharedContext.add(attuidContext);
 
 164                 String jsonResponse = convertResponseToJSON(listSharedContext);
 
 169          * Tests for presence of the specified key in the specified context (RESTful
 
 173          *            HTTP servlet request
 
 175          *            ID that identifies the context, usually the ECOMP Portal
 
 178          *            Key for the key-value pair to test
 
 179          * @return JSON with result indicating whether the context and key were
 
 184         @ApiOperation(value = "Tests for presence of the specified key in the specified context.", response = SharedContextJsonResponse.class)
 
 185         @RequestMapping(value = { "/check" }, method = RequestMethod.GET, produces = "application/json")
 
 186         public String checkContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey)
 
 189                 logger.debug(EELFLoggerDelegate.debugLogger, "checkContext for " + context_id + ", key " + ckey);
 
 190                 if (context_id == null || ckey == null)
 
 191                         throw new Exception("Received null for contextId and/or key");
 
 193                 String response = null;
 
 194                 SharedContext context = contextService.getSharedContext(context_id, ckey);
 
 198                 String jsonResponse = convertResponseToJSON(response);
 
 203          * Removes the specified key in the specified context (RESTful service
 
 207          *            HTTP servlet request
 
 209          *            ID that identifies the context, usually the ECOMP Portal
 
 212          *            Key for the key-value pair to remove
 
 213          * @return JSON with result indicating whether the context and key were
 
 218         @ApiOperation(value = "Removes the specified key in the specified context.", response = SharedContextJsonResponse.class)
 
 219         @RequestMapping(value = { "/remove" }, method = RequestMethod.GET, produces = "application/json")
 
 220         public String removeContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey)
 
 223                 logger.debug(EELFLoggerDelegate.debugLogger, "removeContext for " + context_id + ", key " + ckey);
 
 224                 if (context_id == null || ckey == null)
 
 225                         throw new Exception("Received null for contextId and/or key");
 
 227                 SharedContext context = contextService.getSharedContext(context_id, ckey);
 
 228                 String response = null;
 
 229                 if (context != null) {
 
 230                         contextService.deleteSharedContext(context);
 
 231                         response = "removed";
 
 234                 String jsonResponse = convertResponseToJSON(response);
 
 239          * Clears all key-value pairs in the specified context (RESTful service
 
 243          *            HTTP servlet request
 
 245          *            ID that identifies the context, usually the ECOMP Portal
 
 247          * @return JSON with result indicating the number of key-value pairs
 
 252         @ApiOperation(value = "Clears all key-value pairs in the specified context.", response = SharedContextJsonResponse.class)
 
 253         @RequestMapping(value = { "/clear" }, method = RequestMethod.GET, produces = "application/json")
 
 254         public String clearContext(HttpServletRequest request, @RequestParam String context_id) throws Exception {
 
 256                 logger.debug(EELFLoggerDelegate.debugLogger, "clearContext for " + context_id);
 
 257                 if (context_id == null)
 
 258                         throw new Exception("clearContext: Received null for contextId");
 
 260                 int count = contextService.deleteSharedContexts(context_id);
 
 261                 String jsonResponse = convertResponseToJSON(Integer.toString(count));
 
 266          * Sets a context value for the specified context and key (RESTful service
 
 267          * method). Creates the context if no context with the specified ID-key pair
 
 268          * exists, overwrites the value if it exists already.
 
 271          *            HTTP servlet request
 
 273          *            JSON block with these tag-value pairs:
 
 275          *            <LI>context_id: ID that identifies the context
 
 276          *            <LI>ckey: Key for the key-value pair to store
 
 277          *            <LI>cvalue: Value to store
 
 279          * @return JSON with result indicating whether the value was added (key not
 
 280          *         previously known) or replaced (key previously known).
 
 284         @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)
 
 285         @RequestMapping(value = { "/set" }, method = RequestMethod.POST, produces = "application/json")
 
 286         public String setContext(HttpServletRequest request, @RequestBody String userJson) throws Exception {
 
 288                 @SuppressWarnings("unchecked")
 
 289                 Map<String, Object> userData = mapper.readValue(userJson, Map.class);
 
 290                 // Use column names as JSON tags
 
 291                 final String contextId = (String) userData.get("context_id");
 
 292                 final String key = (String) userData.get("ckey");
 
 293                 final String value = (String) userData.get("cvalue");
 
 294                 if (contextId == null || key == null)
 
 295                         throw new Exception("setContext: received null for contextId and/or key");
 
 297                 logger.debug(EELFLoggerDelegate.debugLogger, "setContext: ID " + contextId + ", key " + key + "->" + value);
 
 298                 String response = null;
 
 299                 SharedContext existing = contextService.getSharedContext(contextId, key);
 
 300                 if (existing == null) {
 
 301                         contextService.addSharedContext(contextId, key, value);
 
 303                         existing.setCvalue(value);
 
 304                         contextService.saveSharedContext(existing);
 
 306                 response = existing == null ? "added" : "replaced";
 
 307                 String jsonResponse = convertResponseToJSON(response);
 
 312          * Creates a two-element JSON object tagged "response".
 
 314          * @param responseBody
 
 315          * @return JSON object as String
 
 316          * @throws JsonProcessingException
 
 318         private String convertResponseToJSON(String responseBody) throws JsonProcessingException {
 
 319                 Map<String, String> responseMap = new HashMap<String, String>();
 
 320                 responseMap.put("response", responseBody);
 
 321                 String response = mapper.writeValueAsString(responseMap);
 
 326          * Converts a list of SharedContext objects to a JSON array.
 
 329          * @return JSON array as String
 
 330          * @throws JsonProcessingException
 
 332         private String convertResponseToJSON(List<SharedContext> contextList) throws JsonProcessingException {
 
 333                 String jsonArray = mapper.writeValueAsString(contextList);
 
 338          * Creates a JSON object with the content of the shared context; null is ok.
 
 341          * @return tag "response" with collection of context object's fields
 
 342          * @throws JsonProcessingException
 
 344         private String convertResponseToJSON(SharedContext context) throws JsonProcessingException {
 
 345                 Map<String, Object> responseMap = new HashMap<String, Object>();
 
 346                 responseMap.put("response", context);
 
 347                 String responseBody = mapper.writeValueAsString(responseMap);
 
 352          * Handles any exception thrown by a method in this controller.
 
 357          *            HttpServletResponse
 
 358          * @throws IOException
 
 360         @ExceptionHandler(Exception.class)
 
 361         protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException {
 
 362                 logger.error(EELFLoggerDelegate.errorLogger, "handleBadRequest caught exception", e);
 
 363                 response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());