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