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.util.ArrayList;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.HashMap;
38 import java.util.HashSet;
39 import java.util.Iterator;
40 import java.util.LinkedHashMap;
41 import java.util.List;
44 import java.util.stream.Collectors;
45 import java.util.stream.IntStream;
46 import java.util.stream.Stream;
48 import javax.script.SimpleBindings;
49 import javax.servlet.http.HttpServletRequest;
50 import javax.servlet.http.HttpServletResponse;
52 import org.json.JSONObject;
53 import org.onap.policy.common.logging.flexlogger.FlexLogger;
54 import org.onap.policy.common.logging.flexlogger.Logger;
55 import org.onap.policy.model.PDPGroupContainer;
56 import org.onap.policy.model.Roles;
57 import org.onap.policy.rest.adapter.AutoPushTabAdapter;
58 import org.onap.policy.rest.dao.CommonClassDao;
59 import org.onap.policy.rest.jpa.PolicyEntity;
60 import org.onap.policy.rest.jpa.PolicyVersion;
61 import org.onap.policy.rest.util.PDPPolicyContainer;
62 import org.onap.policy.utils.PolicyUtils;
63 import org.onap.policy.xacml.api.XACMLErrorConstants;
64 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
65 import org.onap.policy.xacml.std.pap.StdPDPGroup;
66 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
67 import org.onap.portalsdk.core.controller.RestrictedBaseController;
68 import org.onap.portalsdk.core.web.support.JsonMessage;
69 import org.onap.portalsdk.core.web.support.UserUtils;
70 import org.springframework.beans.factory.annotation.Autowired;
71 import org.springframework.http.MediaType;
72 import org.springframework.stereotype.Controller;
73 import org.springframework.web.bind.annotation.RequestMapping;
74 import org.springframework.web.bind.annotation.RequestMethod;
75 import org.springframework.web.servlet.ModelAndView;
78 @RequestMapping({"/"})
79 public class AutoPushController extends RestrictedBaseController {
81 private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
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;
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 * getPolicyGroupContainerData.
130 * @param request HttpServletRequest
131 * @param response HttpServletResponse
134 value = {"/get_AutoPushPoliciesContainerData"},
135 method = {RequestMethod.GET},
136 produces = MediaType.APPLICATION_JSON_VALUE)
137 public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response) {
139 Set<String> scopes = new HashSet<>();
140 List<String> roles = new ArrayList<>();
141 List<Object> data = new ArrayList<>();
142 Map<String, Object> model = new HashMap<>();
144 String userId = UserUtils.getUserSession(request).getOrgUserId();
146 PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
147 List<Object> userRoles = controller.getRoles(userId);
148 for (Object role : userRoles) {
149 Roles userRole = (Roles) role;
150 roles.add(userRole.getRole());
151 addAllScopes(userRole, scopes);
154 if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) {
155 data = commonClassDao.getData(PolicyVersion.class);
157 if (!scopes.isEmpty()) {
158 for (String scope : scopes) {
160 String query = "From PolicyVersion where policy_name like :scope and id > 0";
161 SimpleBindings params = new SimpleBindings();
162 params.put("scope", scope);
163 List<Object> filterdatas = commonClassDao.getDataByQuery(query, params);
164 if (filterdatas != null) {
165 data.addAll(filterdatas);
169 PolicyVersion emptyPolicyName = new PolicyVersion();
171 .setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
172 data.add(emptyPolicyName);
175 ObjectMapper mapper = new ObjectMapper();
176 model.put("policydatas", mapper.writeValueAsString(data));
177 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
178 response.getWriter().write(new JSONObject(msg).toString());
179 } catch (Exception e) {
180 logger.error("Exception Occurred" + e);
185 * pushPolicyToPDPGroup.
187 * @param request HttpServletRequest
188 * @param response HttpServletResponse
189 * @return ModelAndView
190 * @throws IOException IOException
192 @RequestMapping(value = {"/auto_Push/PushPolicyToPDP.htm"}, method = {RequestMethod.POST})
193 public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response)
196 response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
197 request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
201 ArrayList<Object> selectedPdps = new ArrayList<>();
202 ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
203 PolicyController controller = getPolicyControllerInstance();
204 this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
205 ObjectMapper mapper = new ObjectMapper();
206 this.container = new PDPGroupContainer(controller.getPapEngine());
207 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
208 JsonNode root = mapper.readTree(request.getReader());
210 String userId = UserUtils.getUserSession(request).getOrgUserId();
212 "**********************Logging UserID while Pushing Policy to PDP Group***********************");
213 logger.info("UserId: " + userId + "Push Policy Data: " + root.get("pushTabData").toString());
215 "**********************************************************************************************");
217 AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
218 for (Object pdpGroupId : adapter.getPdpDatas()) {
219 LinkedHashMap<?, ?> selectedPdp = (LinkedHashMap<?, ?>) pdpGroupId;
220 for (OnapPDPGroup pdpGroup : this.groups) {
221 if (pdpGroup.getId().equals(selectedPdp.get("id"))) {
222 selectedPdps.add(pdpGroup);
227 for (Object policyId : adapter.getPolicyDatas()) {
228 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>) policyId;
230 selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
231 selectedPoliciesInUI.add(policyName);
234 for (Object pdpDestinationGroupId : selectedPdps) {
235 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
236 Set<PDPPolicy> selectedPolicies = new HashSet<>();
237 for (String policyId : selectedPoliciesInUI) {
238 logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
241 // Get the current selection
243 assert policyId != null;
244 // create the id of the target file
245 // Our standard for file naming is:
246 // <domain>.<filename>.<version>.xml
247 // since the file name usually has a ".xml", we need to strip
249 // before adding the other parts
250 String name = policyId.replace(File.separator, ".");
252 if (id.endsWith(".xml")) {
253 id = id.replace(".xml", "");
254 id = id.substring(0, id.lastIndexOf('.'));
257 // Default policy to be Root policy; user can change to deferred
260 StdPDPPolicy selectedPolicy = null;
261 String dbCheckName = name;
262 if (dbCheckName.contains("Config_")) {
263 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
264 } else if (dbCheckName.contains("Action_")) {
265 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
266 } else if (dbCheckName.contains("Decision_")) {
267 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
269 String[] split = dbCheckName.split(":");
270 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
271 SimpleBindings policyParams = new SimpleBindings();
272 policyParams.put("split_1", split[1]);
273 policyParams.put("split_0", split[0]);
274 List<Object> queryData = controller.getDataByQuery(query, policyParams);
275 PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
276 File temp = new File(name);
277 BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
278 bw.write(policyEntity.getPolicyData());
282 selectedPolicy = new StdPDPPolicy(name, true, id, temp.toURI());
283 } catch (IOException e) {
284 logger.error("Unable to create policy '" + name + "': " + e.getMessage(), e);
286 StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
287 if (selectedPolicy != null) {
288 // Add Current policies from container
289 for (OnapPDPGroup group : container.getGroups()) {
290 if (group.getId().equals(selectedGroup.getId())) {
291 currentPoliciesInGroup.addAll(group.getPolicies());
294 // copy policy to PAP
296 controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
297 } catch (PAPException e) {
298 logger.error("Exception Occured" + e);
301 selectedPolicies.add(selectedPolicy);
305 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
306 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(),
307 pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
308 updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps());
309 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
310 updatedGroupObject.setStatus(pdpGroup.getStatus());
311 updatedGroupObject.setOperation("push");
313 // replace the original set of Policies with the set from the
314 // container (possibly modified by the user)
315 // do not allow multiple copies of same policy
316 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
317 logger.debug("policyIterator....." + selectedPolicies);
318 while (policyIterator.hasNext()) {
319 PDPPolicy existingPolicy = policyIterator.next();
320 for (PDPPolicy selPolicy : selectedPolicies) {
321 if (selPolicy.getName().equals(existingPolicy.getName())) {
322 if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
323 if (selPolicy.getId().equals(existingPolicy.getId())) {
324 policyIterator.remove();
325 logger.debug("Removing policy: " + selPolicy);
329 policyIterator.remove();
330 logger.debug("Removing Old Policy version: " + selPolicy);
337 currentPoliciesInGroup.addAll(selectedPolicies);
338 updatedGroupObject.setPolicies(currentPoliciesInGroup);
339 this.container.updateGroup(updatedGroupObject, userId);
340 response.setContentType(PolicyUtils.APPLICATION_JSON);
342 response.getWriter().write(new JSONObject(
343 new JsonMessage(mapper.writeValueAsString(groups))).toString());
345 } catch (Exception e) {
347 response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
355 @SuppressWarnings("unchecked")
356 @RequestMapping(value = {"/auto_Push/remove_GroupPolicies.htm"}, method = {RequestMethod.POST})
357 public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
359 response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
360 request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
364 PolicyController controller = getPolicyControllerInstance();
365 this.container = new PDPGroupContainer(controller.getPapEngine());
366 ObjectMapper mapper = new ObjectMapper();
367 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
368 JsonNode root = mapper.readTree(request.getReader());
369 final StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
370 final JsonNode removePolicyData = root.get("data");
372 String userId = UserUtils.getUserSession(request).getOrgUserId();
374 "**********************Logging UserID while Removing Policy from PDP Group*********************");
375 logger.info("UserId: " + userId + "PDP Group Data: " + root.get("activePdpGroup").toString()
376 + "Remove Policy Data: " + root.get("data"));
378 "**********************************************************************************************");
380 policyContainer = new PDPPolicyContainer(group);
381 if (removePolicyData.size() > 0) {
382 IntStream.range(0, removePolicyData.size()).mapToObj(i -> removePolicyData.get(i).toString())
383 .forEach(polData -> this.policyContainer.removeItem(polData));
384 Set<PDPPolicy> changedPolicies =
385 new HashSet<>((Collection<PDPPolicy>) this.policyContainer.getItemIds());
386 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(),
387 group.getDescription(), null);
388 updatedGroupObject.setPolicies(changedPolicies);
389 updatedGroupObject.setOnapPdps(group.getOnapPdps());
390 updatedGroupObject.setPipConfigs(group.getPipConfigs());
391 updatedGroupObject.setStatus(group.getStatus());
392 updatedGroupObject.setOperation("delete");
393 this.container.updateGroup(updatedGroupObject);
396 response.setContentType(PolicyUtils.APPLICATION_JSON);
399 response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
400 } catch (Exception e) {
402 response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);