2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
8 * Unless otherwise specified, all software contained herein is licensed
9 * under the Apache License, Version 2.0 (the "License");
10 * you may not use this software except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * Unless otherwise specified, all documentation contained herein is licensed
22 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23 * you may not use this documentation except in compliance with the License.
24 * You may obtain a copy of the License at
26 * https://creativecommons.org/licenses/by/4.0/
28 * Unless required by applicable law or agreed to in writing, documentation
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
34 * ============LICENSE_END============================================
38 package org.onap.portalapp.portal.controller;
40 import java.io.IOException;
41 import java.util.ArrayList;
42 import java.util.HashMap;
43 import java.util.List;
46 import javax.servlet.http.HttpServletRequest;
47 import javax.servlet.http.HttpServletResponse;
49 import org.onap.portalapp.controller.EPRestrictedRESTfulBaseController;
50 import org.onap.portalapp.portal.domain.SharedContext;
51 import org.onap.portalapp.portal.exceptions.NotValidDataException;
52 import org.onap.portalapp.portal.logging.aop.EPAuditLog;
53 import org.onap.portalapp.portal.service.SharedContextService;
54 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
55 import org.onap.portalapp.portal.utils.PortalConstants;
56 import org.onap.portalapp.validation.DataValidator;
57 import org.onap.portalapp.validation.SecureString;
58 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
59 import org.springframework.beans.factory.annotation.Autowired;
60 import org.springframework.context.annotation.Configuration;
61 import org.springframework.context.annotation.EnableAspectJAutoProxy;
62 import org.springframework.http.HttpStatus;
63 import org.springframework.web.bind.annotation.ExceptionHandler;
64 import org.springframework.web.bind.annotation.RequestBody;
65 import org.springframework.web.bind.annotation.RequestMapping;
66 import org.springframework.web.bind.annotation.GetMapping;
67 import org.springframework.web.bind.annotation.PostMapping;
68 import org.springframework.web.bind.annotation.RequestMethod;
69 import org.springframework.web.bind.annotation.RequestParam;
70 import org.springframework.web.bind.annotation.RestController;
72 import com.fasterxml.jackson.core.JsonProcessingException;
73 import com.fasterxml.jackson.databind.ObjectMapper;
75 import io.swagger.annotations.ApiOperation;
78 * The shared-context feature allows onboarded applications to share data among
79 * themselves easily for a given session. It basically implements a Java map:
80 * put or get a key-value pair within a map identified by a session ID.
82 * This REST endpoint listens on the Portal app server and answers requests made
83 * by back-end application servers. Reads and writes values to the database
84 * using a Hibernate service to ensure all servers in a high-availability
85 * cluster see the same data.
89 @RequestMapping(PortalConstants.REST_AUX_API + "/context")
90 @EnableAspectJAutoProxy
92 public class SharedContextRestController extends EPRestrictedRESTfulBaseController {
93 private static final DataValidator dataValidator = new DataValidator();
94 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextRestController.class);
95 private static final ObjectMapper mapper = new ObjectMapper();
97 private SharedContextService contextService;
100 public SharedContextRestController(SharedContextService contextService) {
101 this.contextService = contextService;
105 * Gets a value for the specified context and key (RESTful service method).
108 * HTTP servlet request
110 * ID that identifies the context, usually the ONAP Portal
113 * Key for the key-value pair to fetch
114 * @return JSON with shared context object; response=null if not found.
118 @ApiOperation(value = "Gets a value for the specified context and key.", response = SharedContext.class)
119 @GetMapping(value = { "/get" }, produces = "application/json")
120 public String getContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey)
122 logger.debug(EELFLoggerDelegate.debugLogger, "getContext for ID " + context_id + ", key " + ckey);
123 if (context_id == null || ckey == null)
124 throw new Exception("Received null for context_id and/or ckey");
125 SecureString secureContextId = new SecureString(context_id);
126 SecureString secureCKey = new SecureString(ckey);
128 if(!dataValidator.isValid(secureContextId) || !dataValidator.isValid(secureCKey)){
129 throw new NotValidDataException("Received not valid for context_id and/or ckey");
132 SharedContext context = contextService.getSharedContext(context_id, ckey);
135 jsonResponse = convertResponseToJSON(context);
137 jsonResponse = mapper.writeValueAsString(context);
143 * Gets user information for the specified context (RESTful service method).
146 * HTTP servlet request
148 * ID that identifies the context, usually the ONAP Portal
150 * @return List of shared-context objects as JSON; should have user's first
151 * name, last name and email address; null if none found
155 @ApiOperation(value = "Gets user information for the specified context.", response = SharedContext.class, responseContainer = "List")
156 @GetMapping(value = { "/get_user" }, produces = "application/json")
157 public String getUserContext(HttpServletRequest request, @RequestParam String context_id) throws Exception {
159 logger.debug(EELFLoggerDelegate.debugLogger, "getUserContext for ID " + context_id);
160 if (context_id == null)
161 throw new Exception("Received null for context_id");
162 SecureString secureContextId = new SecureString(context_id);
163 if (!dataValidator.isValid(secureContextId))
164 throw new NotValidDataException("context_id is not valid");
166 List<SharedContext> listSharedContext = new ArrayList<>();
167 SharedContext firstNameContext = contextService.getSharedContext(context_id,
168 EPCommonSystemProperties.USER_FIRST_NAME);
169 SharedContext lastNameContext = contextService.getSharedContext(context_id,
170 EPCommonSystemProperties.USER_LAST_NAME);
171 SharedContext emailContext = contextService.getSharedContext(context_id, EPCommonSystemProperties.USER_EMAIL);
172 SharedContext orgUserIdContext = contextService.getSharedContext(context_id,
173 EPCommonSystemProperties.USER_ORG_USERID);
174 if (firstNameContext != null)
175 listSharedContext.add(firstNameContext);
176 if (lastNameContext != null)
177 listSharedContext.add(lastNameContext);
178 if (emailContext != null)
179 listSharedContext.add(emailContext);
180 if (orgUserIdContext != null)
181 listSharedContext.add(orgUserIdContext);
182 return convertResponseToJSON(listSharedContext);
186 * Tests for presence of the specified key in the specified context (RESTful
190 * HTTP servlet request
192 * ID that identifies the context, usually the ONAP Portal
195 * Key for the key-value pair to test
196 * @return JSON with result indicating whether the context and key were
201 @ApiOperation(value = "Tests for presence of the specified key in the specified context.", response = SharedContextJsonResponse.class)
202 @GetMapping(value = { "/check" }, produces = "application/json")
203 public String checkContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey)
206 logger.debug(EELFLoggerDelegate.debugLogger, "checkContext for " + context_id + ", key " + ckey);
207 if (context_id == null || ckey == null)
208 throw new Exception("Received null for contextId and/or key");
210 SecureString secureContextId = new SecureString(context_id);
211 SecureString secureCKey = new SecureString(ckey);
213 if (!dataValidator.isValid(secureContextId) || !dataValidator.isValid(secureCKey))
214 throw new NotValidDataException("Not valid data for contextId and/or key");
216 String response = null;
217 SharedContext context = contextService.getSharedContext(context_id, ckey);
221 return convertResponseToJSON(response);
225 * Removes the specified key in the specified context (RESTful service
229 * HTTP servlet request
231 * ID that identifies the context, usually the ONAP Portal
234 * Key for the key-value pair to remove
235 * @return JSON with result indicating whether the context and key were
240 @ApiOperation(value = "Removes the specified key in the specified context.", response = SharedContextJsonResponse.class)
241 @GetMapping(value = { "/remove" }, produces = "application/json")
242 public String removeContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey)
245 logger.debug(EELFLoggerDelegate.debugLogger, "removeContext for " + context_id + ", key " + ckey);
246 if (context_id == null || ckey == null)
247 throw new Exception("Received null for contextId and/or key");
249 SecureString secureContextId = new SecureString(context_id);
250 SecureString secureCKey = new SecureString(ckey);
252 if (!dataValidator.isValid(secureContextId) || !dataValidator.isValid(secureCKey))
253 throw new NotValidDataException("Not valid data for contextId and/or key");
255 SharedContext context = contextService.getSharedContext(context_id, ckey);
256 String response = null;
257 if (context != null) {
258 contextService.deleteSharedContext(context);
259 response = "removed";
262 return convertResponseToJSON(response);
266 * Clears all key-value pairs in the specified context (RESTful service
270 * HTTP servlet request
272 * ID that identifies the context, usually the ONAP Portal
274 * @return JSON with result indicating the number of key-value pairs
279 @ApiOperation(value = "Clears all key-value pairs in the specified context.", response = SharedContextJsonResponse.class)
280 @GetMapping(value = { "/clear" }, produces = "application/json")
281 public String clearContext(HttpServletRequest request, @RequestParam String context_id) throws Exception {
283 logger.debug(EELFLoggerDelegate.debugLogger, "clearContext for " + context_id);
284 if (context_id == null)
285 throw new Exception("clearContext: Received null for contextId");
287 SecureString secureContextId = new SecureString(context_id);
289 if (!dataValidator.isValid(secureContextId))
290 throw new NotValidDataException("Not valid data for contextId");
292 int count = contextService.deleteSharedContexts(context_id);
293 return convertResponseToJSON(Integer.toString(count));
297 * Sets a context value for the specified context and key (RESTful service
298 * method). Creates the context if no context with the specified ID-key pair
299 * exists, overwrites the value if it exists already.
302 * HTTP servlet request
304 * JSON block with these tag-value pairs:
306 * <LI>context_id: ID that identifies the context
307 * <LI>ckey: Key for the key-value pair to store
308 * <LI>cvalue: Value to store
310 * @return JSON with result indicating whether the value was added (key not
311 * previously known) or replaced (key previously known).
315 @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)
316 @PostMapping(value = { "/set" }, produces = "application/json")
317 public String setContext(HttpServletRequest request, @RequestBody String userJson) throws Exception {
318 if (userJson !=null){
319 SecureString secureUserJson = new SecureString(userJson);
320 if (!dataValidator.isValid(secureUserJson))
321 throw new NotValidDataException("Not valid data for userJson");
324 @SuppressWarnings("unchecked")
325 Map<String, Object> userData = mapper.readValue(userJson, Map.class);
326 // Use column names as JSON tags
327 final String contextId = (String) userData.get("context_id");
328 final String key = (String) userData.get("ckey");
329 final String value = (String) userData.get("cvalue");
330 if (contextId == null || key == null)
331 throw new Exception("setContext: received null for contextId and/or key");
333 logger.debug(EELFLoggerDelegate.debugLogger, "setContext: ID " + contextId + ", key " + key + "->" + value);
335 SharedContext existing = contextService.getSharedContext(contextId, key);
336 if (existing == null) {
337 contextService.addSharedContext(contextId, key, value);
339 existing.setCvalue(value);
340 contextService.saveSharedContext(existing);
342 response = existing == null ? "added" : "replaced";
343 return convertResponseToJSON(response);
347 * Creates a two-element JSON object tagged "response".
349 * @param responseBody
350 * @return JSON object as String
351 * @throws JsonProcessingException
353 private String convertResponseToJSON(String responseBody) throws JsonProcessingException {
354 Map<String, String> responseMap = new HashMap<>();
355 responseMap.put("response", responseBody);
356 return mapper.writeValueAsString(responseMap);
360 * Converts a list of SharedContext objects to a JSON array.
363 * @return JSON array as String
364 * @throws JsonProcessingException
366 private String convertResponseToJSON(List<SharedContext> contextList) throws JsonProcessingException {
367 return mapper.writeValueAsString(contextList);
371 * Creates a JSON object with the content of the shared context; null is ok.
374 * @return tag "response" with collection of context object's fields
375 * @throws JsonProcessingException
377 private String convertResponseToJSON(SharedContext context) throws JsonProcessingException {
378 Map<String, Object> responseMap = new HashMap<>();
379 responseMap.put("response", context);
380 return mapper.writeValueAsString(responseMap);
384 * Handles any exception thrown by a method in this controller.
389 * HttpServletResponse
390 * @throws IOException
392 @ExceptionHandler(Exception.class)
393 protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException {
394 logger.error(EELFLoggerDelegate.errorLogger, "handleBadRequest caught exception", e);
395 response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());
399 class SharedContextJsonResponse {