Merge "Fix issue for policies not loading on GUI push tab"
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / AutoPushController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019 Bell Canada
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.controller;
23
24 import com.att.research.xacml.api.pap.PAPException;
25 import com.att.research.xacml.api.pap.PDPPolicy;
26 import com.fasterxml.jackson.databind.DeserializationFeature;
27 import com.fasterxml.jackson.databind.JsonNode;
28 import com.fasterxml.jackson.databind.ObjectMapper;
29 import java.io.BufferedWriter;
30 import java.io.File;
31 import java.io.FileWriter;
32 import java.io.IOException;
33 import java.io.PrintWriter;
34 import java.net.URI;
35 import java.util.ArrayList;
36 import java.util.Collection;
37 import java.util.Collections;
38 import java.util.HashMap;
39 import java.util.HashSet;
40 import java.util.Iterator;
41 import java.util.LinkedHashMap;
42 import java.util.List;
43 import java.util.Map;
44 import java.util.Set;
45 import java.util.stream.Collectors;
46 import java.util.stream.IntStream;
47 import java.util.stream.Stream;
48 import javax.script.SimpleBindings;
49 import javax.servlet.http.HttpServletRequest;
50 import javax.servlet.http.HttpServletResponse;
51 import org.json.JSONObject;
52 import org.onap.policy.common.logging.flexlogger.FlexLogger;
53 import org.onap.policy.common.logging.flexlogger.Logger;
54 import org.onap.policy.model.PDPGroupContainer;
55 import org.onap.policy.model.Roles;
56 import org.onap.policy.rest.adapter.AutoPushTabAdapter;
57 import org.onap.policy.rest.dao.CommonClassDao;
58 import org.onap.policy.rest.jpa.PolicyEntity;
59 import org.onap.policy.rest.jpa.PolicyVersion;
60 import org.onap.policy.rest.util.PDPPolicyContainer;
61 import org.onap.policy.utils.PolicyUtils;
62 import org.onap.policy.xacml.api.XACMLErrorConstants;
63 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
64 import org.onap.policy.xacml.std.pap.StdPDPGroup;
65 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
66 import org.onap.portalsdk.core.controller.RestrictedBaseController;
67 import org.onap.portalsdk.core.web.support.JsonMessage;
68 import org.onap.portalsdk.core.web.support.UserUtils;
69 import org.springframework.beans.factory.annotation.Autowired;
70 import org.springframework.http.MediaType;
71 import org.springframework.stereotype.Controller;
72 import org.springframework.web.bind.annotation.RequestMapping;
73 import org.springframework.web.bind.annotation.RequestMethod;
74 import org.springframework.web.servlet.ModelAndView;
75
76 @Controller
77 @RequestMapping({"/"})
78 public class AutoPushController extends RestrictedBaseController {
79
80     private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
81     private static final String UTF8 = "UTF-8";
82
83     @Autowired
84     CommonClassDao commonClassDao;
85
86     private PDPGroupContainer container;
87     private PDPPolicyContainer policyContainer;
88     private PolicyController policyController;
89     protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<>());
90
91     public PolicyController getPolicyController() {
92         return policyController;
93     }
94
95     public void setPolicyController(PolicyController policyController) {
96         this.policyController = policyController;
97     }
98
99     public synchronized void refreshGroups() {
100         synchronized (this.groups) {
101             this.groups.clear();
102             try {
103                 PolicyController controller = getPolicyControllerInstance();
104                 this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
105             } catch (PAPException e) {
106                 String message = "Unable to retrieve Groups from server: " + e;
107                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
108             }
109
110         }
111     }
112
113     private PolicyController getPolicyControllerInstance() {
114         return policyController != null ? getPolicyController() : new PolicyController();
115     }
116
117     private Set<String> addAllScopes(Roles userRole, Set<String> scopes) {
118         if (userRole.getScope() != null) {
119             scopes.addAll(Stream.of(userRole.getScope().split(",")).collect(Collectors.toSet()));
120         }
121         return scopes;
122     }
123
124     @RequestMapping(value = {"/get_AutoPushPoliciesContainerData"}, method = {RequestMethod.GET},
125             produces = MediaType.APPLICATION_JSON_VALUE)
126     public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response) {
127         try {
128             Set<String> scopes = new HashSet<>();
129             List<String> roles = new ArrayList<>();
130             List<Object> data = new ArrayList<>();
131             Map<String, Object> model = new HashMap<>();
132
133             String userId = UserUtils.getUserSession(request).getOrgUserId();
134
135             PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
136             List<Object> userRoles = controller.getRoles(userId);
137             for (Object role : userRoles) {
138                 Roles userRole = (Roles) role;
139                 roles.add(userRole.getRole());
140                 addAllScopes(userRole, scopes);
141             }
142
143             if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) {
144                 data = commonClassDao.getData(PolicyVersion.class);
145             } else {
146                 if (!scopes.isEmpty()) {
147                     for (String scope : scopes) {
148                         scope += "%";
149                         String query = "From PolicyVersion where policy_name like :scope and id > 0";
150                         SimpleBindings params = new SimpleBindings();
151                         params.put("scope", scope);
152                         List<Object> filterdatas = commonClassDao.getDataByQuery(query, params);
153                         if (filterdatas != null) {
154                             data.addAll(filterdatas);
155                         }
156                     }
157                 } else {
158                     PolicyVersion emptyPolicyName = new PolicyVersion();
159                     emptyPolicyName
160                             .setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
161                     data.add(emptyPolicyName);
162                 }
163             }
164             ObjectMapper mapper = new ObjectMapper();
165             model.put("policydatas", mapper.writeValueAsString(data));
166             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
167             JSONObject j = new JSONObject(msg);
168             response.getWriter().write(j.toString());
169         } catch (Exception e) {
170             logger.error("Exception Occurred" + e);
171         }
172     }
173
174     @RequestMapping(value = {"/auto_Push/PushPolicyToPDP.htm"}, method = {RequestMethod.POST})
175     public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response)
176             throws IOException {
177         try {
178             ArrayList<Object> selectedPDPS = new ArrayList<>();
179             ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
180             PolicyController controller = getPolicyControllerInstance();
181             this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
182             ObjectMapper mapper = new ObjectMapper();
183             this.container = new PDPGroupContainer(controller.getPapEngine());
184             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
185             JsonNode root = mapper.readTree(request.getReader());
186
187             String userId = UserUtils.getUserSession(request).getOrgUserId();
188             logger.info(
189                     "****************************************Logging UserID while Pushing  Policy to PDP Group*****************************************");
190             logger.info("UserId:  " + userId + "Push Policy Data:  " + root.get("pushTabData").toString());
191             logger.info(
192                     "***********************************************************************************************************************************");
193
194             AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
195             for (Object pdpGroupId : adapter.getPdpDatas()) {
196                 LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>) pdpGroupId;
197                 for (OnapPDPGroup pdpGroup : this.groups) {
198                     if (pdpGroup.getId().equals(selectedPDP.get("id"))) {
199                         selectedPDPS.add(pdpGroup);
200                     }
201                 }
202             }
203
204             for (Object policyId : adapter.getPolicyDatas()) {
205                 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>) policyId;
206                 String policyName =
207                         selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
208                 selectedPoliciesInUI.add(policyName);
209             }
210
211             for (Object pdpDestinationGroupId : selectedPDPS) {
212                 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
213                 Set<PDPPolicy> selectedPolicies = new HashSet<>();
214                 for (String policyId : selectedPoliciesInUI) {
215                     logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
216
217                     //
218                     // Get the current selection
219                     //
220                     assert policyId != null;
221                     // create the id of the target file
222                     // Our standard for file naming is:
223                     // <domain>.<filename>.<version>.xml
224                     // since the file name usually has a ".xml", we need to strip
225                     // that
226                     // before adding the other parts
227                     String name = policyId.replace(File.separator, ".");
228                     String id = name;
229                     if (id.endsWith(".xml")) {
230                         id = id.replace(".xml", "");
231                         id = id.substring(0, id.lastIndexOf('.'));
232                     }
233
234                     // Default policy to be Root policy; user can change to deferred
235                     // later
236
237                     StdPDPPolicy selectedPolicy = null;
238                     String dbCheckName = name;
239                     if (dbCheckName.contains("Config_")) {
240                         dbCheckName = dbCheckName.replace(".Config_", ":Config_");
241                     } else if (dbCheckName.contains("Action_")) {
242                         dbCheckName = dbCheckName.replace(".Action_", ":Action_");
243                     } else if (dbCheckName.contains("Decision_")) {
244                         dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
245                     }
246                     String[] split = dbCheckName.split(":");
247                     String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
248                     SimpleBindings policyParams = new SimpleBindings();
249                     policyParams.put("split_1", split[1]);
250                     policyParams.put("split_0", split[0]);
251                     List<Object> queryData = controller.getDataByQuery(query, policyParams);
252                     PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
253                     File temp = new File(name);
254                     BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
255                     bw.write(policyEntity.getPolicyData());
256                     bw.close();
257                     URI selectedURI = temp.toURI();
258                     try {
259                         // Create the policy
260                         selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
261                     } catch (IOException e) {
262                         logger.error("Unable to create policy '" + name + "': " + e.getMessage(), e);
263                     }
264                     StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
265                     if (selectedPolicy != null) {
266                         // Add Current policies from container
267                         for (OnapPDPGroup group : container.getGroups()) {
268                             if (group.getId().equals(selectedGroup.getId())) {
269                                 currentPoliciesInGroup.addAll(group.getPolicies());
270                             }
271                         }
272                         // copy policy to PAP
273                         try {
274                             controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
275                         } catch (PAPException e) {
276                             logger.error("Exception Occured" + e);
277                             return null;
278                         }
279                         selectedPolicies.add(selectedPolicy);
280                     }
281                     temp.delete();
282                 }
283                 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
284                 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(),
285                         pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
286                 updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps());
287                 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
288                 updatedGroupObject.setStatus(pdpGroup.getStatus());
289                 updatedGroupObject.setOperation("push");
290
291                 // replace the original set of Policies with the set from the
292                 // container (possibly modified by the user)
293                 // do not allow multiple copies of same policy
294                 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
295                 logger.debug("policyIterator....." + selectedPolicies);
296                 while (policyIterator.hasNext()) {
297                     PDPPolicy existingPolicy = policyIterator.next();
298                     for (PDPPolicy selPolicy : selectedPolicies) {
299                         if (selPolicy.getName().equals(existingPolicy.getName())) {
300                             if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
301                                 if (selPolicy.getId().equals(existingPolicy.getId())) {
302                                     policyIterator.remove();
303                                     logger.debug("Removing policy: " + selPolicy);
304                                     break;
305                                 }
306                             } else {
307                                 policyIterator.remove();
308                                 logger.debug("Removing Old Policy version: " + selPolicy);
309                                 break;
310                             }
311                         }
312                     }
313                 }
314
315                 currentPoliciesInGroup.addAll(selectedPolicies);
316                 updatedGroupObject.setPolicies(currentPoliciesInGroup);
317                 this.container.updateGroup(updatedGroupObject, userId);
318
319                 response.setCharacterEncoding(UTF8);
320                 response.setContentType("application / json");
321                 request.setCharacterEncoding(UTF8);
322
323                 PrintWriter out = response.getWriter();
324                 refreshGroups();
325                 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
326                 JSONObject j = new JSONObject(msg);
327                 out.write(j.toString());
328                 //
329                 // Why is this here? This defeats the purpose of the loop??
330                 // Sonar says to remove it or make it conditional
331                 //
332                 return null;
333             }
334         } catch (Exception e) {
335             response.setCharacterEncoding(UTF8);
336             request.setCharacterEncoding(UTF8);
337             PrintWriter out = response.getWriter();
338             logger.error(e);
339             out.write(PolicyUtils.CATCH_EXCEPTION);
340         }
341         return null;
342     }
343
344     @SuppressWarnings("unchecked")
345     @RequestMapping(value = {"/auto_Push/remove_GroupPolicies.htm"}, method = {RequestMethod.POST})
346     public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
347         try {
348             PolicyController controller = getPolicyControllerInstance();
349             this.container = new PDPGroupContainer(controller.getPapEngine());
350             ObjectMapper mapper = new ObjectMapper();
351             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
352             JsonNode root = mapper.readTree(request.getReader());
353             StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
354             JsonNode removePolicyData = root.get("data");
355
356             String userId = UserUtils.getUserSession(request).getOrgUserId();
357             logger.info(
358                     "****************************************Logging UserID while Removing Policy from PDP Group*****************************************");
359             logger.info("UserId:  " + userId + "PDP Group Data:  " + root.get("activePdpGroup").toString()
360                     + "Remove Policy Data: " + root.get("data"));
361             logger.info(
362                     "***********************************************************************************************************************************");
363
364             policyContainer = new PDPPolicyContainer(group);
365             if (removePolicyData.size() > 0) {
366                 IntStream.range(0, removePolicyData.size()).mapToObj(i -> removePolicyData.get(i).toString())
367                         .forEach(polData -> this.policyContainer.removeItem(polData));
368                 Set<PDPPolicy> changedPolicies =
369                         new HashSet<>((Collection<PDPPolicy>) this.policyContainer.getItemIds());
370                 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(),
371                         group.getDescription(), null);
372                 updatedGroupObject.setPolicies(changedPolicies);
373                 updatedGroupObject.setOnapPdps(group.getOnapPdps());
374                 updatedGroupObject.setPipConfigs(group.getPipConfigs());
375                 updatedGroupObject.setStatus(group.getStatus());
376                 updatedGroupObject.setOperation("delete");
377                 this.container.updateGroup(updatedGroupObject);
378             }
379
380             response.setCharacterEncoding(UTF8);
381             response.setContentType("application / json");
382             request.setCharacterEncoding(UTF8);
383
384             PrintWriter out = response.getWriter();
385             refreshGroups();
386             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
387             JSONObject j = new JSONObject(msg);
388
389             out.write(j.toString());
390
391             return null;
392         } catch (Exception e) {
393             response.setCharacterEncoding(UTF8);
394             request.setCharacterEncoding(UTF8);
395             PrintWriter out = response.getWriter();
396             logger.error(e);
397             out.write(PolicyUtils.CATCH_EXCEPTION);
398         }
399         return null;
400     }
401 }