nexus site path corrected
[portal.git] / ecomp-portal-BE / 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.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;
46
47 import com.fasterxml.jackson.core.JsonProcessingException;
48 import com.fasterxml.jackson.databind.ObjectMapper;
49
50 /**
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.
54  * 
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.
59  * 
60  * TODO: This extends EPRestrictedRESTfulBaseController which is an exact copy
61  * of org.openecomp.portalsdk.core.controller.RestrictedRESTfulBaseController.
62  */
63
64 @RestController
65 @RequestMapping("/context")
66 @org.springframework.context.annotation.Configuration
67 @EnableAspectJAutoProxy
68 @EPAuditLog
69 public class SharedContextRestController extends EPRestrictedRESTfulBaseController {
70         /**
71          * Access to the database
72          */
73         @Autowired
74         SharedContextService contextService;
75
76         /**
77          * Logger for debug etc.
78          */
79         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextRestController.class);
80
81         /**
82          * Reusable JSON (de)serializer
83          */
84         private final ObjectMapper mapper = new ObjectMapper();
85
86         /**
87          * Gets a value for the specified context and key (RESTful service method).
88          * 
89          * @param ctxtId
90          *            ID that identifies the context, usually the ECOMP Portal
91          *            session key.
92          * @param ckey
93          *            Key for the key-value pair to fetch
94          * @return JSON with shared context object; response=null if not found.
95          */
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             = "";
99                 
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");
103                 }
104                 
105                 SharedContext context = contextService.getSharedContext(context_id, ckey);
106                 if (context == null) {
107                         jsonResponse = convertResponseToJSON(context);
108                 } else {
109                         jsonResponse = mapper.writeValueAsString(context);
110                 }
111                 
112                 return jsonResponse;
113         }
114
115         /**
116          * Gets user information for the specified context (RESTful service method).
117          * 
118          * @param ctxtId
119          *            ID that identifies the context, usually the ECOMP Portal
120          *            session key.
121          * 
122          * @return JSON with user's first name, last name and email address; null if
123          *         none found
124          */
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>();
129                 try{
130                         logger.debug(EELFLoggerDelegate.debugLogger, "getUserContext for ID " + context_id);
131                         if (context_id == null) {
132                                 throw new Exception("Received null for contextId");
133                         }
134                         try{
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);
147                         }catch(Exception e){
148                                 logger.error(EELFLoggerDelegate.errorLogger, "Error while getting SharedContext values from database ... ",e);
149                         }
150                         jsonResponse = convertResponseToJSON(listSharedContext);
151                 }catch(Exception e){
152                         logger.error(EELFLoggerDelegate.errorLogger, "Error while running getUserContext request ... ", e);
153                 }       
154                 return jsonResponse;
155         }
156
157         /**
158          * Tests for presence of the specified key in the specified context (RESTful
159          * service method).
160          * 
161          * @param context_id
162          *            ID that identifies the context, usually the ECOMP Portal
163          *            session key.
164          * @param ckey
165          *            Key for the key-value pair to test
166          * @return JSON with result indicating whether the context and key were
167          *         found.
168          */
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             = "";
172                 
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");
176                 }
177                 
178                 String response = null;
179                 SharedContext context = contextService.getSharedContext(context_id, ckey);
180                 if (context != null)
181                         response = "exists";
182                 
183                 jsonResponse = convertResponseToJSON(response);
184                 
185                 return jsonResponse;
186         }
187
188         /**
189          * Removes the specified key in the specified context (RESTful service
190          * method).
191          * 
192          * @param context_id
193          *            ID that identifies the context, usually the ECOMP Portal
194          *            session key.
195          * @param ckey
196          *            Key for the key-value pair to remove
197          * @return JSON with result indicating whether the context and key were
198          *         found.
199          */
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             = "";
203                 
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");
207                 }
208                 
209                 SharedContext context = contextService.getSharedContext(context_id, ckey);
210                 String response = null;
211                 if (context != null) {
212                         contextService.deleteSharedContext(context);
213                         response = "removed";
214                 }
215                 
216                 jsonResponse = convertResponseToJSON(response);
217                 
218                 return jsonResponse;
219         }
220
221         /**
222          * Clears all key-value pairs in the specified context (RESTful service
223          * method).
224          * 
225          * @param context_id
226          *            ID that identifies the context, usually the ECOMP Portal
227          *            session key.
228          * @return JSON with result indicating the number of key-value pairs removed.
229          */
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             = "";
233                 
234                 logger.debug(EELFLoggerDelegate.debugLogger, "clearContext for " + context_id);
235                 if (context_id == null) {
236                         throw new Exception("Received null for contextId");
237                 }
238                 
239                 int count = contextService.deleteSharedContexts(context_id);
240                 jsonResponse = convertResponseToJSON(Integer.toString(count));
241                 
242                 return jsonResponse;
243         }
244
245         /**
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.
249          * 
250          * @param userJson
251          *            JSON block with these tag-value pairs:
252          *            <UL>
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
256          *            </UL>
257          * @return JSON with result indicating whether the value was added (key not
258          *         previously known) or replaced (key previously known).
259          */
260         @RequestMapping(value = { "/set" }, method = RequestMethod.POST, produces = "application/json")
261         public String setContext(HttpServletRequest request, @RequestBody String userJson) throws Exception {
262                 String jsonResponse             = "";
263                 
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");
272                 }
273                 
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);
279                 } else {
280                         existing.setCvalue(value);
281                         contextService.saveSharedContext(existing);
282                 }
283                 response = existing == null ? "added" : "replaced";
284                 jsonResponse = convertResponseToJSON(response);
285                 
286                 return jsonResponse;
287         }
288
289         /**
290          * Creates a two-element JSON object tagged "response".
291          * 
292          * @param responseBody
293          * @return
294          * @throws JsonProcessingException
295          */
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);
300                 return response;
301         }
302
303         /**
304          * Converts list of SharedContext objects to a JSON array.
305          * 
306          * @param contextList
307          * @return
308          * @throws JsonProcessingException
309          */
310         private String convertResponseToJSON(List<SharedContext> contextList) throws JsonProcessingException {
311                 String jsonArray = mapper.writeValueAsString(contextList);
312                 return jsonArray;
313         }
314
315         /**
316          * Creates a JSON object with the content of the shared context; null is ok.
317          * 
318          * @param responseBody
319          * @return tag "response" with collection of context object's fields
320          * @throws JsonProcessingException
321          */
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);
326                 return responseBody;
327         }
328
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());
333         }
334
335 }