Add capability for multi-role support
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / PolicyRolesController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
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  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.controller;
22
23 import java.io.PrintWriter;
24 import java.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Map;
28
29 import javax.servlet.http.HttpServletRequest;
30 import javax.servlet.http.HttpServletResponse;
31
32 import org.json.JSONObject;
33 import org.onap.policy.common.logging.flexlogger.FlexLogger;
34 import org.onap.policy.common.logging.flexlogger.Logger;
35 import org.onap.policy.rest.dao.CommonClassDao;
36 import org.onap.policy.rest.jpa.PolicyEditorScopes;
37 import org.onap.policy.rest.jpa.PolicyRoles;
38 import org.onap.policy.rest.jpa.UserInfo;
39 import org.onap.portalsdk.core.controller.RestrictedBaseController;
40 import org.onap.portalsdk.core.web.support.JsonMessage;
41 import org.onap.portalsdk.core.web.support.UserUtils;
42 import org.springframework.beans.factory.annotation.Autowired;
43 import org.springframework.http.MediaType;
44 import org.springframework.stereotype.Controller;
45 import org.springframework.web.bind.annotation.RequestMapping;
46 import org.springframework.web.servlet.ModelAndView;
47
48 import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
49 import com.fasterxml.jackson.annotation.PropertyAccessor;
50 import com.fasterxml.jackson.databind.DeserializationFeature;
51 import com.fasterxml.jackson.databind.JsonNode;
52 import com.fasterxml.jackson.databind.ObjectMapper;
53
54 @Controller
55 @RequestMapping("/")
56 public class PolicyRolesController extends RestrictedBaseController {
57
58     private static final Logger LOGGER = FlexLogger.getLogger(PolicyRolesController.class);
59
60     @Autowired
61     CommonClassDao commonClassDao;
62
63     public void setCommonClassDao(CommonClassDao commonClassDao) {
64         this.commonClassDao = commonClassDao;
65     }
66
67     List<String> scopelist;
68
69     /**
70      * Gets the policy roles entity data.
71      *
72      * @param request  the request
73      * @param response the response
74      */
75     @RequestMapping(value = { "/get_RolesData" }, method = {
76             org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE)
77     public void getPolicyRolesEntityData(HttpServletRequest request, HttpServletResponse response) {
78         try {
79             Map<String, Object> model = new HashMap<>();
80             ObjectMapper mapper = new ObjectMapper();
81             model.put("rolesDatas", mapper.writeValueAsString(commonClassDao.getUserRoles()));
82             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
83             JSONObject j = new JSONObject(msg);
84             response.getWriter().write(j.toString());
85         } catch (Exception e) {
86             LOGGER.error("Exception Occured" + e);
87         }
88     }
89
90     /**
91      * Save roles and Mechid entity data.
92      *
93      * @param request  the request
94      * @param response the response
95      * @return the model and view
96      */
97     @RequestMapping(value = { "/save_NonSuperRolesData" }, method = {
98             org.springframework.web.bind.annotation.RequestMethod.POST })
99     public ModelAndView SaveRolesEntityData(HttpServletRequest request, HttpServletResponse response) {
100         try {
101             StringBuilder scopeName = new StringBuilder();
102             ObjectMapper mapper = new ObjectMapper();
103             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
104             String userId = UserUtils.getUserSession(request).getOrgUserId();
105             JsonNode root = mapper.readTree(request.getReader());
106             ReadScopes adapter = mapper.readValue(root.get("editRoleData").toString(), ReadScopes.class);
107             for (int i = 0; i < adapter.getScope().size(); i++) {
108                 if (i == 0) {
109                     scopeName.append(adapter.getScope().get(0));
110                 } else {
111                     scopeName.append("," + adapter.getScope().get(i));
112                 }
113             }
114             LOGGER.info(
115                     "****************************************Logging UserID for Roles Function********************************************************");
116             LOGGER.info("UserId:  " + userId + "Updating the Scope for following user" + adapter.getLoginId()
117                     + "ScopeNames" + adapter.getScope());
118             LOGGER.info(
119                     "*********************************************************************************************************************************");
120             UserInfo userInfo = new UserInfo();
121             userInfo.setUserLoginId(adapter.getLoginId().getUserName());
122             userInfo.setUserName(adapter.getLoginId().getUserName());
123
124             boolean checkNew = false;
125             if (adapter.getId() == 0 && "mechid".equals(adapter.getRole())) {
126                 // Save new mechid scopes entity data.
127                 LOGGER.info(
128                         "****************************************Logging UserID for New Mechid Function***************************************************");
129                 LOGGER.info("UserId:" + userId + "Adding new mechid-scopes for following user" + adapter.getLoginId()
130                         + "ScopeNames " + adapter.getScope());
131                 LOGGER.info(
132                         "*********************************************************************************************************************************");
133                 // First add the mechid to userinfo
134                 commonClassDao.save(userInfo);
135                 checkNew = true;
136             }
137
138             PolicyRoles roles = new PolicyRoles();
139             roles.setId(adapter.getId());
140             roles.setLoginId(adapter.getLoginId());
141             roles.setRole(adapter.getRole());
142             roles.setScope(scopeName.toString());
143             if (checkNew) {
144                 roles.setLoginId(userInfo);
145                 commonClassDao.save(roles);
146             } else {
147                 commonClassDao.update(roles);
148             }
149             response.setCharacterEncoding("UTF-8");
150             response.setContentType("application / json");
151             request.setCharacterEncoding("UTF-8");
152
153             PrintWriter out = response.getWriter();
154             String responseString = mapper.writeValueAsString(commonClassDao.getUserRoles());
155             JSONObject j = new JSONObject("{rolesDatas: " + responseString + "}");
156
157             out.write(j.toString());
158         } catch (Exception e) {
159             LOGGER.error("Exception Occured" + e);
160         }
161         return null;
162     }
163
164     /**
165      * Gets the policy scopes entity data.
166      *
167      * @param request  the request
168      * @param response the response
169      */
170     @RequestMapping(value = { "/get_PolicyRolesScopeData" }, method = {
171             org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE)
172     public void getPolicyScopesEntityData(HttpServletRequest request, HttpServletResponse response) {
173         try {
174             scopelist = new ArrayList<>();
175             Map<String, Object> model = new HashMap<>();
176             ObjectMapper mapper = new ObjectMapper();
177             mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
178             List<String> scopesData = commonClassDao.getDataByColumn(PolicyEditorScopes.class, "scopeName");
179             model.put("scopeDatas", mapper.writeValueAsString(scopesData));
180             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
181             JSONObject j = new JSONObject(msg);
182             response.getWriter().write(j.toString());
183         } catch (Exception e) {
184             LOGGER.error("Exception Occured" + e);
185         }
186     }
187 }
188
189 class ReadScopes {
190     private int id;
191     private UserInfo loginId;
192     private String role;
193     private List<String> scope;
194
195     public int getId() {
196         return id;
197     }
198
199     public void setId(int id) {
200         this.id = id;
201     }
202
203     public UserInfo getLoginId() {
204         return loginId;
205     }
206
207     public void setLoginId(UserInfo loginId) {
208         this.loginId = loginId;
209     }
210
211     public String getRole() {
212         return role;
213     }
214
215     public void setRole(String role) {
216         this.role = role;
217     }
218
219     public List<String> getScope() {
220         return scope;
221     }
222
223     public void setScope(List<String> scope) {
224         this.scope = scope;
225     }
226
227 }