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;
30 import java.io.BufferedWriter;
32 import java.io.FileWriter;
33 import java.io.IOException;
34 import java.io.PrintWriter;
36 import java.util.ArrayList;
37 import java.util.Collection;
38 import java.util.Collections;
39 import java.util.HashMap;
40 import java.util.HashSet;
41 import java.util.Iterator;
42 import java.util.LinkedHashMap;
43 import java.util.List;
46 import java.util.stream.Collectors;
47 import java.util.stream.IntStream;
48 import java.util.stream.Stream;
50 import javax.script.SimpleBindings;
51 import javax.servlet.http.HttpServletRequest;
52 import javax.servlet.http.HttpServletResponse;
54 import org.json.JSONObject;
55 import org.onap.policy.common.logging.flexlogger.FlexLogger;
56 import org.onap.policy.common.logging.flexlogger.Logger;
57 import org.onap.policy.model.PDPGroupContainer;
58 import org.onap.policy.model.Roles;
59 import org.onap.policy.rest.adapter.AutoPushTabAdapter;
60 import org.onap.policy.rest.dao.CommonClassDao;
61 import org.onap.policy.rest.jpa.PolicyEntity;
62 import org.onap.policy.rest.jpa.PolicyVersion;
63 import org.onap.policy.rest.util.PDPPolicyContainer;
64 import org.onap.policy.utils.PolicyUtils;
65 import org.onap.policy.xacml.api.XACMLErrorConstants;
66 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
67 import org.onap.policy.xacml.std.pap.StdPDPGroup;
68 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
69 import org.onap.portalsdk.core.controller.RestrictedBaseController;
70 import org.onap.portalsdk.core.web.support.JsonMessage;
71 import org.onap.portalsdk.core.web.support.UserUtils;
72 import org.springframework.beans.factory.annotation.Autowired;
73 import org.springframework.http.MediaType;
74 import org.springframework.stereotype.Controller;
75 import org.springframework.web.bind.annotation.RequestMapping;
76 import org.springframework.web.bind.annotation.RequestMethod;
77 import org.springframework.web.servlet.ModelAndView;
80 @RequestMapping({"/"})
81 public class AutoPushController extends RestrictedBaseController {
83 private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
84 private static final String UTF8 = "UTF-8";
87 CommonClassDao commonClassDao;
89 private PDPGroupContainer container;
90 private PDPPolicyContainer policyContainer;
91 private PolicyController policyController;
92 protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<>());
94 public PolicyController getPolicyController() {
95 return policyController;
98 public void setPolicyController(PolicyController policyController) {
99 this.policyController = policyController;
102 public synchronized void refreshGroups() {
103 synchronized (this.groups) {
106 PolicyController controller = getPolicyControllerInstance();
107 this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
108 } catch (PAPException e) {
109 String message = "Unable to retrieve Groups from server: " + e;
110 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
116 private PolicyController getPolicyControllerInstance() {
117 return policyController != null ? getPolicyController() : new PolicyController();
120 private Set<String> addAllScopes(Roles userRole, Set<String> scopes) {
121 if (userRole.getScope() != null) {
122 scopes.addAll(Stream.of(userRole.getScope().split(",")).collect(Collectors.toSet()));
128 value = {"/get_AutoPushPoliciesContainerData"},
129 method = {RequestMethod.GET},
130 produces = MediaType.APPLICATION_JSON_VALUE)
131 public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response) {
133 Set<String> scopes = new HashSet<>();
134 List<String> roles = new ArrayList<>();
135 List<Object> data = new ArrayList<>();
136 Map<String, Object> model = new HashMap<>();
138 String userId = UserUtils.getUserSession(request).getOrgUserId();
140 PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
141 List<Object> userRoles = controller.getRoles(userId);
142 for (Object role : userRoles) {
143 Roles userRole = (Roles) role;
144 roles.add(userRole.getRole());
145 addAllScopes(userRole, scopes);
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 data.addAll(filterdatas);
163 PolicyVersion emptyPolicyName = new PolicyVersion();
165 .setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
166 data.add(emptyPolicyName);
169 ObjectMapper mapper = new ObjectMapper();
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());
174 } catch (Exception e) {
175 logger.error("Exception Occurred" + e);
179 @RequestMapping(value = {"/auto_Push/PushPolicyToPDP.htm"}, method = {RequestMethod.POST})
180 public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response)
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();
194 "****************************************Logging UserID while Pushing Policy to PDP Group*****************************************");
195 logger.info("UserId: " + userId + "Push Policy Data: " + root.get("pushTabData").toString());
197 "***********************************************************************************************************************************");
199 AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
200 for (Object pdpGroupId : adapter.getPdpDatas()) {
201 LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>) pdpGroupId;
202 for (OnapPDPGroup pdpGroup : this.groups) {
203 if (pdpGroup.getId().equals(selectedPDP.get("id"))) {
204 selectedPDPS.add(pdpGroup);
209 for (Object policyId : adapter.getPolicyDatas()) {
210 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>) policyId;
212 selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
213 selectedPoliciesInUI.add(policyName);
216 for (Object pdpDestinationGroupId : selectedPDPS) {
217 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
218 Set<PDPPolicy> selectedPolicies = new HashSet<>();
219 for (String policyId : selectedPoliciesInUI) {
220 logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
223 // Get the current selection
225 assert policyId != null;
226 // create the id of the target file
227 // Our standard for file naming is:
228 // <domain>.<filename>.<version>.xml
229 // since the file name usually has a ".xml", we need to strip
231 // before adding the other parts
232 String name = policyId.replace(File.separator, ".");
234 if (id.endsWith(".xml")) {
235 id = id.replace(".xml", "");
236 id = id.substring(0, id.lastIndexOf('.'));
239 // Default policy to be Root policy; user can change to deferred
242 StdPDPPolicy selectedPolicy = null;
243 String dbCheckName = name;
244 if (dbCheckName.contains("Config_")) {
245 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
246 } else if (dbCheckName.contains("Action_")) {
247 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
248 } else if (dbCheckName.contains("Decision_")) {
249 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
251 String[] split = dbCheckName.split(":");
252 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
253 SimpleBindings policyParams = new SimpleBindings();
254 policyParams.put("split_1", split[1]);
255 policyParams.put("split_0", split[0]);
256 List<Object> queryData = controller.getDataByQuery(query, policyParams);
257 PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
258 File temp = new File(name);
259 BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
260 bw.write(policyEntity.getPolicyData());
262 URI selectedURI = temp.toURI();
265 selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
266 } catch (IOException e) {
267 logger.error("Unable to create policy '" + name + "': " + e.getMessage(), e);
269 StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
270 if (selectedPolicy != null) {
271 // Add Current policies from container
272 for (OnapPDPGroup group : container.getGroups()) {
273 if (group.getId().equals(selectedGroup.getId())) {
274 currentPoliciesInGroup.addAll(group.getPolicies());
277 // copy policy to PAP
279 controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
280 } catch (PAPException e) {
281 logger.error("Exception Occured" + e);
284 selectedPolicies.add(selectedPolicy);
288 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
289 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(),
290 pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
291 updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps());
292 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
293 updatedGroupObject.setStatus(pdpGroup.getStatus());
294 updatedGroupObject.setOperation("push");
296 // replace the original set of Policies with the set from the
297 // container (possibly modified by the user)
298 // do not allow multiple copies of same policy
299 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
300 logger.debug("policyIterator....." + selectedPolicies);
301 while (policyIterator.hasNext()) {
302 PDPPolicy existingPolicy = policyIterator.next();
303 for (PDPPolicy selPolicy : selectedPolicies) {
304 if (selPolicy.getName().equals(existingPolicy.getName())) {
305 if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
306 if (selPolicy.getId().equals(existingPolicy.getId())) {
307 policyIterator.remove();
308 logger.debug("Removing policy: " + selPolicy);
312 policyIterator.remove();
313 logger.debug("Removing Old Policy version: " + selPolicy);
320 currentPoliciesInGroup.addAll(selectedPolicies);
321 updatedGroupObject.setPolicies(currentPoliciesInGroup);
322 this.container.updateGroup(updatedGroupObject, userId);
324 response.setCharacterEncoding(UTF8);
325 response.setContentType("application / json");
326 request.setCharacterEncoding(UTF8);
328 PrintWriter out = response.getWriter();
330 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
331 JSONObject j = new JSONObject(msg);
332 out.write(j.toString());
334 // Why is this here? This defeats the purpose of the loop??
335 // Sonar says to remove it or make it conditional
339 } catch (Exception e) {
340 response.setCharacterEncoding(UTF8);
341 request.setCharacterEncoding(UTF8);
342 PrintWriter out = response.getWriter();
344 out.write(PolicyUtils.CATCH_EXCEPTION);
349 @SuppressWarnings("unchecked")
350 @RequestMapping(value = {"/auto_Push/remove_GroupPolicies.htm"}, method = {RequestMethod.POST})
351 public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
353 PolicyController controller = getPolicyControllerInstance();
354 this.container = new PDPGroupContainer(controller.getPapEngine());
355 ObjectMapper mapper = new ObjectMapper();
356 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
357 JsonNode root = mapper.readTree(request.getReader());
358 StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
359 JsonNode removePolicyData = root.get("data");
361 String userId = UserUtils.getUserSession(request).getOrgUserId();
363 "****************************************Logging UserID while Removing Policy from PDP Group*****************************************");
364 logger.info("UserId: " + userId + "PDP Group Data: " + root.get("activePdpGroup").toString()
365 + "Remove Policy Data: " + root.get("data"));
367 "***********************************************************************************************************************************");
369 policyContainer = new PDPPolicyContainer(group);
370 if (removePolicyData.size() > 0) {
371 IntStream.range(0, removePolicyData.size()).mapToObj(i -> removePolicyData.get(i).toString())
372 .forEach(polData -> this.policyContainer.removeItem(polData));
373 Set<PDPPolicy> changedPolicies =
374 new HashSet<>((Collection<PDPPolicy>) this.policyContainer.getItemIds());
375 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(),
376 group.getDescription(), null);
377 updatedGroupObject.setPolicies(changedPolicies);
378 updatedGroupObject.setOnapPdps(group.getOnapPdps());
379 updatedGroupObject.setPipConfigs(group.getPipConfigs());
380 updatedGroupObject.setStatus(group.getStatus());
381 updatedGroupObject.setOperation("delete");
382 this.container.updateGroup(updatedGroupObject);
385 response.setCharacterEncoding(UTF8);
386 response.setContentType("application / json");
387 request.setCharacterEncoding(UTF8);
389 PrintWriter out = response.getWriter();
391 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
392 JSONObject j = new JSONObject(msg);
394 out.write(j.toString());
397 } catch (Exception e) {
398 response.setCharacterEncoding(UTF8);
399 request.setCharacterEncoding(UTF8);
400 PrintWriter out = response.getWriter();
402 out.write(PolicyUtils.CATCH_EXCEPTION);