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