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