ca902c49a3cf6426553c96949bb03d4f2eb8b038
[portal/sdk.git] /
1 /*-
2  * ================================================================================
3  * ECOMP Portal SDK
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.controller.core;
21
22 import java.io.IOException;
23 import java.io.PrintWriter;
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.json.JSONObject;
32 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
33 import org.openecomp.portalsdk.core.domain.Role;
34 import org.openecomp.portalsdk.core.domain.RoleFunction;
35 import org.openecomp.portalsdk.core.logging.aspect.EELFLoggerAdvice;
36 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
37 import org.openecomp.portalsdk.core.service.RoleService;
38 import org.openecomp.portalsdk.core.util.SystemProperties;
39 import org.openecomp.portalsdk.core.web.support.JsonMessage;
40 import org.slf4j.MDC;
41 import org.springframework.beans.factory.annotation.Autowired;
42 import org.springframework.stereotype.Controller;
43 import org.springframework.web.bind.ServletRequestUtils;
44 import org.springframework.web.bind.annotation.RequestMapping;
45 import org.springframework.web.bind.annotation.RequestMethod;
46 import org.springframework.web.servlet.ModelAndView;
47
48 import com.fasterxml.jackson.databind.DeserializationFeature;
49 import com.fasterxml.jackson.databind.JsonNode;
50 import com.fasterxml.jackson.databind.ObjectMapper;
51 import com.fasterxml.jackson.databind.type.TypeFactory;
52
53 @Controller
54 @RequestMapping("/")
55 public class RoleController extends RestrictedBaseController {
56         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleController.class);
57
58         @Autowired
59         RoleService roleService;
60
61         private String viewName;
62
63         @RequestMapping(value = { "/role" }, method = RequestMethod.GET)
64         public ModelAndView role(HttpServletRequest request) {
65                 Map<String, Object> model = new HashMap<String, Object>();
66                 ObjectMapper mapper = new ObjectMapper();
67
68                 Role role = roleService.getRole(new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
69                 logger.info("role_id" + role.getId());
70                 try {
71                         model.put("availableRoleFunctions", mapper.writeValueAsString(roleService.getRoleFunctions()));
72                         model.put("availableRoles", mapper.writeValueAsString(roleService.getAvailableChildRoles(role.getId())));
73                         model.put("role", mapper.writeValueAsString(role));
74                 } catch (Exception e) {
75                         logger.error("role: failed", e);
76                         logger.error(EELFLoggerDelegate.errorLogger, "role failed", e);
77                 }
78                 return new ModelAndView(getViewName(), model);
79         }
80
81         @RequestMapping(value = { "/get_role" }, method = RequestMethod.GET)
82         public void getRole(HttpServletRequest request, HttpServletResponse response) {
83                 Map<String, Object> model = new HashMap<String, Object>();
84                 ObjectMapper mapper = new ObjectMapper();
85
86                 Role role = roleService.getRole(new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
87                 logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + role.getId());
88                 try {
89                         model.put("availableRoleFunctions", mapper.writeValueAsString(roleService.getRoleFunctions()));
90                         model.put("availableRoles", mapper.writeValueAsString(roleService.getAvailableChildRoles(role.getId())));
91                         model.put("role", mapper.writeValueAsString(role));
92
93                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
94                         JSONObject j = new JSONObject(msg);
95                         response.getWriter().write(j.toString());
96                 } catch (Exception e) {
97                         logger.error(EELFLoggerDelegate.errorLogger, "getRole failed", e);
98                 }
99
100         }
101
102         /**
103          * Creates a new role or updates an existing role.
104          * 
105          * @param request
106          * @param response
107          * @return Always returns null.
108          * @throws IOException
109          *             If the write to the result project fails
110          */
111         @RequestMapping(value = { "/role/saveRole" }, method = RequestMethod.POST)
112         public ModelAndView saveRole(HttpServletRequest request, HttpServletResponse response) throws IOException {
113                 JSONObject j = null;
114                 logger.debug(EELFLoggerDelegate.debugLogger, "RoleController.save");
115                 try {
116                         ObjectMapper mapper = new ObjectMapper();
117                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
118                         JsonNode root = mapper.readTree(request.getReader());
119                         Role role = mapper.readValue(root.get("role").toString(), Role.class);
120
121                         List<Role> childRoles = mapper.readValue(root.get("childRoles").toString(),
122                                         TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
123
124                         List<RoleFunction> roleFunctions = mapper.readValue(root.get("roleFunctions").toString(),
125                                         TypeFactory.defaultInstance().constructCollectionType(List.class, RoleFunction.class));
126
127                         Role domainRole = null;
128                         if (role.getId() != null) {
129                                 doAuditLog("saveRole: updating existing role {}", role.getId());
130                                 domainRole = roleService.getRole(role.getId());
131
132                                 domainRole.setName(role.getName());
133                                 domainRole.setPriority(role.getPriority());
134                         } else {
135                                 doAuditLog("saveRole: creating new role", role.getName());
136                                 // check for existing role of same name
137                                 List<Role> roles = roleService.getAvailableRoles();
138                                 for (Role existRole : roles)
139                                         if (existRole.getName().equalsIgnoreCase(role.getName()))
140                                                 throw new Exception("role already exists: " + existRole.getName());
141
142                                 domainRole = new Role();
143                                 domainRole.setName(role.getName());
144                                 domainRole.setPriority(role.getPriority());
145                                 if (role.getChildRoles().size() > 0) {
146                                         for (Object childRole : childRoles) {
147                                                 domainRole.addChildRole((Role) childRole);
148                                         }
149                                 }
150                                 if (role.getRoleFunctions().size() > 0) {
151                                         for (Object roleFunction : roleFunctions) {
152                                                 domainRole.addRoleFunction((RoleFunction) roleFunction);
153                                         }
154                                 }
155                         }
156
157                         roleService.saveRole(domainRole);
158
159                         String responseString = mapper.writeValueAsString(domainRole);
160                         j = new JSONObject("{role: " + responseString + "}");
161                 } catch (Exception e) {
162                         // Produce JSON error message
163                         logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e);
164                         j = new JSONObject("{error: '" + e.getMessage() + "'}");
165                 }
166
167                 response.setCharacterEncoding("UTF-8");
168                 response.setContentType("application/json");
169                 PrintWriter out = response.getWriter();
170                 out.write(j.toString());
171                 return null;
172         }
173
174         @RequestMapping(value = { "/role/removeRoleFunction" }, method = RequestMethod.POST)
175         public ModelAndView removeRoleFunction(HttpServletRequest request, HttpServletResponse response) throws Exception {
176
177                 logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeRoleFunction");
178                 try {
179
180                         ObjectMapper mapper = new ObjectMapper();
181                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
182                         JsonNode root = mapper.readTree(request.getReader());
183                         RoleFunction roleFunction = mapper.readValue(root.get("roleFunction").toString(), RoleFunction.class);
184
185                         Role domainRole = roleService.getRole(new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
186                         doAuditLog("Remove role function {} from role {}", roleFunction.getCode(),
187                                         ServletRequestUtils.getIntParameter(request, "role_id", 0));
188
189                         domainRole.removeRoleFunction(roleFunction.getCode());
190
191                         roleService.saveRole(domainRole);
192
193                         response.setCharacterEncoding("UTF-8");
194                         response.setContentType("application/json");
195                         String responseString = mapper.writeValueAsString(domainRole);
196                         JSONObject j = new JSONObject("{role: " + responseString + "}");
197                         PrintWriter out = response.getWriter();
198                         out.write(j.toString());
199                         return null;
200                 } catch (Exception e) {
201                         logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed", e);
202                         response.setCharacterEncoding("UTF-8");
203                         PrintWriter out = response.getWriter();
204                         out.write(e.getMessage());
205                         return null;
206                 }
207
208         }
209
210         @RequestMapping(value = { "/role/addRoleFunction" }, method = RequestMethod.POST)
211         public ModelAndView addRoleFunction(HttpServletRequest request, HttpServletResponse response) throws Exception {
212
213                 logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeRoleFunction");
214                 try {
215
216                         ObjectMapper mapper = new ObjectMapper();
217                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
218                         JsonNode root = mapper.readTree(request.getReader());
219                         RoleFunction roleFunction = mapper.readValue(root.get("roleFunction").toString(), RoleFunction.class);
220
221                         Role domainRole = roleService.getRole(new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
222
223                         domainRole.addRoleFunction(roleFunction);
224
225                         roleService.saveRole(domainRole);
226                         doAuditLog("Add role function {} to role {}", roleFunction.getCode(),
227                                         ServletRequestUtils.getIntParameter(request, "role_id", 0));
228
229                         response.setCharacterEncoding("UTF-8");
230                         response.setContentType("application/json");
231                         String responseString = mapper.writeValueAsString(domainRole);
232                         JSONObject j = new JSONObject("{role: " + responseString + "}");
233                         PrintWriter out = response.getWriter();
234                         out.write(j.toString());
235                         return null;
236                 } catch (Exception e) {
237                         logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed", e);
238                         response.setCharacterEncoding("UTF-8");
239                         PrintWriter out = response.getWriter();
240                         out.write(e.getMessage());
241                         return null;
242                 }
243
244         }
245
246         @RequestMapping(value = { "/role/removeChildRole" }, method = RequestMethod.POST)
247         public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
248
249                 logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeChileRole");
250                 try {
251                         ObjectMapper mapper = new ObjectMapper();
252                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
253                         JsonNode root = mapper.readTree(request.getReader());
254                         Role childRole = mapper.readValue(root.get("childRole").toString(), Role.class);
255
256                         Role domainRole = roleService.getRole(new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
257
258                         domainRole.removeChildRole(childRole.getId());
259                         doAuditLog("remove child role {} from role {}", childRole.getId(),
260                                         ServletRequestUtils.getIntParameter(request, "role_id", 0));
261
262                         roleService.saveRole(domainRole);
263
264                         response.setCharacterEncoding("UTF-8");
265                         response.setContentType("application/json");
266                         String responseString = mapper.writeValueAsString(domainRole);
267                         JSONObject j = new JSONObject("{role: " + responseString + "}");
268                         PrintWriter out = response.getWriter();
269                         out.write(j.toString());
270                         return null;
271                 } catch (Exception e) {
272                         logger.error(EELFLoggerDelegate.errorLogger, "removeChildRole failed", e);
273                         response.setCharacterEncoding("UTF-8");
274                         PrintWriter out = response.getWriter();
275                         out.write(e.getMessage());
276                         return null;
277                 }
278
279         }
280
281         @RequestMapping(value = { "/role/addChildRole" }, method = RequestMethod.POST)
282         public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
283
284                 logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.addChileRole");
285                 try {
286
287                         ObjectMapper mapper = new ObjectMapper();
288                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
289                         JsonNode root = mapper.readTree(request.getReader());
290                         Role childRole = mapper.readValue(root.get("childRole").toString(), Role.class);
291
292                         Role domainRole = roleService.getRole(new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
293
294                         domainRole.addChildRole(childRole);
295
296                         roleService.saveRole(domainRole);
297                         doAuditLog("Add child role {} to role {}", childRole.getId(),
298                                         ServletRequestUtils.getIntParameter(request, "role_id", 0));
299
300                         response.setCharacterEncoding("UTF-8");
301                         response.setContentType("application/json");
302                         String responseString = mapper.writeValueAsString(domainRole);
303                         JSONObject j = new JSONObject("{role: " + responseString + "}");
304                         PrintWriter out = response.getWriter();
305                         out.write(j.toString());
306                         return null;
307                 } catch (Exception e) {
308                         logger.error(EELFLoggerDelegate.errorLogger, "addChildRole failed", e);
309                         response.setCharacterEncoding("UTF-8");
310                         PrintWriter out = response.getWriter();
311                         out.write(e.getMessage());
312                         return null;
313                 }
314
315         }
316
317         /**
318          * Sets context with begin and end timestamps at current date & time, writes
319          * the specified message and parameters to the audit log, then removes the
320          * timestamps from context.
321          * 
322          * @param message
323          * @param parameters
324          */
325         private void doAuditLog(String message, Object... parameters) {
326                 final String currentDateTime = EELFLoggerAdvice.getCurrentDateTimeUTC();
327                 // Set the MDC with audit properties
328                 MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, currentDateTime);
329                 MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, currentDateTime);
330                 logger.info(EELFLoggerDelegate.auditLogger, message, parameters);
331                 MDC.remove(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
332                 MDC.remove(SystemProperties.AUDITLOG_END_TIMESTAMP);
333         }
334
335         public String getViewName() {
336                 return viewName;
337         }
338
339         public void setViewName(String viewName) {
340                 this.viewName = viewName;
341         }
342 }