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 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()));
124 @RequestMapping(value = {"/get_AutoPushPoliciesContainerData"}, method = {RequestMethod.GET},
125 produces = MediaType.APPLICATION_JSON_VALUE)
126 public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response) {
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<>();
133 String userId = UserUtils.getUserSession(request).getOrgUserId();
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);
143 if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) {
144 data = commonClassDao.getData(PolicyVersion.class);
146 if (!scopes.isEmpty()) {
147 for (String scope : scopes) {
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);
158 PolicyVersion emptyPolicyName = new PolicyVersion();
160 .setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
161 data.add(emptyPolicyName);
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);
174 @RequestMapping(value = {"/auto_Push/PushPolicyToPDP.htm"}, method = {RequestMethod.POST})
175 public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response)
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());
187 String userId = UserUtils.getUserSession(request).getOrgUserId();
189 "****************************************Logging UserID while Pushing Policy to PDP Group*****************************************");
190 logger.info("UserId: " + userId + "Push Policy Data: " + root.get("pushTabData").toString());
192 "***********************************************************************************************************************************");
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);
204 for (Object policyId : adapter.getPolicyDatas()) {
205 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>) policyId;
207 selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
208 selectedPoliciesInUI.add(policyName);
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);
218 // Get the current selection
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
226 // before adding the other parts
227 String name = policyId.replace(File.separator, ".");
229 if (id.endsWith(".xml")) {
230 id = id.replace(".xml", "");
231 id = id.substring(0, id.lastIndexOf('.'));
234 // Default policy to be Root policy; user can change to deferred
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_");
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());
257 URI selectedURI = temp.toURI();
260 selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
261 } catch (IOException e) {
262 logger.error("Unable to create policy '" + name + "': " + e.getMessage(), e);
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());
272 // copy policy to PAP
274 controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
275 } catch (PAPException e) {
276 logger.error("Exception Occured" + e);
279 selectedPolicies.add(selectedPolicy);
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");
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);
307 policyIterator.remove();
308 logger.debug("Removing Old Policy version: " + selPolicy);
315 currentPoliciesInGroup.addAll(selectedPolicies);
316 updatedGroupObject.setPolicies(currentPoliciesInGroup);
317 this.container.updateGroup(updatedGroupObject, userId);
319 response.setCharacterEncoding(UTF8);
320 response.setContentType("application / json");
321 request.setCharacterEncoding(UTF8);
323 PrintWriter out = response.getWriter();
325 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
326 JSONObject j = new JSONObject(msg);
327 out.write(j.toString());
329 // Why is this here? This defeats the purpose of the loop??
330 // Sonar says to remove it or make it conditional
334 } catch (Exception e) {
335 response.setCharacterEncoding(UTF8);
336 request.setCharacterEncoding(UTF8);
337 PrintWriter out = response.getWriter();
339 out.write(PolicyUtils.CATCH_EXCEPTION);
344 @SuppressWarnings("unchecked")
345 @RequestMapping(value = {"/auto_Push/remove_GroupPolicies.htm"}, method = {RequestMethod.POST})
346 public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
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");
356 String userId = UserUtils.getUserSession(request).getOrgUserId();
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"));
362 "***********************************************************************************************************************************");
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);
380 response.setCharacterEncoding(UTF8);
381 response.setContentType("application / json");
382 request.setCharacterEncoding(UTF8);
384 PrintWriter out = response.getWriter();
386 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
387 JSONObject j = new JSONObject(msg);
389 out.write(j.toString());
392 } catch (Exception e) {
393 response.setCharacterEncoding(UTF8);
394 request.setCharacterEncoding(UTF8);
395 PrintWriter out = response.getWriter();
397 out.write(PolicyUtils.CATCH_EXCEPTION);