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;
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;
49 import javax.script.SimpleBindings;
50 import javax.servlet.http.HttpServletRequest;
51 import javax.servlet.http.HttpServletResponse;
53 import org.json.JSONObject;
54 import org.onap.policy.common.logging.flexlogger.FlexLogger;
55 import org.onap.policy.common.logging.flexlogger.Logger;
56 import org.onap.policy.model.PDPGroupContainer;
57 import org.onap.policy.model.Roles;
58 import org.onap.policy.rest.adapter.AutoPushTabAdapter;
59 import org.onap.policy.rest.dao.CommonClassDao;
60 import org.onap.policy.rest.jpa.PolicyEntity;
61 import org.onap.policy.rest.jpa.PolicyVersion;
62 import org.onap.policy.rest.util.PDPPolicyContainer;
63 import org.onap.policy.utils.PolicyUtils;
64 import org.onap.policy.xacml.api.XACMLErrorConstants;
65 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
66 import org.onap.policy.xacml.std.pap.StdPDPGroup;
67 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
68 import org.onap.portalsdk.core.controller.RestrictedBaseController;
69 import org.onap.portalsdk.core.web.support.JsonMessage;
70 import org.onap.portalsdk.core.web.support.UserUtils;
71 import org.springframework.beans.factory.annotation.Autowired;
72 import org.springframework.http.MediaType;
73 import org.springframework.stereotype.Controller;
74 import org.springframework.web.bind.annotation.RequestMapping;
75 import org.springframework.web.bind.annotation.RequestMethod;
76 import org.springframework.web.servlet.ModelAndView;
79 @RequestMapping({"/"})
80 public class AutoPushController extends RestrictedBaseController {
82 private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
83 private static final String UTF8 = "UTF-8";
86 CommonClassDao commonClassDao;
88 private PDPGroupContainer container;
89 private PDPPolicyContainer policyContainer;
90 private PolicyController policyController;
91 protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<>());
93 public PolicyController getPolicyController() {
94 return policyController;
97 public void setPolicyController(PolicyController policyController) {
98 this.policyController = policyController;
104 public synchronized void refreshGroups() {
105 synchronized (this.groups) {
108 PolicyController controller = getPolicyControllerInstance();
109 this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
110 } catch (PAPException e) {
111 String message = "Unable to retrieve Groups from server: " + e;
112 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
118 private PolicyController getPolicyControllerInstance() {
119 return policyController != null ? getPolicyController() : new PolicyController();
122 private Set<String> addAllScopes(Roles userRole, Set<String> scopes) {
123 if (userRole.getScope() != null) {
124 scopes.addAll(Stream.of(userRole.getScope().split(",")).collect(Collectors.toSet()));
130 * getPolicyGroupContainerData.
132 * @param request HttpServletRequest
133 * @param response HttpServletResponse
136 value = {"/get_AutoPushPoliciesContainerData"},
137 method = {RequestMethod.GET},
138 produces = MediaType.APPLICATION_JSON_VALUE)
139 public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response) {
141 Set<String> scopes = new HashSet<>();
142 List<String> roles = new ArrayList<>();
143 List<Object> data = new ArrayList<>();
144 Map<String, Object> model = new HashMap<>();
146 String userId = UserUtils.getUserSession(request).getOrgUserId();
148 PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
149 List<Object> userRoles = controller.getRoles(userId);
150 for (Object role : userRoles) {
151 Roles userRole = (Roles) role;
152 roles.add(userRole.getRole());
153 addAllScopes(userRole, scopes);
156 if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) {
157 data = commonClassDao.getData(PolicyVersion.class);
159 if (!scopes.isEmpty()) {
160 for (String scope : scopes) {
162 String query = "From PolicyVersion where policy_name like :scope and id > 0";
163 SimpleBindings params = new SimpleBindings();
164 params.put("scope", scope);
165 List<Object> filterdatas = commonClassDao.getDataByQuery(query, params);
166 if (filterdatas != null) {
167 data.addAll(filterdatas);
171 PolicyVersion emptyPolicyName = new PolicyVersion();
173 .setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
174 data.add(emptyPolicyName);
177 ObjectMapper mapper = new ObjectMapper();
178 model.put("policydatas", mapper.writeValueAsString(data));
179 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
180 response.getWriter().write(new JSONObject(msg).toString());
181 } catch (Exception e) {
182 logger.error("Exception Occurred" + e);
187 * pushPolicyToPDPGroup.
189 * @param request HttpServletRequest
190 * @param response HttpServletResponse
191 * @return ModelAndView
192 * @throws IOException IOException
194 @RequestMapping(value = {"/auto_Push/PushPolicyToPDP.htm"}, method = {RequestMethod.POST})
195 public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response)
198 ArrayList<Object> selectedPdps = new ArrayList<>();
199 ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
200 PolicyController controller = getPolicyControllerInstance();
201 this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
202 ObjectMapper mapper = new ObjectMapper();
203 this.container = new PDPGroupContainer(controller.getPapEngine());
204 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
205 JsonNode root = mapper.readTree(request.getReader());
207 String userId = UserUtils.getUserSession(request).getOrgUserId();
209 "**********************Logging UserID while Pushing Policy to PDP Group***********************");
210 logger.info("UserId: " + userId + "Push Policy Data: " + root.get("pushTabData").toString());
212 "**********************************************************************************************");
214 AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
215 for (Object pdpGroupId : adapter.getPdpDatas()) {
216 LinkedHashMap<?, ?> selectedPdp = (LinkedHashMap<?, ?>) pdpGroupId;
217 for (OnapPDPGroup pdpGroup : this.groups) {
218 if (pdpGroup.getId().equals(selectedPdp.get("id"))) {
219 selectedPdps.add(pdpGroup);
224 for (Object policyId : adapter.getPolicyDatas()) {
225 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>) policyId;
227 selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
228 selectedPoliciesInUI.add(policyName);
231 for (Object pdpDestinationGroupId : selectedPdps) {
232 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
233 Set<PDPPolicy> selectedPolicies = new HashSet<>();
234 for (String policyId : selectedPoliciesInUI) {
235 logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
238 // Get the current selection
240 assert policyId != null;
241 // create the id of the target file
242 // Our standard for file naming is:
243 // <domain>.<filename>.<version>.xml
244 // since the file name usually has a ".xml", we need to strip
246 // before adding the other parts
247 String name = policyId.replace(File.separator, ".");
249 if (id.endsWith(".xml")) {
250 id = id.replace(".xml", "");
251 id = id.substring(0, id.lastIndexOf('.'));
254 // Default policy to be Root policy; user can change to deferred
257 StdPDPPolicy selectedPolicy = null;
258 String dbCheckName = name;
259 if (dbCheckName.contains("Config_")) {
260 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
261 } else if (dbCheckName.contains("Action_")) {
262 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
263 } else if (dbCheckName.contains("Decision_")) {
264 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
266 String[] split = dbCheckName.split(":");
267 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
268 SimpleBindings policyParams = new SimpleBindings();
269 policyParams.put("split_1", split[1]);
270 policyParams.put("split_0", split[0]);
271 List<Object> queryData = controller.getDataByQuery(query, policyParams);
272 PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
273 File temp = new File(name);
274 BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
275 bw.write(policyEntity.getPolicyData());
279 selectedPolicy = new StdPDPPolicy(name, true, id, temp.toURI());
280 } catch (IOException e) {
281 logger.error("Unable to create policy '" + name + "': " + e.getMessage(), e);
283 StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
284 if (selectedPolicy != null) {
285 // Add Current policies from container
286 for (OnapPDPGroup group : container.getGroups()) {
287 if (group.getId().equals(selectedGroup.getId())) {
288 currentPoliciesInGroup.addAll(group.getPolicies());
291 // copy policy to PAP
293 controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
294 } catch (PAPException e) {
295 logger.error("Exception Occured" + e);
298 selectedPolicies.add(selectedPolicy);
302 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
303 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(),
304 pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
305 updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps());
306 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
307 updatedGroupObject.setStatus(pdpGroup.getStatus());
308 updatedGroupObject.setOperation("push");
310 // replace the original set of Policies with the set from the
311 // container (possibly modified by the user)
312 // do not allow multiple copies of same policy
313 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
314 logger.debug("policyIterator....." + selectedPolicies);
315 while (policyIterator.hasNext()) {
316 PDPPolicy existingPolicy = policyIterator.next();
317 for (PDPPolicy selPolicy : selectedPolicies) {
318 if (selPolicy.getName().equals(existingPolicy.getName())) {
319 if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
320 if (selPolicy.getId().equals(existingPolicy.getId())) {
321 policyIterator.remove();
322 logger.debug("Removing policy: " + selPolicy);
326 policyIterator.remove();
327 logger.debug("Removing Old Policy version: " + selPolicy);
334 currentPoliciesInGroup.addAll(selectedPolicies);
335 updatedGroupObject.setPolicies(currentPoliciesInGroup);
336 this.container.updateGroup(updatedGroupObject, userId);
338 response.setCharacterEncoding(UTF8);
339 response.setContentType("application / json");
340 request.setCharacterEncoding(UTF8);
342 PrintWriter out = response.getWriter();
344 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
345 out.write(new JSONObject(msg).toString());
347 // Why is this here? This defeats the purpose of the loop??
348 // Sonar says to remove it or make it conditional
352 } catch (Exception e) {
353 response.setCharacterEncoding(UTF8);
354 request.setCharacterEncoding(UTF8);
356 response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
364 @SuppressWarnings("unchecked")
365 @RequestMapping(value = {"/auto_Push/remove_GroupPolicies.htm"}, method = {RequestMethod.POST})
366 public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
368 PolicyController controller = getPolicyControllerInstance();
369 this.container = new PDPGroupContainer(controller.getPapEngine());
370 ObjectMapper mapper = new ObjectMapper();
371 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
372 JsonNode root = mapper.readTree(request.getReader());
373 final StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
374 final JsonNode removePolicyData = root.get("data");
376 String userId = UserUtils.getUserSession(request).getOrgUserId();
378 "**********************Logging UserID while Removing Policy from PDP Group*********************");
379 logger.info("UserId: " + userId + "PDP Group Data: " + root.get("activePdpGroup").toString()
380 + "Remove Policy Data: " + root.get("data"));
382 "**********************************************************************************************");
384 policyContainer = new PDPPolicyContainer(group);
385 if (removePolicyData.size() > 0) {
386 IntStream.range(0, removePolicyData.size()).mapToObj(i -> removePolicyData.get(i).toString())
387 .forEach(polData -> this.policyContainer.removeItem(polData));
388 Set<PDPPolicy> changedPolicies =
389 new HashSet<>((Collection<PDPPolicy>) this.policyContainer.getItemIds());
390 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(),
391 group.getDescription(), null);
392 updatedGroupObject.setPolicies(changedPolicies);
393 updatedGroupObject.setOnapPdps(group.getOnapPdps());
394 updatedGroupObject.setPipConfigs(group.getPipConfigs());
395 updatedGroupObject.setStatus(group.getStatus());
396 updatedGroupObject.setOperation("delete");
397 this.container.updateGroup(updatedGroupObject);
400 response.setCharacterEncoding(UTF8);
401 response.setContentType("application / json");
402 request.setCharacterEncoding(UTF8);
404 PrintWriter out = response.getWriter();
406 out.write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
408 } catch (Exception e) {
409 response.setCharacterEncoding(UTF8);
410 request.setCharacterEncoding(UTF8);
412 response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);