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 * ID that identifies the context, usually the ECOMP Portal
101 * Key for the key-value pair to fetch
102 * @return JSON with shared context object; response=null if not found.
104 @ApiOperation(value = "Gets a value for the specified context and key.", response = SharedContext.class)
105 @RequestMapping(value = { "/get" }, method = RequestMethod.GET, produces = "application/json")
106 public String getContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey)
109 logger.debug(EELFLoggerDelegate.debugLogger, "getContext for ID " + context_id + ", key " + ckey);
110 if (context_id == null || ckey == null)
111 throw new Exception("Received null for context_id and/or ckey");
113 SharedContext context = contextService.getSharedContext(context_id, ckey);
114 String jsonResponse = "";
116 jsonResponse = convertResponseToJSON(context);
118 jsonResponse = mapper.writeValueAsString(context);
124 * Gets user information for the specified context (RESTful service method).
127 * ID that identifies the context, usually the ECOMP Portal
130 * @return List of shared-context objects as JSON; should have user's first
131 * name, last name and email address; null if none found
133 @ApiOperation(value = "Gets user information for the specified context.", response = SharedContext.class, responseContainer = "List")
134 @RequestMapping(value = { "/get_user" }, method = RequestMethod.GET, produces = "application/json")
135 public String getUserContext(HttpServletRequest request, @RequestParam String context_id) throws Exception {
137 logger.debug(EELFLoggerDelegate.debugLogger, "getUserContext for ID " + context_id);
138 if (context_id == null)
139 throw new Exception("Received null for context_id");
141 List<SharedContext> listSharedContext = new ArrayList<SharedContext>();
142 SharedContext firstNameContext = contextService.getSharedContext(context_id,
143 EPCommonSystemProperties.USER_FIRST_NAME);
144 SharedContext lastNameContext = contextService.getSharedContext(context_id,
145 EPCommonSystemProperties.USER_LAST_NAME);
146 SharedContext emailContext = contextService.getSharedContext(context_id, EPCommonSystemProperties.USER_EMAIL);
147 SharedContext attuidContext = contextService.getSharedContext(context_id,
148 EPCommonSystemProperties.USER_ORG_USERID);
149 if (firstNameContext != null)
150 listSharedContext.add(firstNameContext);
151 if (lastNameContext != null)
152 listSharedContext.add(lastNameContext);
153 if (emailContext != null)
154 listSharedContext.add(emailContext);
155 if (attuidContext != null)
156 listSharedContext.add(attuidContext);
157 String jsonResponse = convertResponseToJSON(listSharedContext);
162 * Tests for presence of the specified key in the specified context (RESTful
166 * ID that identifies the context, usually the ECOMP Portal
169 * Key for the key-value pair to test
170 * @return JSON with result indicating whether the context and key were
173 @ApiOperation(value = "Tests for presence of the specified key in the specified context.", response = SharedContextJsonResponse.class)
174 @RequestMapping(value = { "/check" }, method = RequestMethod.GET, produces = "application/json")
175 public String checkContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey)
178 logger.debug(EELFLoggerDelegate.debugLogger, "checkContext for " + context_id + ", key " + ckey);
179 if (context_id == null || ckey == null)
180 throw new Exception("Received null for contextId and/or key");
182 String response = null;
183 SharedContext context = contextService.getSharedContext(context_id, ckey);
187 String jsonResponse = convertResponseToJSON(response);
192 * Removes the specified key in the specified context (RESTful service
196 * ID that identifies the context, usually the ECOMP Portal
199 * Key for the key-value pair to remove
200 * @return JSON with result indicating whether the context and key were
203 @ApiOperation(value = "Removes the specified key in the specified context.", response = SharedContextJsonResponse.class)
204 @RequestMapping(value = { "/remove" }, method = RequestMethod.GET, produces = "application/json")
205 public String removeContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey)
208 logger.debug(EELFLoggerDelegate.debugLogger, "removeContext for " + context_id + ", key " + ckey);
209 if (context_id == null || ckey == null)
210 throw new Exception("Received null for contextId and/or key");
212 SharedContext context = contextService.getSharedContext(context_id, ckey);
213 String response = null;
214 if (context != null) {
215 contextService.deleteSharedContext(context);
216 response = "removed";
219 String jsonResponse = convertResponseToJSON(response);
224 * Clears all key-value pairs in the specified context (RESTful service
228 * ID that identifies the context, usually the ECOMP Portal
230 * @return JSON with result indicating the number of key-value pairs
233 @ApiOperation(value = "Clears all key-value pairs in the specified context.", response = SharedContextJsonResponse.class)
234 @RequestMapping(value = { "/clear" }, method = RequestMethod.GET, produces = "application/json")
235 public String clearContext(HttpServletRequest request, @RequestParam String context_id) throws Exception {
237 logger.debug(EELFLoggerDelegate.debugLogger, "clearContext for " + context_id);
238 if (context_id == null)
239 throw new Exception("clearContext: Received null for contextId");
241 int count = contextService.deleteSharedContexts(context_id);
242 String jsonResponse = convertResponseToJSON(Integer.toString(count));
247 * Sets a context value for the specified context and key (RESTful service
248 * method). Creates the context if no context with the specified ID-key pair
249 * exists, overwrites the value if it exists already.
252 * JSON block with these tag-value pairs:
254 * <LI>context_id: ID that identifies the context
255 * <LI>ckey: Key for the key-value pair to store
256 * <LI>cvalue: Value to store
258 * @return JSON with result indicating whether the value was added (key not
259 * previously known) or replaced (key previously known).
261 @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)
262 @RequestMapping(value = { "/set" }, method = RequestMethod.POST, produces = "application/json")
263 public String setContext(HttpServletRequest request, @RequestBody String userJson) throws Exception {
265 @SuppressWarnings("unchecked")
266 Map<String, Object> userData = mapper.readValue(userJson, Map.class);
267 // Use column names as JSON tags
268 final String contextId = (String) userData.get("context_id");
269 final String key = (String) userData.get("ckey");
270 final String value = (String) userData.get("cvalue");
271 if (contextId == null || key == null)
272 throw new Exception("setContext: received null for contextId and/or key");
274 logger.debug(EELFLoggerDelegate.debugLogger, "setContext: ID " + contextId + ", key " + key + "->" + value);
275 String response = null;
276 SharedContext existing = contextService.getSharedContext(contextId, key);
277 if (existing == null) {
278 contextService.addSharedContext(contextId, key, value);
280 existing.setCvalue(value);
281 contextService.saveSharedContext(existing);
283 response = existing == null ? "added" : "replaced";
284 String jsonResponse = convertResponseToJSON(response);
289 * Creates a two-element JSON object tagged "response".
291 * @param responseBody
292 * @return JSON object as String
293 * @throws JsonProcessingException
295 private String convertResponseToJSON(String responseBody) throws JsonProcessingException {
296 Map<String, String> responseMap = new HashMap<String, String>();
297 responseMap.put("response", responseBody);
298 String response = mapper.writeValueAsString(responseMap);
303 * Converts a list of SharedContext objects to a JSON array.
306 * @return JSON array as String
307 * @throws JsonProcessingException
309 private String convertResponseToJSON(List<SharedContext> contextList) throws JsonProcessingException {
310 String jsonArray = mapper.writeValueAsString(contextList);
315 * Creates a JSON object with the content of the shared context; null is ok.
317 * @param responseBody
318 * @return tag "response" with collection of context object's fields
319 * @throws JsonProcessingException
321 private String convertResponseToJSON(SharedContext context) throws JsonProcessingException {
322 Map<String, Object> responseMap = new HashMap<String, Object>();
323 responseMap.put("response", context);
324 String responseBody = mapper.writeValueAsString(responseMap);
329 * Handles any exception thrown by a method in this controller.
334 * HttpServletResponse
335 * @throws IOException
337 @ExceptionHandler(Exception.class)
338 protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException {
339 logger.error(EELFLoggerDelegate.errorLogger, "handleBadRequest caught exception", e);
340 response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());