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.EPSystemProperties;
36 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
37 import org.springframework.beans.factory.annotation.Autowired;
38 import org.springframework.context.annotation.EnableAspectJAutoProxy;
39 import org.springframework.http.HttpStatus;
40 import org.springframework.web.bind.annotation.ExceptionHandler;
41 import org.springframework.web.bind.annotation.RequestBody;
42 import org.springframework.web.bind.annotation.RequestMapping;
43 import org.springframework.web.bind.annotation.RequestMethod;
44 import org.springframework.web.bind.annotation.RequestParam;
45 import org.springframework.web.bind.annotation.RestController;
47 import com.fasterxml.jackson.core.JsonProcessingException;
48 import com.fasterxml.jackson.databind.ObjectMapper;
51 * The shared-context feature allows onboarded applications to share data among
52 * themselves easily for a given session. It basically implements a Java map:
53 * put or get a key-value pair within a map identified by a session ID.
55 * This REST endpoint listens on the Portal app server and answers requests made
56 * by back-end application servers. Reads and writes values to the database
57 * using a Hibernate service to ensure all servers in a high-availability
58 * cluster see the same data.
60 * TODO: This extends EPRestrictedRESTfulBaseController which is an exact copy
61 * of org.openecomp.portalsdk.core.controller.RestrictedRESTfulBaseController.
65 @RequestMapping("/context")
66 @org.springframework.context.annotation.Configuration
67 @EnableAspectJAutoProxy
69 public class SharedContextRestController extends EPRestrictedRESTfulBaseController {
71 * Access to the database
74 SharedContextService contextService;
77 * Logger for debug etc.
79 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextRestController.class);
82 * Reusable JSON (de)serializer
84 private final ObjectMapper mapper = new ObjectMapper();
87 * Gets a value for the specified context and key (RESTful service method).
90 * ID that identifies the context, usually the ECOMP Portal
93 * Key for the key-value pair to fetch
94 * @return JSON with shared context object; response=null if not found.
96 @RequestMapping(value = { "/get" }, method = RequestMethod.GET, produces = "application/json")
97 public String getContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey) throws Exception {
98 String jsonResponse = "";
100 logger.debug(EELFLoggerDelegate.debugLogger, "getContext for ID " + context_id + ", key " + ckey);
101 if (context_id == null || ckey == null) {
102 throw new Exception("Received null for context_id and/or ckey");
105 SharedContext context = contextService.getSharedContext(context_id, ckey);
106 if (context == null) {
107 jsonResponse = convertResponseToJSON(context);
109 jsonResponse = mapper.writeValueAsString(context);
116 * Gets user information for the specified context (RESTful service method).
119 * ID that identifies the context, usually the ECOMP Portal
122 * @return JSON with user's first name, last name and email address; null if
125 @RequestMapping(value = { "/get_user" }, method = RequestMethod.GET, produces = "application/json")
126 public String getUserContext(HttpServletRequest request, @RequestParam String context_id) throws Exception {
127 String jsonResponse = "";
128 List<SharedContext> listSharedContext = new ArrayList<SharedContext>();
130 logger.debug(EELFLoggerDelegate.debugLogger, "getUserContext for ID " + context_id);
131 if (context_id == null) {
132 throw new Exception("Received null for contextId");
135 SharedContext firstNameContext = contextService.getSharedContext(context_id, EPSystemProperties.USER_FIRST_NAME);
136 SharedContext lastNameContext = contextService.getSharedContext(context_id, EPSystemProperties.USER_LAST_NAME);
137 SharedContext emailContext = contextService.getSharedContext(context_id, EPSystemProperties.USER_EMAIL);
138 SharedContext userIdContext = contextService.getSharedContext(context_id, EPSystemProperties.USER_ORG_USERID);
139 if (firstNameContext != null)
140 listSharedContext.add(firstNameContext);
141 if (lastNameContext != null)
142 listSharedContext.add(lastNameContext);
143 if (emailContext != null)
144 listSharedContext.add(emailContext);
145 if (userIdContext != null)
146 listSharedContext.add(userIdContext);
148 logger.error(EELFLoggerDelegate.errorLogger, "Error while getting SharedContext values from database ... ",e);
150 jsonResponse = convertResponseToJSON(listSharedContext);
152 logger.error(EELFLoggerDelegate.errorLogger, "Error while running getUserContext request ... ", e);
158 * Tests for presence of the specified key in the specified context (RESTful
162 * ID that identifies the context, usually the ECOMP Portal
165 * Key for the key-value pair to test
166 * @return JSON with result indicating whether the context and key were
169 @RequestMapping(value = { "/check" }, method = RequestMethod.GET, produces = "application/json")
170 public String checkContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey) throws Exception {
171 String jsonResponse = "";
173 logger.debug(EELFLoggerDelegate.debugLogger, "checkContext for " + context_id + ", key " + ckey);
174 if (context_id == null || ckey == null) {
175 throw new Exception("Received null for contextId and/or key");
178 String response = null;
179 SharedContext context = contextService.getSharedContext(context_id, ckey);
183 jsonResponse = convertResponseToJSON(response);
189 * Removes the specified key in the specified context (RESTful service
193 * ID that identifies the context, usually the ECOMP Portal
196 * Key for the key-value pair to remove
197 * @return JSON with result indicating whether the context and key were
200 @RequestMapping(value = { "/remove" }, method = RequestMethod.GET, produces = "application/json")
201 public String removeContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey) throws Exception {
202 String jsonResponse = "";
204 logger.debug(EELFLoggerDelegate.debugLogger, "removeContext for " + context_id + ", key " + ckey);
205 if (context_id == null || ckey == null) {
206 throw new Exception("Received null for contextId and/or key");
209 SharedContext context = contextService.getSharedContext(context_id, ckey);
210 String response = null;
211 if (context != null) {
212 contextService.deleteSharedContext(context);
213 response = "removed";
216 jsonResponse = convertResponseToJSON(response);
222 * Clears all key-value pairs in the specified context (RESTful service
226 * ID that identifies the context, usually the ECOMP Portal
228 * @return JSON with result indicating the number of key-value pairs removed.
230 @RequestMapping(value = { "/clear" }, method = RequestMethod.GET, produces = "application/json")
231 public String clearContext(HttpServletRequest request, @RequestParam String context_id) throws Exception {
232 String jsonResponse = "";
234 logger.debug(EELFLoggerDelegate.debugLogger, "clearContext for " + context_id);
235 if (context_id == null) {
236 throw new Exception("Received null for contextId");
239 int count = contextService.deleteSharedContexts(context_id);
240 jsonResponse = convertResponseToJSON(Integer.toString(count));
246 * Sets a context value for the specified context and key (RESTful service
247 * method). Creates the context if no context with the specified ID-key pair
248 * exists, overwrites the value if it exists already.
251 * JSON block with these tag-value pairs:
253 * <LI>context_id: ID that identifies the context
254 * <LI>ckey: Key for the key-value pair to store
255 * <LI>cvalue: Value to store
257 * @return JSON with result indicating whether the value was added (key not
258 * previously known) or replaced (key previously known).
260 @RequestMapping(value = { "/set" }, method = RequestMethod.POST, produces = "application/json")
261 public String setContext(HttpServletRequest request, @RequestBody String userJson) throws Exception {
262 String jsonResponse = "";
264 @SuppressWarnings("unchecked")
265 Map<String, Object> userData = mapper.readValue(userJson, Map.class);
266 // Use column names as JSON tags
267 final String contextId = (String) userData.get("context_id");
268 final String key = (String) userData.get("ckey");
269 final String value = (String) userData.get("cvalue");
270 if (contextId == null || key == null) {
271 throw new Exception("Received null for contextId and/or key");
274 logger.debug(EELFLoggerDelegate.debugLogger, "setContext for 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 jsonResponse = convertResponseToJSON(response);
290 * Creates a two-element JSON object tagged "response".
292 * @param responseBody
294 * @throws JsonProcessingException
296 private String convertResponseToJSON(String responseBody) throws JsonProcessingException {
297 Map<String, String> responseMap = new HashMap<String, String>();
298 responseMap.put("response", responseBody);
299 String response = mapper.writeValueAsString(responseMap);
304 * Converts list of SharedContext objects to a JSON array.
308 * @throws JsonProcessingException
310 private String convertResponseToJSON(List<SharedContext> contextList) throws JsonProcessingException {
311 String jsonArray = mapper.writeValueAsString(contextList);
316 * Creates a JSON object with the content of the shared context; null is ok.
318 * @param responseBody
319 * @return tag "response" with collection of context object's fields
320 * @throws JsonProcessingException
322 private String convertResponseToJSON(SharedContext context) throws JsonProcessingException {
323 Map<String, Object> responseMap = new HashMap<String, Object>();
324 responseMap.put("response", context);
325 String responseBody = mapper.writeValueAsString(responseMap);
329 @ExceptionHandler(Exception.class)
330 protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException {
331 logger.warn(EELFLoggerDelegate.errorLogger, "Handling bad request", e);
332 response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());