Merge "HealthCheckController up"
[portal.git] / portal-BE / src / main / java / org / onap / portal / controller / SharedContextRestController.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
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
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
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.
20  *
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
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
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.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38 package org.onap.portal.controller;
39
40 import com.fasterxml.jackson.core.JsonProcessingException;
41 import com.fasterxml.jackson.databind.ObjectMapper;
42 import io.swagger.annotations.ApiOperation;
43 import java.io.IOException;
44 import java.util.ArrayList;
45 import java.util.HashMap;
46 import java.util.List;
47 import java.util.Map;
48 import javax.servlet.http.HttpServletRequest;
49 import javax.servlet.http.HttpServletResponse;
50 import org.onap.portal.domain.db.fn.FnSharedContext;
51 import org.onap.portal.domain.dto.ecomp.SharedContext;
52 import org.onap.portal.exception.NotValidDataException;
53 import org.onap.portal.logging.aop.EPAuditLog;
54 import org.onap.portal.service.sharedContext.FnSharedContextService;
55 import org.onap.portal.utils.EPCommonSystemProperties;
56 import org.onap.portal.utils.PortalConstants;
57 import org.onap.portal.validation.DataValidator;
58 import org.onap.portal.validation.SecureString;
59 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
60 import org.springframework.beans.factory.annotation.Autowired;
61 import org.springframework.context.annotation.Configuration;
62 import org.springframework.context.annotation.EnableAspectJAutoProxy;
63 import org.springframework.http.HttpStatus;
64 import org.springframework.web.bind.annotation.ExceptionHandler;
65 import org.springframework.web.bind.annotation.RequestBody;
66 import org.springframework.web.bind.annotation.RequestMapping;
67 import org.springframework.web.bind.annotation.RequestMethod;
68 import org.springframework.web.bind.annotation.RequestParam;
69 import org.springframework.web.bind.annotation.RestController;
70
71
72 @Configuration
73 @RestController
74 @RequestMapping(PortalConstants.REST_AUX_API + "/context")
75 @EnableAspectJAutoProxy
76 @EPAuditLog
77 public class SharedContextRestController {
78         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextRestController.class);
79         private static final ObjectMapper mapper = new ObjectMapper();
80
81         private final FnSharedContextService contextService;
82         private final DataValidator dataValidator;
83
84         @Autowired
85         public SharedContextRestController(FnSharedContextService contextService,
86                 DataValidator dataValidator) {
87                 this.contextService = contextService;
88                 this.dataValidator = dataValidator;
89         }
90
91         @ApiOperation(value = "Gets a value for the specified context and key.", response = SharedContext.class)
92         @RequestMapping(value = { "/get" }, method = RequestMethod.GET, produces = "application/json")
93         public String getContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey)
94                 throws Exception {
95                 logger.debug(EELFLoggerDelegate.debugLogger, "getContext for ID " + context_id + ", key " + ckey);
96                 if (context_id == null || ckey == null)
97                         throw new Exception("Received null for context_id and/or ckey");
98                 SecureString secureContextId = new SecureString(context_id);
99                 SecureString secureCKey = new SecureString(ckey);
100
101                 if(!dataValidator.isValid(secureContextId) || !dataValidator.isValid(secureCKey)){
102                         throw new NotValidDataException("Received not valid for context_id and/or ckey");
103                 }
104
105                 FnSharedContext context = contextService.getFnSharedContext(context_id, ckey);
106                 String jsonResponse;
107                 if (context == null)
108                         jsonResponse = convertResponseToJSON(context);
109                 else
110                         jsonResponse = mapper.writeValueAsString(context);
111
112                 return jsonResponse;
113         }
114
115         @ApiOperation(value = "Gets user information for the specified context.", response = SharedContext.class, responseContainer = "List")
116         @RequestMapping(value = { "/get_user" }, method = RequestMethod.GET, produces = "application/json")
117         public String getUserContext(HttpServletRequest request, @RequestParam String context_id) throws Exception {
118
119                 logger.debug(EELFLoggerDelegate.debugLogger, "getUserContext for ID " + context_id);
120                 if (context_id == null)
121                         throw new Exception("Received null for context_id");
122                 SecureString secureContextId = new SecureString(context_id);
123                 if (!dataValidator.isValid(secureContextId))
124                         throw new NotValidDataException("context_id is not valid");
125
126                 List<FnSharedContext> listSharedContext = new ArrayList<>();
127                 FnSharedContext firstNameContext = contextService.getFnSharedContext(context_id,
128                                 EPCommonSystemProperties.USER_FIRST_NAME);
129                 FnSharedContext lastNameContext = contextService.getFnSharedContext(context_id,
130                                 EPCommonSystemProperties.USER_LAST_NAME);
131                 FnSharedContext emailContext = contextService.getFnSharedContext(context_id, EPCommonSystemProperties.USER_EMAIL);
132                 FnSharedContext orgUserIdContext = contextService.getFnSharedContext(context_id,
133                                 EPCommonSystemProperties.USER_ORG_USERID);
134                 if (firstNameContext != null)
135                         listSharedContext.add(firstNameContext);
136                 if (lastNameContext != null)
137                         listSharedContext.add(lastNameContext);
138                 if (emailContext != null)
139                         listSharedContext.add(emailContext);
140                 if (orgUserIdContext != null)
141                         listSharedContext.add(orgUserIdContext);
142                 return convertResponseToJSON(listSharedContext);
143         }
144
145         @ApiOperation(value = "Tests for presence of the specified key in the specified context.")
146         @RequestMapping(value = { "/check" }, method = RequestMethod.GET, produces = "application/json")
147         public String checkContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey)
148                         throws Exception {
149
150                 logger.debug(EELFLoggerDelegate.debugLogger, "checkContext for " + context_id + ", key " + ckey);
151                 if (context_id == null || ckey == null)
152                         throw new Exception("Received null for contextId and/or key");
153
154                 SecureString secureContextId = new SecureString(context_id);
155                 SecureString secureCKey = new SecureString(ckey);
156
157                 if (!dataValidator.isValid(secureContextId) || !dataValidator.isValid(secureCKey))
158                         throw new NotValidDataException("Not valid data for contextId and/or key");
159
160                 String response = null;
161                 FnSharedContext context = contextService.getFnSharedContext(context_id, ckey);
162                 if (context != null)
163                         response = "exists";
164
165                 return convertResponseToJSON(response);
166         }
167
168         @ApiOperation(value = "Removes the specified key in the specified context.")
169         @RequestMapping(value = { "/remove" }, method = RequestMethod.GET, produces = "application/json")
170         public String removeContext(HttpServletRequest request, @RequestParam String context_id, @RequestParam String ckey)
171                         throws Exception {
172
173                 logger.debug(EELFLoggerDelegate.debugLogger, "removeContext 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                 SecureString secureContextId = new SecureString(context_id);
178                 SecureString secureCKey = new SecureString(ckey);
179
180                 if (!dataValidator.isValid(secureContextId) || !dataValidator.isValid(secureCKey))
181                         throw new NotValidDataException("Not valid data for contextId and/or key");
182
183                 FnSharedContext context = contextService.getFnSharedContext(context_id, ckey);
184                 String response = null;
185                 if (context != null) {
186                         contextService.delete(context);
187                         response = "removed";
188                 }
189
190                 return convertResponseToJSON(response);
191         }
192
193         @ApiOperation(value = "Clears all key-value pairs in the specified context.")
194         @RequestMapping(value = { "/clear" }, method = RequestMethod.GET, produces = "application/json")
195         public String clearContext(HttpServletRequest request, @RequestParam String contextId) throws Exception {
196
197                 logger.debug(EELFLoggerDelegate.debugLogger, "clearContext for " + contextId);
198                 if (contextId == null)
199                         throw new Exception("clearContext: Received null for contextId");
200
201                 SecureString secureContextId = new SecureString(contextId);
202
203                 if (!dataValidator.isValid(secureContextId))
204                         throw new NotValidDataException("Not valid data for contextId");
205
206                 int count = contextService.deleteSharedContexts(contextId);
207                 return convertResponseToJSON(Integer.toString(count));
208         }
209
210         @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.")
211         @RequestMapping(value = { "/set" }, method = RequestMethod.POST, produces = "application/json")
212         public String setContext(HttpServletRequest request, @RequestBody String userJson) throws Exception {
213                 if (userJson !=null){
214                 SecureString secureUserJson = new SecureString(userJson);
215                 if (!dataValidator.isValid(secureUserJson))
216                         throw new NotValidDataException("Not valid data for userJson");
217                 }
218
219                 @SuppressWarnings("unchecked")
220                 Map<String, Object> userData = mapper.readValue(userJson, Map.class);
221                 // Use column names as JSON tags
222                 final String contextId = (String) userData.get("context_id");
223                 final String key = (String) userData.get("ckey");
224                 final String value = (String) userData.get("cvalue");
225                 if (contextId == null || key == null)
226                         throw new Exception("setContext: received null for contextId and/or key");
227
228                 logger.debug(EELFLoggerDelegate.debugLogger, "setContext: ID " + contextId + ", key " + key + "->" + value);
229                 String response;
230                 FnSharedContext existing = contextService.getFnSharedContext(contextId, key);
231                 if (existing == null) {
232                         contextService.addFnSharedContext(contextId, key, value);
233                 } else {
234                         existing.setCvalue(value);
235                         contextService.save(existing);
236                 }
237                 response = existing == null ? "added" : "replaced";
238                 return convertResponseToJSON(response);
239         }
240
241         private String convertResponseToJSON(String responseBody) throws JsonProcessingException {
242                 Map<String, String> responseMap = new HashMap<>();
243                 responseMap.put("response", responseBody);
244                 return mapper.writeValueAsString(responseMap);
245         }
246
247         private String convertResponseToJSON(List<FnSharedContext> contextList) throws JsonProcessingException {
248                 return mapper.writeValueAsString(contextList);
249         }
250
251         private String convertResponseToJSON(FnSharedContext context) throws JsonProcessingException {
252                 Map<String, Object> responseMap = new HashMap<>();
253                 responseMap.put("response", context);
254                 return mapper.writeValueAsString(responseMap);
255         }
256
257         @ExceptionHandler(Exception.class)
258         protected void handleBadRequests(Exception e, HttpServletResponse response) throws IOException {
259                 logger.error(EELFLoggerDelegate.errorLogger, "handleBadRequest caught exception", e);
260                 response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage());
261         }
262
263 }
264