[PORTAL-7] Rebase
[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 ctxtId
98          *            ID that identifies the context, usually the ECOMP Portal
99          *            session key.
100          * @param ckey
101          *            Key for the key-value pair to fetch
102          * @return JSON with shared context object; response=null if not found.
103          */
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)
107                         throws Exception {
108
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");
112
113                 SharedContext context = contextService.getSharedContext(context_id, ckey);
114                 String jsonResponse = "";
115                 if (context == null)
116                         jsonResponse = convertResponseToJSON(context);
117                 else
118                         jsonResponse = mapper.writeValueAsString(context);
119
120                 return jsonResponse;
121         }
122
123         /**
124          * Gets user information for the specified context (RESTful service method).
125          * 
126          * @param ctxtId
127          *            ID that identifies the context, usually the ECOMP Portal
128          *            session key.
129          * 
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
132          */
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 {
136
137                 logger.debug(EELFLoggerDelegate.debugLogger, "getUserContext for ID " + context_id);
138                 if (context_id == null)
139                         throw new Exception("Received null for context_id");
140
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);
158                 return jsonResponse;
159         }
160
161         /**
162          * Tests for presence of the specified key in the specified context (RESTful
163          * service method).
164          * 
165          * @param context_id
166          *            ID that identifies the context, usually the ECOMP Portal
167          *            session key.
168          * @param ckey
169          *            Key for the key-value pair to test
170          * @return JSON with result indicating whether the context and key were
171          *         found.
172          */
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)
176                         throws Exception {
177
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");
181
182                 String response = null;
183                 SharedContext context = contextService.getSharedContext(context_id, ckey);
184                 if (context != null)
185                         response = "exists";
186
187                 String jsonResponse = convertResponseToJSON(response);
188                 return jsonResponse;
189         }
190
191         /**
192          * Removes the specified key in the specified context (RESTful service
193          * method).
194          * 
195          * @param context_id
196          *            ID that identifies the context, usually the ECOMP Portal
197          *            session key.
198          * @param ckey
199          *            Key for the key-value pair to remove
200          * @return JSON with result indicating whether the context and key were
201          *         found.
202          */
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)
206                         throws Exception {
207
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");
211
212                 SharedContext context = contextService.getSharedContext(context_id, ckey);
213                 String response = null;
214                 if (context != null) {
215                         contextService.deleteSharedContext(context);
216                         response = "removed";
217                 }
218
219                 String jsonResponse = convertResponseToJSON(response);
220                 return jsonResponse;
221         }
222
223         /**
224          * Clears all key-value pairs in the specified context (RESTful service
225          * method).
226          * 
227          * @param context_id
228          *            ID that identifies the context, usually the ECOMP Portal
229          *            session key.
230          * @return JSON with result indicating the number of key-value pairs
231          *         removed.
232          */
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 {
236
237                 logger.debug(EELFLoggerDelegate.debugLogger, "clearContext for " + context_id);
238                 if (context_id == null)
239                         throw new Exception("clearContext: Received null for contextId");
240
241                 int count = contextService.deleteSharedContexts(context_id);
242                 String jsonResponse = convertResponseToJSON(Integer.toString(count));
243                 return jsonResponse;
244         }
245
246         /**
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.
250          * 
251          * @param userJson
252          *            JSON block with these tag-value pairs:
253          *            <UL>
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
257          *            </UL>
258          * @return JSON with result indicating whether the value was added (key not
259          *         previously known) or replaced (key previously known).
260          */
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 {
264
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");
273
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);
279                 } else {
280                         existing.setCvalue(value);
281                         contextService.saveSharedContext(existing);
282                 }
283                 response = existing == null ? "added" : "replaced";
284                 String jsonResponse = convertResponseToJSON(response);
285                 return jsonResponse;
286         }
287
288         /**
289          * Creates a two-element JSON object tagged "response".
290          * 
291          * @param responseBody
292          * @return JSON object as String
293          * @throws JsonProcessingException
294          */
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);
299                 return response;
300         }
301
302         /**
303          * Converts a list of SharedContext objects to a JSON array.
304          * 
305          * @param contextList
306          * @return JSON array as String
307          * @throws JsonProcessingException
308          */
309         private String convertResponseToJSON(List<SharedContext> contextList) throws JsonProcessingException {
310                 String jsonArray = mapper.writeValueAsString(contextList);
311                 return jsonArray;
312         }
313
314         /**
315          * Creates a JSON object with the content of the shared context; null is ok.
316          * 
317          * @param responseBody
318          * @return tag "response" with collection of context object's fields
319          * @throws JsonProcessingException
320          */
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);
325                 return responseBody;
326         }
327
328         /**
329          * Handles any exception thrown by a method in this controller.
330          * 
331          * @param e
332          *            Exception
333          * @param response
334          *            HttpServletResponse
335          * @throws IOException
336          */
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());
341         }
342
343 }