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);
82 private static final String UTF8 = "UTF-8";
85 CommonClassDao commonClassDao;
87 private PDPGroupContainer container;
88 private PDPPolicyContainer policyContainer;
89 private PolicyController policyController;
90 protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<>());
92 public PolicyController getPolicyController() {
93 return policyController;
96 public void setPolicyController(PolicyController policyController) {
97 this.policyController = policyController;
103 public synchronized void refreshGroups() {
104 synchronized (this.groups) {
107 PolicyController controller = getPolicyControllerInstance();
108 this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
109 } catch (PAPException e) {
110 String message = "Unable to retrieve Groups from server: " + e;
111 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
117 private PolicyController getPolicyControllerInstance() {
118 return policyController != null ? getPolicyController() : new PolicyController();
121 private Set<String> addAllScopes(Roles userRole, Set<String> scopes) {
122 if (userRole.getScope() != null) {
123 scopes.addAll(Stream.of(userRole.getScope().split(",")).collect(Collectors.toSet()));
129 * getPolicyGroupContainerData.
131 * @param request HttpServletRequest
132 * @param response HttpServletResponse
135 value = {"/get_AutoPushPoliciesContainerData"},
136 method = {RequestMethod.GET},
137 produces = MediaType.APPLICATION_JSON_VALUE)
138 public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response) {
140 Set<String> scopes = new HashSet<>();
141 List<String> roles = new ArrayList<>();
142 List<Object> data = new ArrayList<>();
143 Map<String, Object> model = new HashMap<>();
145 String userId = UserUtils.getUserSession(request).getOrgUserId();
147 PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
148 List<Object> userRoles = controller.getRoles(userId);
149 for (Object role : userRoles) {
150 Roles userRole = (Roles) role;
151 roles.add(userRole.getRole());
152 addAllScopes(userRole, scopes);
155 if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) {
156 data = commonClassDao.getData(PolicyVersion.class);
158 if (!scopes.isEmpty()) {
159 for (String scope : scopes) {
161 String query = "From PolicyVersion where policy_name like :scope and id > 0";
162 SimpleBindings params = new SimpleBindings();
163 params.put("scope", scope);
164 List<Object> filterdatas = commonClassDao.getDataByQuery(query, params);
165 if (filterdatas != null) {
166 data.addAll(filterdatas);
170 PolicyVersion emptyPolicyName = new PolicyVersion();
172 .setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
173 data.add(emptyPolicyName);
176 ObjectMapper mapper = new ObjectMapper();
177 model.put("policydatas", mapper.writeValueAsString(data));
178 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
179 response.getWriter().write(new JSONObject(msg).toString());
180 } catch (Exception e) {
181 logger.error("Exception Occurred" + e);
186 * pushPolicyToPDPGroup.
188 * @param request HttpServletRequest
189 * @param response HttpServletResponse
190 * @return ModelAndView
191 * @throws IOException IOException
193 @RequestMapping(value = {"/auto_Push/PushPolicyToPDP.htm"}, method = {RequestMethod.POST})
194 public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response)
197 ArrayList<Object> selectedPdps = new ArrayList<>();
198 ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
199 PolicyController controller = getPolicyControllerInstance();
200 this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
201 ObjectMapper mapper = new ObjectMapper();
202 this.container = new PDPGroupContainer(controller.getPapEngine());
203 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
204 JsonNode root = mapper.readTree(request.getReader());
206 String userId = UserUtils.getUserSession(request).getOrgUserId();
208 "**********************Logging UserID while Pushing Policy to PDP Group***********************");
209 logger.info("UserId: " + userId + "Push Policy Data: " + root.get("pushTabData").toString());
211 "**********************************************************************************************");
213 AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
214 for (Object pdpGroupId : adapter.getPdpDatas()) {
215 LinkedHashMap<?, ?> selectedPdp = (LinkedHashMap<?, ?>) pdpGroupId;
216 for (OnapPDPGroup pdpGroup : this.groups) {
217 if (pdpGroup.getId().equals(selectedPdp.get("id"))) {
218 selectedPdps.add(pdpGroup);
223 for (Object policyId : adapter.getPolicyDatas()) {
224 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>) policyId;
226 selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
227 selectedPoliciesInUI.add(policyName);
230 for (Object pdpDestinationGroupId : selectedPdps) {
231 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
232 Set<PDPPolicy> selectedPolicies = new HashSet<>();
233 for (String policyId : selectedPoliciesInUI) {
234 logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
237 // Get the current selection
239 assert policyId != null;
240 // create the id of the target file
241 // Our standard for file naming is:
242 // <domain>.<filename>.<version>.xml
243 // since the file name usually has a ".xml", we need to strip
245 // before adding the other parts
246 String name = policyId.replace(File.separator, ".");
248 if (id.endsWith(".xml")) {
249 id = id.replace(".xml", "");
250 id = id.substring(0, id.lastIndexOf('.'));
253 // Default policy to be Root policy; user can change to deferred
256 StdPDPPolicy selectedPolicy = null;
257 String dbCheckName = name;
258 if (dbCheckName.contains("Config_")) {
259 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
260 } else if (dbCheckName.contains("Action_")) {
261 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
262 } else if (dbCheckName.contains("Decision_")) {
263 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
265 String[] split = dbCheckName.split(":");
266 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
267 SimpleBindings policyParams = new SimpleBindings();
268 policyParams.put("split_1", split[1]);
269 policyParams.put("split_0", split[0]);
270 List<Object> queryData = controller.getDataByQuery(query, policyParams);
271 PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
272 File temp = new File(name);
273 BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
274 bw.write(policyEntity.getPolicyData());
278 selectedPolicy = new StdPDPPolicy(name, true, id, temp.toURI());
279 } catch (IOException e) {
280 logger.error("Unable to create policy '" + name + "': " + e.getMessage(), e);
282 StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
283 if (selectedPolicy != null) {
284 // Add Current policies from container
285 for (OnapPDPGroup group : container.getGroups()) {
286 if (group.getId().equals(selectedGroup.getId())) {
287 currentPoliciesInGroup.addAll(group.getPolicies());
290 // copy policy to PAP
292 controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
293 } catch (PAPException e) {
294 logger.error("Exception Occured" + e);
297 selectedPolicies.add(selectedPolicy);
301 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
302 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(),
303 pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
304 updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps());
305 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
306 updatedGroupObject.setStatus(pdpGroup.getStatus());
307 updatedGroupObject.setOperation("push");
309 // replace the original set of Policies with the set from the
310 // container (possibly modified by the user)
311 // do not allow multiple copies of same policy
312 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
313 logger.debug("policyIterator....." + selectedPolicies);
314 while (policyIterator.hasNext()) {
315 PDPPolicy existingPolicy = policyIterator.next();
316 for (PDPPolicy selPolicy : selectedPolicies) {
317 if (selPolicy.getName().equals(existingPolicy.getName())) {
318 if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
319 if (selPolicy.getId().equals(existingPolicy.getId())) {
320 policyIterator.remove();
321 logger.debug("Removing policy: " + selPolicy);
325 policyIterator.remove();
326 logger.debug("Removing Old Policy version: " + selPolicy);
333 currentPoliciesInGroup.addAll(selectedPolicies);
334 updatedGroupObject.setPolicies(currentPoliciesInGroup);
335 this.container.updateGroup(updatedGroupObject, userId);
337 response.setCharacterEncoding(UTF8);
338 response.setContentType("application / json");
339 request.setCharacterEncoding(UTF8);
342 response.getWriter().write(new JSONObject(
343 new JsonMessage(mapper.writeValueAsString(groups))).toString());
345 } catch (Exception e) {
346 response.setCharacterEncoding(UTF8);
347 request.setCharacterEncoding(UTF8);
349 response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
357 @SuppressWarnings("unchecked")
358 @RequestMapping(value = {"/auto_Push/remove_GroupPolicies.htm"}, method = {RequestMethod.POST})
359 public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
361 PolicyController controller = getPolicyControllerInstance();
362 this.container = new PDPGroupContainer(controller.getPapEngine());
363 ObjectMapper mapper = new ObjectMapper();
364 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
365 JsonNode root = mapper.readTree(request.getReader());
366 final StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
367 final JsonNode removePolicyData = root.get("data");
369 String userId = UserUtils.getUserSession(request).getOrgUserId();
371 "**********************Logging UserID while Removing Policy from PDP Group*********************");
372 logger.info("UserId: " + userId + "PDP Group Data: " + root.get("activePdpGroup").toString()
373 + "Remove Policy Data: " + root.get("data"));
375 "**********************************************************************************************");
377 policyContainer = new PDPPolicyContainer(group);
378 if (removePolicyData.size() > 0) {
379 IntStream.range(0, removePolicyData.size()).mapToObj(i -> removePolicyData.get(i).toString())
380 .forEach(polData -> this.policyContainer.removeItem(polData));
381 Set<PDPPolicy> changedPolicies =
382 new HashSet<>((Collection<PDPPolicy>) this.policyContainer.getItemIds());
383 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(),
384 group.getDescription(), null);
385 updatedGroupObject.setPolicies(changedPolicies);
386 updatedGroupObject.setOnapPdps(group.getOnapPdps());
387 updatedGroupObject.setPipConfigs(group.getPipConfigs());
388 updatedGroupObject.setStatus(group.getStatus());
389 updatedGroupObject.setOperation("delete");
390 this.container.updateGroup(updatedGroupObject);
393 response.setCharacterEncoding(UTF8);
394 response.setContentType("application / json");
395 request.setCharacterEncoding(UTF8);
398 response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
399 } catch (Exception e) {
400 response.setCharacterEncoding(UTF8);
401 request.setCharacterEncoding(UTF8);
403 response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);