More sonar cleanup and line consolidation
[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             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
86         } catch (Exception e) {
87             LOGGER.error("Exception Occured" + e);
88         }
89     }
90
91     /**
92      * Save roles and Mechid entity data.
93      *
94      * @param request the request
95      * @param response the response
96      * @return the model and view
97      */
98     @RequestMapping(
99             value = {"/save_NonSuperRolesData"},
100             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
101     public ModelAndView SaveRolesEntityData(HttpServletRequest request, HttpServletResponse response) {
102         try {
103             StringBuilder scopeName = new StringBuilder();
104             ObjectMapper mapper = new ObjectMapper();
105             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
106             String userId = UserUtils.getUserSession(request).getOrgUserId();
107             JsonNode root = mapper.readTree(request.getReader());
108             ReadScopes adapter = mapper.readValue(root.get("editRoleData").toString(), ReadScopes.class);
109             for (int i = 0; i < adapter.getScope().size(); i++) {
110                 if (i == 0) {
111                     scopeName.append(adapter.getScope().get(0));
112                 } else {
113                     scopeName.append("," + adapter.getScope().get(i));
114                 }
115             }
116             LOGGER.info(
117                     "*************************Logging UserID for Roles Function***********************************");
118             LOGGER.info("UserId:  " + userId + "Updating the Scope for following user" + adapter.getLoginId()
119                     + "ScopeNames" + adapter.getScope());
120             LOGGER.info(
121                     "*********************************************************************************************");
122             UserInfo userInfo = new UserInfo();
123             userInfo.setUserLoginId(adapter.getLoginId().getUserName());
124             userInfo.setUserName(adapter.getLoginId().getUserName());
125
126             boolean checkNew = false;
127             if (adapter.getId() == 0 && "mechid".equals(adapter.getRole())) {
128                 // Save new mechid scopes entity data.
129                 LOGGER.info(
130                         "*********************Logging UserID for New Mechid Function********************************");
131                 LOGGER.info("UserId:" + userId + "Adding new mechid-scopes for following user" + adapter.getLoginId()
132                         + "ScopeNames " + adapter.getScope());
133                 LOGGER.info(
134                         "*******************************************************************************************");
135                 // First add the mechid to userinfo
136                 commonClassDao.save(userInfo);
137                 checkNew = true;
138             }
139
140             PolicyRoles roles = new PolicyRoles();
141             roles.setId(adapter.getId());
142             roles.setLoginId(adapter.getLoginId());
143             roles.setRole(adapter.getRole());
144             roles.setScope(scopeName.toString());
145             if (checkNew) {
146                 roles.setLoginId(userInfo);
147                 commonClassDao.save(roles);
148             } else {
149                 commonClassDao.update(roles);
150             }
151             response.setCharacterEncoding("UTF-8");
152             response.setContentType("application / json");
153             request.setCharacterEncoding("UTF-8");
154             response.getWriter().write(new JSONObject("{rolesDatas: "
155                 + mapper.writeValueAsString(commonClassDao.getUserRoles()) + "}").toString());
156         } catch (Exception e) {
157             LOGGER.error("Exception Occured" + e);
158         }
159         return null;
160     }
161
162     /**
163      * Gets the policy scopes entity data.
164      *
165      * @param request the request
166      * @param response the response
167      */
168     @RequestMapping(
169             value = {"/get_PolicyRolesScopeData"},
170             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
171             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             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
181         } catch (Exception e) {
182             LOGGER.error("Exception Occured" + e);
183         }
184     }
185 }
186
187 @Setter
188 @Getter
189 class ReadScopes {
190     private int id;
191     private UserInfo loginId;
192     private String role;
193     private List<String> scope;
194 }