summaryrefslogtreecommitdiffstats
path: root/ecomp-sdk/epsdk-app-common/src/main/java/org/onap/portalapp/controller/core/RoleController.java
blob: 8306e91dd3a32f309f5c669d09db4ff783fd90b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
/*
 * ============LICENSE_START==========================================
 * ONAP Portal SDK
 * ===================================================================
 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
 * ===================================================================
 *
 * Unless otherwise specified, all software contained herein is licensed
 * under the Apache License, Version 2.0 (the "License");
 * you may not use this software except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Unless otherwise specified, all documentation contained herein is licensed
 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
 * you may not use this documentation except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             https://creativecommons.org/licenses/by/4.0/
 *
 * Unless required by applicable law or agreed to in writing, documentation
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * ============LICENSE_END============================================
 *
 * 
 */
package org.onap.portalapp.controller.core;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.onap.portalsdk.core.domain.Role;
import org.onap.portalsdk.core.domain.RoleFunction;
import org.onap.portalsdk.core.domain.User;
import org.onap.portalsdk.core.logging.aspect.EELFLoggerAdvice;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.service.RoleService;
import org.onap.portalsdk.core.util.SystemProperties;
import org.onap.portalsdk.core.web.support.JsonMessage;
import org.onap.portalsdk.core.web.support.UserUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

@Controller
@RequestMapping("/")
public class RoleController extends RestrictedBaseController {

	private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleController.class);

	@Autowired
	private RoleService roleService;

	private String viewName;

	@RequestMapping(value = { "/role" }, method = RequestMethod.GET)
	public ModelAndView role(HttpServletRequest request) throws IOException {
		Map<String, Object> model = new HashMap<>();
		ObjectMapper mapper = new ObjectMapper();
		User user = UserUtils.getUserSession(request);

		Role role = roleService.getRole(user.getOrgUserId(),
				new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
		logger.info("role_id" + role.getId());
		try {
			model.put("availableRoleFunctions",
					mapper.writeValueAsString(roleService.getRoleFunctions(user.getOrgUserId())));
			model.put("availableRoles",
					mapper.writeValueAsString(roleService.getAvailableChildRoles(user.getOrgUserId(), role.getId())));
			model.put("role", mapper.writeValueAsString(role));
		} catch (Exception e) {
			logger.error("role: failed", e);
			logger.error(EELFLoggerDelegate.errorLogger, "role failed", e);
		}
		return new ModelAndView(getViewName(), model);
	}

	@RequestMapping(value = { "/get_role" }, method = RequestMethod.GET)
	public void getRole(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, Object> model = new HashMap<>();
		ObjectMapper mapper = new ObjectMapper();
		User user = UserUtils.getUserSession(request);

		Role role = roleService.getRole(user.getOrgUserId(),
				new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
		logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + role.getId());
		try {
			model.put("availableRoleFunctions",
					mapper.writeValueAsString(roleService.getRoleFunctions(user.getOrgUserId())));
			model.put("availableRoles",
					mapper.writeValueAsString(roleService.getAvailableChildRoles(user.getOrgUserId(), role.getId())));
			model.put("role", mapper.writeValueAsString(role));

			JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
			JSONObject j = new JSONObject(msg);
			response.getWriter().write(j.toString());
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "getRole failed", e);
		}

	}

	/**
	 * Creates a new role or updates an existing role.
	 * 
	 * @param request
	 * @param response
	 * @return Always returns null.
	 * @throws IOException
	 *             If the write to the result project fails
	 */
	@RequestMapping(value = { "/role/saveRole" }, method = RequestMethod.POST)
	public ModelAndView saveRole(HttpServletRequest request, HttpServletResponse response) throws IOException {
		JSONObject j = null;
		User user = UserUtils.getUserSession(request);
		logger.debug(EELFLoggerDelegate.debugLogger, "RoleController.save");
		try {
			ObjectMapper mapper = new ObjectMapper();
			mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			JsonNode root = mapper.readTree(request.getReader());
			Role role = mapper.readValue(root.get("role").toString(), Role.class);

			List<Role> childRoles = mapper.readValue(root.get("childRoles").toString(),
					TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));

			List<RoleFunction> roleFunctions = mapper.readValue(root.get("roleFunctions").toString(),
					TypeFactory.defaultInstance().constructCollectionType(List.class, RoleFunction.class));

			Role domainRole;
			if (role.getId() != null) {
				doAuditLog("saveRole: updating existing role {}", role.getId());
				domainRole = roleService.getRole(user.getOrgUserId(), role.getId());
				domainRole.setName(role.getName());
				domainRole.setPriority(role.getPriority());
			} else {
				doAuditLog("saveRole: creating new role", role.getName());
				// check for existing role of same name
				List<Role> roles = roleService.getAvailableRoles(user.getOrgUserId());
				for (Role existRole : roles)
					if (existRole.getName().equalsIgnoreCase(role.getName()))
						throw new Exception("role already exists: " + existRole.getName());

				domainRole = new Role();
				domainRole.setName(role.getName());
				domainRole.setPriority(role.getPriority());
				if (role.getChildRoles() != null && role.getChildRoles().size() > 0) {
					for (Object childRole : childRoles) {
						domainRole.addChildRole((Role) childRole);
					}
				}
			}
			if (role.getRoleFunctions() != null && role.getRoleFunctions().size() > 0) {
				domainRole.setRoleFunctions(new TreeSet());
				for (Object roleFunction : roleFunctions) {
					domainRole.addRoleFunction((RoleFunction) roleFunction);
				}
			}
			roleService.saveRole(user.getOrgUserId(), domainRole);

			String responseString = mapper.writeValueAsString(domainRole);
			j = new JSONObject("{role: " + responseString + "}");
		} catch (Exception e) {
			// Produce JSON error message
			logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e);
			j = new JSONObject("{error: '" + e.getMessage() + "'}");
		}

		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		out.write(j.toString());
		return null;
	}

	@RequestMapping(value = { "/role/removeRoleFunction" }, method = RequestMethod.POST)
	public ModelAndView removeRoleFunction(HttpServletRequest request, HttpServletResponse response) throws IOException {
		User user = UserUtils.getUserSession(request);
		logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeRoleFunction");
		try {

			ObjectMapper mapper = new ObjectMapper();
			mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			JsonNode root = mapper.readTree(request.getReader());
			RoleFunction roleFunction = mapper.readValue(root.get("roleFunction").toString(), RoleFunction.class);

			Role domainRole = roleService.getRole(user.getOrgUserId(),
					new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));
			doAuditLog("Remove role function {} from role {}", roleFunction.getCode(),
					ServletRequestUtils.getIntParameter(request, "role_id", 0));

			domainRole.removeRoleFunction(roleFunction.getCode());

			roleService.saveRole(user.getOrgUserId(), domainRole);

			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json");
			String responseString = mapper.writeValueAsString(domainRole);
			JSONObject j = new JSONObject("{role: " + responseString + "}");
			PrintWriter out = response.getWriter();
			out.write(j.toString());
			return null;
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed", e);
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			out.write("An error occurred removeRole failed in the removeRoleFunction");
			return null;
		}

	}

	@RequestMapping(value = { "/role/addRoleFunction" }, method = RequestMethod.POST)
	public ModelAndView addRoleFunction(HttpServletRequest request, HttpServletResponse response) throws IOException {
		User user = UserUtils.getUserSession(request);
		logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeRoleFunction");
		try {

			ObjectMapper mapper = new ObjectMapper();
			mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			JsonNode root = mapper.readTree(request.getReader());
			RoleFunction roleFunction = mapper.readValue(root.get("roleFunction").toString(), RoleFunction.class);

			Role domainRole = roleService.getRole(user.getOrgUserId(),
					new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));

			domainRole.addRoleFunction(roleFunction);

			roleService.saveRole(user.getOrgUserId(), domainRole);
			doAuditLog("Add role function {} to role {}", roleFunction.getCode(),
					ServletRequestUtils.getIntParameter(request, "role_id", 0));

			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json");
			String responseString = mapper.writeValueAsString(domainRole);
			JSONObject j = new JSONObject("{role: " + responseString + "}");
			PrintWriter out = response.getWriter();
			out.write(j.toString());
			return null;
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed", e);
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			out.write("An error occurred removeRoleFunction failed in the removeRoleFunction");
			return null;
		}

	}

	@RequestMapping(value = { "/role/removeChildRole" }, method = RequestMethod.POST)
	public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws IOException {
		User user = UserUtils.getUserSession(request);
		logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.removeChileRole");
		try {
			ObjectMapper mapper = new ObjectMapper();
			mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			JsonNode root = mapper.readTree(request.getReader());
			Role childRole = mapper.readValue(root.get("childRole").toString(), Role.class);

			Role domainRole = roleService.getRole(user.getOrgUserId(),
					new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0)));

			domainRole.removeChildRole(childRole.getId());
			doAuditLog("remove child role {} from role {}", childRole.getId(),
					ServletRequestUtils.getIntParameter(request, "role_id", 0));

			roleService.saveRole(user.getOrgUserId(), domainRole);

			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json");
			String responseString = mapper.writeValueAsString(domainRole);
			JSONObject j = new JSONObject("{role: " + responseString + "}");
			PrintWriter out = response.getWriter();
			out.write(j.toString());
			return null;
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "removeChildRole failed", e);
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			out.write("An error occurred removeChildRole failed in the removeChildRole()");
			return null;
		}

	}

	@RequestMapping(value = { "/role/addChildRole" }, method = RequestMethod.POST)
	public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws IOException {
		User user = UserUtils.getUserSession(request);
		logger.info(EELFLoggerDelegate.applicationLogger, "RoleController.addChileRole");
		try {

			ObjectMapper mapper = new ObjectMapper();
			mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			JsonNode root = mapper.readTree(request.getReader());
			Role childRole = mapper.readValue(root.get("childRole").toString(), Role.class);
			Long role_id = new Long(ServletRequestUtils.getIntParameter(request, "role_id", 0));

			Role domainRole = roleService.getRole(user.getOrgUserId(), role_id);

			domainRole.addChildRole(childRole);

			roleService.saveRole(user.getOrgUserId(), domainRole);
			doAuditLog("Add child role {} to role {}", childRole.getId(),
					ServletRequestUtils.getIntParameter(request, "role_id", 0));

			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json");
			String responseString = mapper.writeValueAsString(domainRole);
			JSONObject j = new JSONObject("{role: " + responseString + "}");
			PrintWriter out = response.getWriter();
			out.write(j.toString());
			return null;
		} catch (Exception e) {
			logger.error(EELFLoggerDelegate.errorLogger, "addChildRole failed", e);
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			out.write("An error occurred addChildRole failed in the addChildRole()");
			return null;
		}

	}

	/**
	 * Sets context with begin and end timestamps at current date & time, writes the
	 * specified message and parameters to the audit log, then removes the
	 * timestamps from context.
	 * 
	 * @param message
	 * @param parameters
	 */
	private void doAuditLog(String message, Object... parameters) {
		final String currentDateTime = EELFLoggerAdvice.getCurrentDateTimeUTC();
		// Set the MDC with audit properties
		MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, currentDateTime);
		MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, currentDateTime);
		logger.info(EELFLoggerDelegate.auditLogger, message, parameters);
		MDC.remove(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
		MDC.remove(SystemProperties.AUDITLOG_END_TIMESTAMP);
	}

	@Override
	public String getViewName() {
		return viewName;
	}

	@Override
	public void setViewName(String viewName) {
		this.viewName = viewName;
	}
	
}