Merge "Adding simple, missing junit"
[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.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33
34 import javax.servlet.http.HttpServletRequest;
35 import javax.servlet.http.HttpServletResponse;
36 import lombok.Getter;
37 import lombok.Setter;
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             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).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(
98             value = {"/save_NonSuperRolesData"},
99             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
100     public ModelAndView SaveRolesEntityData(HttpServletRequest request, HttpServletResponse response) {
101         try {
102             StringBuilder scopeName = new StringBuilder();
103             ObjectMapper mapper = new ObjectMapper();
104             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
105             String userId = UserUtils.getUserSession(request).getOrgUserId();
106             JsonNode root = mapper.readTree(request.getReader());
107             ReadScopes adapter = mapper.readValue(root.get("editRoleData").toString(), ReadScopes.class);
108             for (int i = 0; i < adapter.getScope().size(); i++) {
109                 if (i == 0) {
110                     scopeName.append(adapter.getScope().get(0));
111                 } else {
112                     scopeName.append("," + adapter.getScope().get(i));
113                 }
114             }
115             LOGGER.info(
116                     "*************************Logging UserID for Roles Function***********************************");
117             LOGGER.info("UserId:  " + userId + "Updating the Scope for following user" + adapter.getLoginId()
118                     + "ScopeNames" + adapter.getScope());
119             LOGGER.info(
120                     "*********************************************************************************************");
121             UserInfo userInfo = new UserInfo();
122             userInfo.setUserLoginId(adapter.getLoginId().getUserName());
123             userInfo.setUserName(adapter.getLoginId().getUserName());
124
125             boolean checkNew = false;
126             if (adapter.getId() == 0 && "mechid".equals(adapter.getRole())) {
127                 // Save new mechid scopes entity data.
128                 LOGGER.info(
129                         "*********************Logging UserID for New Mechid Function********************************");
130                 LOGGER.info("UserId:" + userId + "Adding new mechid-scopes for following user" + adapter.getLoginId()
131                         + "ScopeNames " + adapter.getScope());
132                 LOGGER.info(
133                         "*******************************************************************************************");
134                 // First add the mechid to userinfo
135                 commonClassDao.save(userInfo);
136                 checkNew = true;
137             }
138
139             PolicyRoles roles = new PolicyRoles();
140             roles.setId(adapter.getId());
141             roles.setLoginId(adapter.getLoginId());
142             roles.setRole(adapter.getRole());
143             roles.setScope(scopeName.toString());
144             if (checkNew) {
145                 roles.setLoginId(userInfo);
146                 commonClassDao.save(roles);
147             } else {
148                 commonClassDao.update(roles);
149             }
150             response.setCharacterEncoding("UTF-8");
151             response.setContentType("application / json");
152             request.setCharacterEncoding("UTF-8");
153             response.getWriter().write(new JSONObject("{rolesDatas: "
154                 + mapper.writeValueAsString(commonClassDao.getUserRoles()) + "}").toString());
155         } catch (Exception e) {
156             LOGGER.error("Exception Occured" + e);
157         }
158         return null;
159     }
160
161     /**
162      * Gets the policy scopes entity data.
163      *
164      * @param request the request
165      * @param response the response
166      */
167     @RequestMapping(
168             value = {"/get_PolicyRolesScopeData"},
169             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
170             produces = MediaType.APPLICATION_JSON_VALUE)
171     public void getPolicyScopesEntityData(HttpServletRequest request, HttpServletResponse response) {
172         try {
173             scopelist = new ArrayList<>();
174             Map<String, Object> model = new HashMap<>();
175             ObjectMapper mapper = new ObjectMapper();
176             mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
177             List<String> scopesData = commonClassDao.getDataByColumn(PolicyEditorScopes.class, "scopeName");
178             model.put("scopeDatas", mapper.writeValueAsString(scopesData));
179             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
180         } catch (Exception e) {
181             LOGGER.error("Exception Occured" + e);
182         }
183     }
184 }
185
186 @Setter
187 @Getter
188 class ReadScopes {
189     private int id;
190     private UserInfo loginId;
191     private String role;
192     private List<String> scope;
193 }