5d12f4aa4d342253fba8c713a7805d3dd38e3fbb
[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() != null && role.getChildRoles().size() > 0 ){
153 //                              if (role.getChildRoles().size() > 0 ) {
154                                         for (Object childRole : childRoles) {
155                                                 domainRole.addChildRole((Role) childRole);
156                                         }
157 //                              }
158                                 }
159                                 if(role.getRoleFunctions() != null && role.getRoleFunctions().size() > 0){
160 //                              if (role.getRoleFunctions().size() > 0) {
161                                         for (Object roleFunction : roleFunctions) {
162                                                 domainRole.addRoleFunction((RoleFunction) roleFunction);
163                                         }
164 //                              }
165                                 }
166                         }
167
168                         roleService.saveRole(user.getOrgUserId(),domainRole);
169
170                         String responseString = mapper.writeValueAsString(domainRole);
171                         j = new JSONObject("{role: " + responseString + "}");
172                 } catch (Exception e) {
173                         // Produce JSON error message
174                         logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e);
175                         j = new JSONObject("{error: '" + e.getMessage() + "'}");
176                 }
177
178                 response.setCharacterEncoding("UTF-8");
179                 response.setContentType("application/json");
180                 PrintWriter out = response.getWriter();
181                 out.write(j.toString());
182                 return null;
183         }
184
185         @RequestMapping(value = { "/role/removeRoleFunction" }, method = RequestMethod.POST)
186         public ModelAndView removeRoleFunction(HttpServletRequest request, HttpServletResponse response) throws Exception {
187                 User user = UserUtils.getUserSession(request);
188                 logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeRoleFunction");
189                 try {
190
191                         ObjectMapper mapper = new ObjectMapper();
192                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
193                         JsonNode root = mapper.readTree(request.getReader());
194                         RoleFunction roleFunction = mapper.readValue(root.get("roleFunction").toString(), RoleFunction.class);
195
196                         Role domainRole = roleService.getRole(user.getOrgUserId(),new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
197                         doAuditLog("Remove role function {} from role {}", roleFunction.getCode(),
198                                         ServletRequestUtils.getIntParameter(request, "role_id", 0));
199
200                         domainRole.removeRoleFunction(roleFunction.getCode());
201
202                         roleService.saveRole(user.getOrgUserId(),domainRole);
203
204                         response.setCharacterEncoding("UTF-8");
205                         response.setContentType("application/json");
206                         String responseString = mapper.writeValueAsString(domainRole);
207                         JSONObject j = new JSONObject("{role: " + responseString + "}");
208                         PrintWriter out = response.getWriter();
209                         out.write(j.toString());
210                         return null;
211                 } catch (Exception e) {
212                         logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed", e);
213                         response.setCharacterEncoding("UTF-8");
214                         PrintWriter out = response.getWriter();
215                         out.write(e.getMessage());
216                         return null;
217                 }
218
219         }
220
221         @RequestMapping(value = { "/role/addRoleFunction" }, method = RequestMethod.POST)
222         public ModelAndView addRoleFunction(HttpServletRequest request, HttpServletResponse response) throws Exception {
223                 User user = UserUtils.getUserSession(request);
224                 logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeRoleFunction");
225                 try {
226
227                         ObjectMapper mapper = new ObjectMapper();
228                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
229                         JsonNode root = mapper.readTree(request.getReader());
230                         RoleFunction roleFunction = mapper.readValue(root.get("roleFunction").toString(), RoleFunction.class);
231
232                         Role domainRole = roleService.getRole(user.getOrgUserId(),new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
233
234                         domainRole.addRoleFunction(roleFunction);
235
236                         roleService.saveRole(user.getOrgUserId(),domainRole);
237                         doAuditLog("Add role function {} to role {}", roleFunction.getCode(),
238                                         ServletRequestUtils.getIntParameter(request, "role_id", 0));
239
240                         response.setCharacterEncoding("UTF-8");
241                         response.setContentType("application/json");
242                         String responseString = mapper.writeValueAsString(domainRole);
243                         JSONObject j = new JSONObject("{role: " + responseString + "}");
244                         PrintWriter out = response.getWriter();
245                         out.write(j.toString());
246                         return null;
247                 } catch (Exception e) {
248                         logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed", e);
249                         response.setCharacterEncoding("UTF-8");
250                         PrintWriter out = response.getWriter();
251                         out.write(e.getMessage());
252                         return null;
253                 }
254
255         }
256
257         @RequestMapping(value = { "/role/removeChildRole" }, method = RequestMethod.POST)
258         public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
259                 User user = UserUtils.getUserSession(request);
260                 logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeChileRole");
261                 try {
262                         ObjectMapper mapper = new ObjectMapper();
263                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
264                         JsonNode root = mapper.readTree(request.getReader());
265                         Role childRole = mapper.readValue(root.get("childRole").toString(), Role.class);
266
267                         Role domainRole = roleService.getRole(user.getOrgUserId(),new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
268
269                         domainRole.removeChildRole(childRole.getId());
270                         doAuditLog("remove child role {} from role {}", childRole.getId(),
271                                         ServletRequestUtils.getIntParameter(request, "role_id", 0));
272
273                         roleService.saveRole(user.getOrgUserId(),domainRole);
274
275                         response.setCharacterEncoding("UTF-8");
276                         response.setContentType("application/json");
277                         String responseString = mapper.writeValueAsString(domainRole);
278                         JSONObject j = new JSONObject("{role: " + responseString + "}");
279                         PrintWriter out = response.getWriter();
280                         out.write(j.toString());
281                         return null;
282                 } catch (Exception e) {
283                         logger.error(EELFLoggerDelegate.errorLogger, "removeChildRole failed", e);
284                         response.setCharacterEncoding("UTF-8");
285                         PrintWriter out = response.getWriter();
286                         out.write(e.getMessage());
287                         return null;
288                 }
289
290         }
291
292         @RequestMapping(value = { "/role/addChildRole" }, method = RequestMethod.POST)
293         public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
294                 User user = UserUtils.getUserSession(request);
295                 logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.addChileRole");
296                 try {
297
298                         ObjectMapper mapper = new ObjectMapper();
299                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
300                         JsonNode root = mapper.readTree(request.getReader());
301                         Role childRole = mapper.readValue(root.get("childRole").toString(), Role.class);
302                         long role_id = new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0));
303
304                         Role domainRole = roleService.getRole(user.getOrgUserId(),role_id );
305
306                         domainRole.addChildRole(childRole);
307
308                         roleService.saveRole(user.getOrgUserId(),domainRole);
309                         doAuditLog("Add child role {} to role {}", childRole.getId(),
310                                         ServletRequestUtils.getIntParameter(request, "role_id", 0));
311
312                         response.setCharacterEncoding("UTF-8");
313                         response.setContentType("application/json");
314                         String responseString = mapper.writeValueAsString(domainRole);
315                         JSONObject j = new JSONObject("{role: " + responseString + "}");
316                         PrintWriter out = response.getWriter();
317                         out.write(j.toString());
318                         return null;
319                 } catch (Exception e) {
320                         logger.error(EELFLoggerDelegate.errorLogger, "addChildRole failed", e);
321                         response.setCharacterEncoding("UTF-8");
322                         PrintWriter out = response.getWriter();
323                         out.write(e.getMessage());
324                         return null;
325                 }
326
327         }
328
329         /**
330          * Sets context with begin and end timestamps at current date & time, writes
331          * the specified message and parameters to the audit log, then removes the
332          * timestamps from context.
333          * 
334          * @param message
335          * @param parameters
336          */
337         private void doAuditLog(String message, Object... parameters) {
338                 final String currentDateTime = EELFLoggerAdvice.getCurrentDateTimeUTC();
339                 // Set the MDC with audit properties
340                 MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, currentDateTime);
341                 MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, currentDateTime);
342                 logger.info(EELFLoggerDelegate.auditLogger, message, parameters);
343                 MDC.remove(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
344                 MDC.remove(SystemProperties.AUDITLOG_END_TIMESTAMP);
345         }
346
347         public String getViewName() {
348                 return viewName;
349         }
350
351         public void setViewName(String viewName) {
352                 this.viewName = viewName;
353         }
354 }