08a0d49b23b5a44399721b82d4e084305818343d
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / controller / SharedContextRestController.java
1 /*-
2  * ================================================================================
3  * ECOMP Portal
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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  * ================================================================================
19  */
20 package org.openecomp.portalapp.portal.controller;
21
22 import java.io.IOException;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27
28 import javax.servlet.http.HttpServletRequest;
29 import javax.servlet.http.HttpServletResponse;
30
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;
48
49 import com.fasterxml.jackson.core.JsonProcessingException;
50 import com.fasterxml.jackson.databind.ObjectMapper;
51
52 import io.swagger.annotations.ApiOperation;
53
54 /**
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.
58  * 
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.
63  */
64 @Configuration
65 @RestController
66 @RequestMapping(PortalConstants.REST_AUX_API + "/context")
67 @EnableAspectJAutoProxy
68 @EPAuditLog
69 public class SharedContextRestController extends EPRestrictedRESTfulBaseController {
70
71         /**
72          * Model for a one-element JSON object returned by many methods.
73          */
74         class SharedContextJsonResponse {
75                 String response;
76         }
77
78         /**
79          * Access to the database
80          */
81         @Autowired
82         private SharedContextService contextService;
83
84         /**
85          * Logger for debug etc.
86          */
87         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextRestController.class);
88
89         /**
90          * Reusable JSON (de)serializer
91          */
92         private final ObjectMapper mapper = new ObjectMapper();
93
94         /**
95          * Gets a value for the specified context and key (RESTful service method).
96          * 
97          * @param request
98          *            HTTP servlet request
99          * @param context_id
100          *            ID that identifies the context, usually the ECOMP Portal
101          *            session key.
102          * @param ckey
103          *            Key for the key-value pair to fetch
104          * @return JSON with shared context object; response=null if not found.
105          * @throws Exception
106          *             on bad arguments
107          */
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)
111                         throws Exception {
112
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");
116
117                 SharedContext context = contextService.getSharedContext(context_id, ckey);
118                 String jsonResponse = "";
119                 if (context == null)
120                         jsonResponse = convertResponseToJSON(context);
121                 else
122                         jsonResponse = mapper.writeValueAsString(context);
123
124                 return jsonResponse;
125         }
126
127         /**
128          * Gets user information for the specified context (RESTful service method).
129          * 
130          * @param request
131          *            HTTP servlet request
132          * @param context_id
133          *            ID that identifies the context, usually the ECOMP Portal
134          *            session key.
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
137          * @throws Exception
138          *             on bad arguments
139          */
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 {
143
144                 logger.debug(EELFLoggerDelegate.debugLogger, "getUserContext for ID " + context_id);
145                 if (context_id == null)
146                         throw new Exception("Received null for context_id");
147
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 orgUserIdContext = 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 (orgUserIdContext != null)
163                         listSharedContext.add(orgUserIdContext);
164                 String jsonResponse = convertResponseToJSON(listSharedContext);
165                 return jsonResponse;
166         }
167
168         /**
169          * Tests for presence of the specified key in the specified context (RESTful
170          * service method).
171          * 
172          * @param request
173          *            HTTP servlet request
174          * @param context_id
175          *            ID that identifies the context, usually the ECOMP Portal
176          *            session key.
177          * @param ckey
178          *            Key for the key-value pair to test
179          * @return JSON with result indicating whether the context and key were
180          *         found.
181          * @throws Exception
182          *             on bad arguments
183          */
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)
187                         throws Exception {
188
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");
192
193                 String response = null;
194                 SharedContext context = contextService.getSharedContext(context_id, ckey);
195                 if (context != null)
196                         response = "exists";
197
198                 String jsonResponse = convertResponseToJSON(response);
199                 return jsonResponse;
200         }
201
202         /**
203          * Removes the specified key in the specified context (RESTful service
204          * method).
205          * 
206          * @param request
207          *            HTTP servlet request
208          * @param context_id
209          *            ID that identifies the context, usually the ECOMP Portal
210          *            session key.
211          * @param ckey
212          *            Key for the key-value pair to remove
213          * @return JSON with result indicating whether the context and key were
214          *         found.
215          * @throws Exception
216          *             on bad arguments
217          */
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)
221                         throws Exception {
222
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");
226
227                 SharedContext context = contextService.getSharedContext(context_id, ckey);
228                 String response = null;
229                 if (context != null) {
230                         contextService.deleteSharedContext(context);
231                         response = "removed";
232                 }
233
234                 String jsonResponse = convertResponseToJSON(response);
235                 return jsonResponse;
236         }
237
238         /**
239          * Clears all key-value pairs in the specified context (RESTful service
240          * method).
241          * 
242          * @param request
243          *            HTTP servlet request
244          * @param context_id
245          *            ID that identifies the context, usually the ECOMP Portal
246          *            session key.
247          * @return JSON with result indicating the number of key-value pairs
248          *         removed.
249          * @throws Exception
250          *             on bad arguments
251          */
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 {
255
256                 logger.debug(EELFLoggerDelegate.debugLogger, "clearContext for " + context_id);
257                 if (context_id == null)
258                         throw new Exception("clearContext: Received null for contextId");
259
260                 int count = contextService.deleteSharedContexts(context_id);
261                 String jsonResponse = convertResponseToJSON(Integer.toString(count));
262                 return jsonResponse;
263         }
264
265         /**
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.
269          * 
270          * @param request
271          *            HTTP servlet request
272          * @param userJson
273          *            JSON block with these tag-value pairs:
274          *            <UL>
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
278          *            </UL>
279          * @return JSON with result indicating whether the value was added (key not
280          *         previously known) or replaced (key previously known).
281          * @throws Exception
282          *             on bad arguments
283          */
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 {
287
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");
296
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);
302                 } else {
303                         existing.setCvalue(value);
304                         contextService.saveSharedContext(existing);
305                 }
306                 response = existing == null ? "added" : "replaced";
307                 String jsonResponse = convertResponseToJSON(response);
308                 return jsonResponse;
309         }
310
311         /**
312          * Creates a two-element JSON object tagged "response".
313          * 
314          * @param responseBody
315          * @return JSON object as String
316          * @throws JsonProcessingException
317          */
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);
322                 return response;
323         }
324
325         /**
326          * Converts a list of SharedContext objects to a JSON array.
327          * 
328          * @param contextList
329          * @return JSON array as String
330          * @throws JsonProcessingException
331          */
332         private String convertResponseToJSON(List<SharedContext> contextList) throws JsonProcessingException {
333                 String jsonArray = mapper.writeValueAsString(contextList);
334                 return jsonArray;
335         }
336
337         /**
338          * Creates a JSON object with the content of the shared context; null is ok.
339          * 
340          * @param context
341          * @return tag "response" with collection of context object's fields
342          * @throws JsonProcessingException
343          */
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);
348                 return responseBody;
349         }
350
351         /**
352          * Handles any exception thrown by a method in this controller.
353          * 
354          * @param e
355          *            Exception
356          * @param response
357          *            HttpServletResponse
358          * @throws IOException
359          */
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());
364         }
365
366 }