2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.policy.controller;
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;
31 import java.io.FileWriter;
32 import java.io.IOException;
33 import java.io.PrintWriter;
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;
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;
77 @RequestMapping({"/"})
78 public class AutoPushController extends RestrictedBaseController {
80 private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
81 private static final String UTF8 = "UTF-8";
84 CommonClassDao commonClassDao;
86 private PDPGroupContainer container;
87 private PDPPolicyContainer policyContainer;
88 private PolicyController policyController;
89 protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<>());
91 public PolicyController getPolicyController() {
92 return policyController;
95 public void setPolicyController(PolicyController policyController) {
96 this.policyController = policyController;
99 public synchronized void refreshGroups() {
100 synchronized (this.groups) {
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);
113 private PolicyController getPolicyControllerInstance() {
114 return policyController != null ? getPolicyController() : new PolicyController();
117 @RequestMapping(value = {"/get_AutoPushPoliciesContainerData"}, method = {RequestMethod.GET},
118 produces = MediaType.APPLICATION_JSON_VALUE)
119 public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response) {
121 Set<String> scopes = new HashSet<>();
122 List<String> roles = new ArrayList<>();
123 List<Object> data = new ArrayList<>();
124 Map<String, Object> model = new HashMap<>();
126 String userId = UserUtils.getUserSession(request).getOrgUserId();
128 PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
129 List<Object> userRoles = controller.getRoles(userId);
130 for (Object role : userRoles) {
131 Roles userRole = (Roles) role;
132 roles.add(userRole.getRole());
133 scopes.addAll(Stream.of(userRole.getScope().split(",")).collect(Collectors.toSet()));
135 if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) {
136 data = commonClassDao.getData(PolicyVersion.class);
138 if (!scopes.isEmpty()) {
139 for (String scope : scopes) {
141 String query = "From PolicyVersion where policy_name like :scope and id > 0";
142 SimpleBindings params = new SimpleBindings();
143 params.put("scope", scope);
144 List<Object> filterdatas = commonClassDao.getDataByQuery(query, params);
145 if (filterdatas != null) {
146 data.addAll(filterdatas);
150 PolicyVersion emptyPolicyName = new PolicyVersion();
152 .setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
153 data.add(emptyPolicyName);
156 ObjectMapper mapper = new ObjectMapper();
157 model.put("policydatas", mapper.writeValueAsString(data));
158 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
159 JSONObject j = new JSONObject(msg);
160 response.getWriter().write(j.toString());
161 } catch (Exception e) {
162 logger.error("Exception Occurred" + e);
166 @RequestMapping(value = {"/auto_Push/PushPolicyToPDP.htm"}, method = {RequestMethod.POST})
167 public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response)
170 ArrayList<Object> selectedPDPS = new ArrayList<>();
171 ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
172 PolicyController controller = getPolicyControllerInstance();
173 this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
174 ObjectMapper mapper = new ObjectMapper();
175 this.container = new PDPGroupContainer(controller.getPapEngine());
176 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
177 JsonNode root = mapper.readTree(request.getReader());
179 String userId = UserUtils.getUserSession(request).getOrgUserId();
181 "****************************************Logging UserID while Pushing Policy to PDP Group*****************************************");
182 logger.info("UserId: " + userId + "Push Policy Data: " + root.get("pushTabData").toString());
184 "***********************************************************************************************************************************");
186 AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
187 for (Object pdpGroupId : adapter.getPdpDatas()) {
188 LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>) pdpGroupId;
189 for (OnapPDPGroup pdpGroup : this.groups) {
190 if (pdpGroup.getId().equals(selectedPDP.get("id"))) {
191 selectedPDPS.add(pdpGroup);
196 for (Object policyId : adapter.getPolicyDatas()) {
197 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>) policyId;
199 selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
200 selectedPoliciesInUI.add(policyName);
203 for (Object pdpDestinationGroupId : selectedPDPS) {
204 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
205 Set<PDPPolicy> selectedPolicies = new HashSet<>();
206 for (String policyId : selectedPoliciesInUI) {
207 logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
210 // Get the current selection
212 assert policyId != null;
213 // create the id of the target file
214 // Our standard for file naming is:
215 // <domain>.<filename>.<version>.xml
216 // since the file name usually has a ".xml", we need to strip
218 // before adding the other parts
219 String name = policyId.replace(File.separator, ".");
221 if (id.endsWith(".xml")) {
222 id = id.replace(".xml", "");
223 id = id.substring(0, id.lastIndexOf('.'));
226 // Default policy to be Root policy; user can change to deferred
229 StdPDPPolicy selectedPolicy = null;
230 String dbCheckName = name;
231 if (dbCheckName.contains("Config_")) {
232 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
233 } else if (dbCheckName.contains("Action_")) {
234 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
235 } else if (dbCheckName.contains("Decision_")) {
236 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
238 String[] split = dbCheckName.split(":");
239 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
240 SimpleBindings policyParams = new SimpleBindings();
241 policyParams.put("split_1", split[1]);
242 policyParams.put("split_0", split[0]);
243 List<Object> queryData = controller.getDataByQuery(query, policyParams);
244 PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
245 File temp = new File(name);
246 BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
247 bw.write(policyEntity.getPolicyData());
249 URI selectedURI = temp.toURI();
252 selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
253 } catch (IOException e) {
254 logger.error("Unable to create policy '" + name + "': " + e.getMessage(), e);
256 StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
257 if (selectedPolicy != null) {
258 // Add Current policies from container
259 for (OnapPDPGroup group : container.getGroups()) {
260 if (group.getId().equals(selectedGroup.getId())) {
261 currentPoliciesInGroup.addAll(group.getPolicies());
264 // copy policy to PAP
266 controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
267 } catch (PAPException e) {
268 logger.error("Exception Occured" + e);
271 selectedPolicies.add(selectedPolicy);
275 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
276 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(),
277 pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
278 updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps());
279 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
280 updatedGroupObject.setStatus(pdpGroup.getStatus());
281 updatedGroupObject.setOperation("push");
283 // replace the original set of Policies with the set from the
284 // container (possibly modified by the user)
285 // do not allow multiple copies of same policy
286 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
287 logger.debug("policyIterator....." + selectedPolicies);
288 while (policyIterator.hasNext()) {
289 PDPPolicy existingPolicy = policyIterator.next();
290 for (PDPPolicy selPolicy : selectedPolicies) {
291 if (selPolicy.getName().equals(existingPolicy.getName())) {
292 if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
293 if (selPolicy.getId().equals(existingPolicy.getId())) {
294 policyIterator.remove();
295 logger.debug("Removing policy: " + selPolicy);
299 policyIterator.remove();
300 logger.debug("Removing Old Policy version: " + selPolicy);
307 currentPoliciesInGroup.addAll(selectedPolicies);
308 updatedGroupObject.setPolicies(currentPoliciesInGroup);
309 this.container.updateGroup(updatedGroupObject, userId);
311 response.setCharacterEncoding(UTF8);
312 response.setContentType("application / json");
313 request.setCharacterEncoding(UTF8);
315 PrintWriter out = response.getWriter();
317 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
318 JSONObject j = new JSONObject(msg);
319 out.write(j.toString());
321 // Why is this here? This defeats the purpose of the loop??
322 // Sonar says to remove it or make it conditional
326 } catch (Exception e) {
327 response.setCharacterEncoding(UTF8);
328 request.setCharacterEncoding(UTF8);
329 PrintWriter out = response.getWriter();
331 out.write(PolicyUtils.CATCH_EXCEPTION);
336 @SuppressWarnings("unchecked")
337 @RequestMapping(value = {"/auto_Push/remove_GroupPolicies.htm"}, method = {RequestMethod.POST})
338 public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
340 PolicyController controller = getPolicyControllerInstance();
341 this.container = new PDPGroupContainer(controller.getPapEngine());
342 ObjectMapper mapper = new ObjectMapper();
343 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
344 JsonNode root = mapper.readTree(request.getReader());
345 StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
346 JsonNode removePolicyData = root.get("data");
348 String userId = UserUtils.getUserSession(request).getOrgUserId();
350 "****************************************Logging UserID while Removing Policy from PDP Group*****************************************");
351 logger.info("UserId: " + userId + "PDP Group Data: " + root.get("activePdpGroup").toString()
352 + "Remove Policy Data: " + root.get("data"));
354 "***********************************************************************************************************************************");
356 policyContainer = new PDPPolicyContainer(group);
357 if (removePolicyData.size() > 0) {
358 IntStream.range(0, removePolicyData.size()).mapToObj(i -> removePolicyData.get(i).toString())
359 .forEach(polData -> this.policyContainer.removeItem(polData));
360 Set<PDPPolicy> changedPolicies =
361 new HashSet<>((Collection<PDPPolicy>) this.policyContainer.getItemIds());
362 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(),
363 group.getDescription(), null);
364 updatedGroupObject.setPolicies(changedPolicies);
365 updatedGroupObject.setOnapPdps(group.getOnapPdps());
366 updatedGroupObject.setPipConfigs(group.getPipConfigs());
367 updatedGroupObject.setStatus(group.getStatus());
368 updatedGroupObject.setOperation("delete");
369 this.container.updateGroup(updatedGroupObject);
372 response.setCharacterEncoding(UTF8);
373 response.setContentType("application / json");
374 request.setCharacterEncoding(UTF8);
376 PrintWriter out = response.getWriter();
378 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
379 JSONObject j = new JSONObject(msg);
381 out.write(j.toString());
384 } catch (Exception e) {
385 response.setCharacterEncoding(UTF8);
386 request.setCharacterEncoding(UTF8);
387 PrintWriter out = response.getWriter();
389 out.write(PolicyUtils.CATCH_EXCEPTION);