2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.controller;
24 import java.io.BufferedWriter;
26 import java.io.FileWriter;
27 import java.io.IOException;
28 import java.io.PrintWriter;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.HashSet;
35 import java.util.Iterator;
36 import java.util.LinkedHashMap;
37 import java.util.List;
41 import javax.script.SimpleBindings;
42 import javax.servlet.http.HttpServletRequest;
43 import javax.servlet.http.HttpServletResponse;
45 import org.json.JSONObject;
46 import org.onap.policy.common.logging.flexlogger.FlexLogger;
47 import org.onap.policy.common.logging.flexlogger.Logger;
48 import org.onap.policy.model.PDPGroupContainer;
49 import org.onap.policy.model.PDPPolicyContainer;
50 import org.onap.policy.model.Roles;
51 import org.onap.policy.rest.adapter.AutoPushTabAdapter;
52 import org.onap.policy.rest.dao.CommonClassDao;
53 import org.onap.policy.rest.jpa.PolicyEntity;
54 import org.onap.policy.rest.jpa.PolicyVersion;
55 import org.onap.policy.utils.PolicyUtils;
56 import org.onap.policy.xacml.api.XACMLErrorConstants;
57 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
58 import org.onap.policy.xacml.std.pap.StdPDPGroup;
59 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
60 import org.onap.portalsdk.core.controller.RestrictedBaseController;
61 import org.onap.portalsdk.core.web.support.JsonMessage;
62 import org.onap.portalsdk.core.web.support.UserUtils;
63 import org.springframework.beans.factory.annotation.Autowired;
64 import org.springframework.http.MediaType;
65 import org.springframework.stereotype.Controller;
66 import org.springframework.web.bind.annotation.RequestMapping;
67 import org.springframework.web.servlet.ModelAndView;
69 import com.att.research.xacml.api.pap.PAPException;
70 import com.att.research.xacml.api.pap.PDPPolicy;
71 import com.fasterxml.jackson.databind.DeserializationFeature;
72 import com.fasterxml.jackson.databind.JsonNode;
73 import com.fasterxml.jackson.databind.ObjectMapper;
77 @RequestMapping({"/"})
78 public class AutoPushController extends RestrictedBaseController{
80 private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
83 CommonClassDao commonClassDao;
85 private PDPGroupContainer container;
86 protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>());
88 private PDPPolicyContainer policyContainer;
90 private PolicyController policyController;
91 public PolicyController getPolicyController() {
92 return policyController;
95 public void setPolicyController(PolicyController policyController) {
96 this.policyController = policyController;
99 private List<Object> data;
101 public synchronized void refreshGroups() {
102 synchronized(this.groups) {
105 PolicyController controller = getPolicyControllerInstance();
106 this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
107 } catch (PAPException e) {
108 String message = "Unable to retrieve Groups from server: " + e;
109 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
115 private PolicyController getPolicyControllerInstance(){
116 return policyController != null ? getPolicyController() : new PolicyController();
119 @RequestMapping(value={"/get_AutoPushPoliciesContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
120 public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response){
124 data = new ArrayList<>();
125 String userId = UserUtils.getUserSession(request).getOrgUserId();
126 Map<String, Object> model = new HashMap<>();
127 ObjectMapper mapper = new ObjectMapper();
128 PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
129 List<Object> userRoles = controller.getRoles(userId);
130 roles = new ArrayList<>();
131 scopes = new HashSet<>();
132 for(Object role: userRoles){
133 Roles userRole = (Roles) role;
134 roles.add(userRole.getRole());
135 if(userRole.getScope() != null){
136 if(userRole.getScope().contains(",")){
137 String[] multipleScopes = userRole.getScope().split(",");
138 for(int i =0; i < multipleScopes.length; i++){
139 scopes.add(multipleScopes[i]);
142 if(!"".equals(userRole.getScope())){
143 scopes.add(userRole.getScope());
148 if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) {
149 data = commonClassDao.getData(PolicyVersion.class);
151 if(!scopes.isEmpty()){
152 for(String scope : scopes){
154 String query = "From PolicyVersion where policy_name like :scope and id > 0";
155 SimpleBindings params = new SimpleBindings();
156 params.put("scope", scope);
157 List<Object> filterdatas = commonClassDao.getDataByQuery(query, params);
158 if(filterdatas != null){
159 for(int i =0; i < filterdatas.size(); i++){
160 data.add(filterdatas.get(i));
165 PolicyVersion emptyPolicyName = new PolicyVersion();
166 emptyPolicyName.setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
167 data.add(emptyPolicyName);
170 model.put("policydatas", mapper.writeValueAsString(data));
171 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
172 JSONObject j = new JSONObject(msg);
173 response.getWriter().write(j.toString());
176 logger.error("Exception Occured"+e);
180 @RequestMapping(value={"/auto_Push/PushPolicyToPDP.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
181 public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
183 ArrayList<Object> selectedPDPS = new ArrayList<>();
184 ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
185 PolicyController controller = getPolicyControllerInstance();
186 this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
187 ObjectMapper mapper = new ObjectMapper();
188 this.container = new PDPGroupContainer(controller.getPapEngine());
189 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
190 JsonNode root = mapper.readTree(request.getReader());
192 String userId = UserUtils.getUserSession(request).getOrgUserId();
193 logger.info("****************************************Logging UserID while Pushing Policy to PDP Group*****************************************");
194 logger.info("UserId: " + userId + "Push Policy Data: "+ root.get("pushTabData").toString());
195 logger.info("***********************************************************************************************************************************");
197 AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
198 for (Object pdpGroupId : adapter.getPdpDatas()) {
199 LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>)pdpGroupId;
200 for(OnapPDPGroup pdpGroup : this.groups){
201 if(pdpGroup.getId().equals(selectedPDP.get("id"))){
202 selectedPDPS.add(pdpGroup);
207 for (Object policyId : adapter.getPolicyDatas()) {
208 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId;
209 String policyName = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
210 selectedPoliciesInUI.add(policyName);
213 for (Object pdpDestinationGroupId : selectedPDPS) {
214 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
215 Set<PDPPolicy> selectedPolicies = new HashSet<>();
216 for (String policyId : selectedPoliciesInUI) {
217 logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
220 // Get the current selection
221 String selectedItem = policyId;
223 assert selectedItem != null;
224 // create the id of the target file
225 // Our standard for file naming is:
226 // <domain>.<filename>.<version>.xml
227 // since the file name usually has a ".xml", we need to strip
229 // before adding the other parts
230 String name = selectedItem.replace(File.separator, ".");
232 if (id.endsWith(".xml")) {
233 id = id.replace(".xml", "");
234 id = id.substring(0, id.lastIndexOf('.'));
237 // Default policy to be Root policy; user can change to deferred
240 StdPDPPolicy selectedPolicy = null;
241 String dbCheckName = name;
242 if(dbCheckName.contains("Config_")){
243 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
244 }else if(dbCheckName.contains("Action_")){
245 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
246 }else if(dbCheckName.contains("Decision_")){
247 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
249 String[] split = dbCheckName.split(":");
250 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
251 SimpleBindings policyParams = new SimpleBindings();
252 policyParams.put("split_1", split[1]);
253 policyParams.put("split_0", split[0]);
254 List<Object> queryData = controller.getDataByQuery(query, policyParams);
255 PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
256 File temp = new File(name);
257 BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
258 bw.write(policyEntity.getPolicyData());
260 URI selectedURI = temp.toURI();
264 selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
265 } catch (IOException e) {
266 logger.error("Unable to create policy '" + name + "': "+ e.getMessage(), e);
268 StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
269 if (selectedPolicy != null) {
270 // Add Current policies from container
271 for (OnapPDPGroup group : container.getGroups()) {
272 if (group.getId().equals(selectedGroup.getId())) {
273 currentPoliciesInGroup.addAll(group.getPolicies());
276 // copy policy to PAP
278 controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
279 } catch (PAPException e) {
280 logger.error("Exception Occured"+e);
283 selectedPolicies.add(selectedPolicy);
287 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
288 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
289 updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps());
290 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
291 updatedGroupObject.setStatus(pdpGroup.getStatus());
292 updatedGroupObject.setOperation("push");
294 // replace the original set of Policies with the set from the
295 // container (possibly modified by the user)
296 // do not allow multiple copies of same policy
297 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
298 logger.debug("policyIterator....." + selectedPolicies);
299 while (policyIterator.hasNext()) {
300 PDPPolicy existingPolicy = policyIterator.next();
301 for (PDPPolicy selPolicy : selectedPolicies) {
302 if (selPolicy.getName().equals(existingPolicy.getName())) {
303 if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
304 if (selPolicy.getId().equals(existingPolicy.getId())) {
305 policyIterator.remove();
306 logger.debug("Removing policy: " + selPolicy);
310 policyIterator.remove();
311 logger.debug("Removing Old Policy version: "+ selPolicy);
318 currentPoliciesInGroup.addAll(selectedPolicies);
319 updatedGroupObject.setPolicies(currentPoliciesInGroup);
320 this.container.updateGroup(updatedGroupObject);
322 response.setCharacterEncoding("UTF-8");
323 response.setContentType("application / json");
324 request.setCharacterEncoding("UTF-8");
326 PrintWriter out = response.getWriter();
328 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
329 JSONObject j = new JSONObject(msg);
330 out.write(j.toString());
332 // Why is this here? This defeats the purpose of the loop??
333 // Sonar says to remove it or make it conditional
339 response.setCharacterEncoding("UTF-8");
340 request.setCharacterEncoding("UTF-8");
341 PrintWriter out = response.getWriter();
343 out.write(PolicyUtils.CATCH_EXCEPTION);
348 @SuppressWarnings("unchecked")
349 @RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
350 public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
352 PolicyController controller = getPolicyControllerInstance();
353 this.container = new PDPGroupContainer(controller.getPapEngine());
354 ObjectMapper mapper = new ObjectMapper();
355 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
356 JsonNode root = mapper.readTree(request.getReader());
357 StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
358 JsonNode removePolicyData = root.get("data");
360 String userId = UserUtils.getUserSession(request).getOrgUserId();
361 logger.info("****************************************Logging UserID while Removing Policy from PDP Group*****************************************");
362 logger.info("UserId: " + userId + "PDP Group Data: "+ root.get("activePdpGroup").toString() + "Remove Policy Data: "+root.get("data"));
363 logger.info("***********************************************************************************************************************************");
365 policyContainer = new PDPPolicyContainer(group);
366 if(removePolicyData.size() > 0){
367 for(int i = 0 ; i < removePolicyData.size(); i++){
368 String polData = removePolicyData.get(i).toString();
369 this.policyContainer.removeItem(polData);
371 Set<PDPPolicy> changedPolicies = new HashSet<>();
372 changedPolicies.addAll((Collection<PDPPolicy>) this.policyContainer.getItemIds());
373 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null);
374 updatedGroupObject.setPolicies(changedPolicies);
375 updatedGroupObject.setOnapPdps(group.getOnapPdps());
376 updatedGroupObject.setPipConfigs(group.getPipConfigs());
377 updatedGroupObject.setStatus(group.getStatus());
378 updatedGroupObject.setOperation("delete");
379 this.container.updateGroup(updatedGroupObject);
382 response.setCharacterEncoding("UTF-8");
383 response.setContentType("application / json");
384 request.setCharacterEncoding("UTF-8");
386 PrintWriter out = response.getWriter();
388 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
389 JSONObject j = new JSONObject(msg);
391 out.write(j.toString());
396 response.setCharacterEncoding("UTF-8");
397 request.setCharacterEncoding("UTF-8");
398 PrintWriter out = response.getWriter();
400 out.write(PolicyUtils.CATCH_EXCEPTION);