2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.controller;
23 import java.io.BufferedWriter;
25 import java.io.FileWriter;
26 import java.io.IOException;
27 import java.io.PrintWriter;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.Iterator;
35 import java.util.LinkedHashMap;
36 import java.util.List;
40 import javax.script.SimpleBindings;
41 import javax.servlet.http.HttpServletRequest;
42 import javax.servlet.http.HttpServletResponse;
44 import org.json.JSONObject;
45 import org.onap.policy.common.logging.flexlogger.FlexLogger;
46 import org.onap.policy.common.logging.flexlogger.Logger;
47 import org.onap.policy.model.PDPGroupContainer;
48 import org.onap.policy.model.Roles;
49 import org.onap.policy.rest.adapter.AutoPushTabAdapter;
50 import org.onap.policy.rest.dao.CommonClassDao;
51 import org.onap.policy.rest.jpa.PolicyEntity;
52 import org.onap.policy.rest.jpa.PolicyVersion;
53 import org.onap.policy.rest.util.PDPPolicyContainer;
54 import org.onap.policy.utils.PolicyUtils;
55 import org.onap.policy.xacml.api.XACMLErrorConstants;
56 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
57 import org.onap.policy.xacml.std.pap.StdPDPGroup;
58 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
59 import org.onap.portalsdk.core.controller.RestrictedBaseController;
60 import org.onap.portalsdk.core.web.support.JsonMessage;
61 import org.onap.portalsdk.core.web.support.UserUtils;
62 import org.springframework.beans.factory.annotation.Autowired;
63 import org.springframework.http.MediaType;
64 import org.springframework.stereotype.Controller;
65 import org.springframework.web.bind.annotation.RequestMapping;
66 import org.springframework.web.servlet.ModelAndView;
68 import com.att.research.xacml.api.pap.PAPException;
69 import com.att.research.xacml.api.pap.PDPPolicy;
70 import com.fasterxml.jackson.databind.DeserializationFeature;
71 import com.fasterxml.jackson.databind.JsonNode;
72 import com.fasterxml.jackson.databind.ObjectMapper;
75 @RequestMapping({ "/" })
76 public class AutoPushController extends RestrictedBaseController {
78 private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
79 private static final String UTF8 = "UTF-8";
82 CommonClassDao commonClassDao;
84 private PDPGroupContainer container;
85 protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>());
87 private PDPPolicyContainer policyContainer;
89 private PolicyController policyController;
91 public PolicyController getPolicyController() {
92 return policyController;
95 public void setPolicyController(PolicyController policyController) {
96 this.policyController = policyController;
99 private List<Object> data;
101 public synchronized void refreshGroups() {
102 synchronized (this.groups) {
105 PolicyController controller = getPolicyControllerInstance();
106 this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
107 } catch (PAPException e) {
108 String message = "Unable to retrieve Groups from server: " + e;
109 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
115 private PolicyController getPolicyControllerInstance() {
116 return policyController != null ? getPolicyController() : new PolicyController();
119 @RequestMapping(value = { "/get_AutoPushPoliciesContainerData" }, method = {
120 org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE)
121 public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response) {
125 data = new ArrayList<>();
126 String userId = UserUtils.getUserSession(request).getOrgUserId();
127 Map<String, Object> model = new HashMap<>();
128 ObjectMapper mapper = new ObjectMapper();
129 PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
130 List<Object> userRoles = controller.getRoles(userId);
131 roles = new ArrayList<>();
132 scopes = new HashSet<>();
133 for (Object role : userRoles) {
134 Roles userRole = (Roles) role;
135 roles.add(userRole.getRole());
136 if (userRole.getScope() != null) {
137 if (userRole.getScope().contains(",")) {
138 String[] multipleScopes = userRole.getScope().split(",");
139 for (int i = 0; i < multipleScopes.length; i++) {
140 scopes.add(multipleScopes[i].replace("[", "").replace("]", "").replace("\"", "").trim());
143 if (!"".equals(userRole.getScope())) {
144 scopes.add(userRole.getScope().replace("[", "").replace("]", "").replace("\"", "").trim());
149 if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) {
150 data = commonClassDao.getData(PolicyVersion.class);
152 if (!scopes.isEmpty()) {
153 for (String scope : scopes) {
155 String query = "From PolicyVersion where policy_name like :scope and id > 0";
156 SimpleBindings params = new SimpleBindings();
157 params.put("scope", scope);
158 List<Object> filterdatas = commonClassDao.getDataByQuery(query, params);
159 if (filterdatas != null) {
160 for (int i = 0; i < filterdatas.size(); i++) {
161 data.add(filterdatas.get(i));
166 PolicyVersion emptyPolicyName = new PolicyVersion();
168 .setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
169 data.add(emptyPolicyName);
172 model.put("policydatas", mapper.writeValueAsString(data));
173 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
174 JSONObject j = new JSONObject(msg);
175 response.getWriter().write(j.toString());
176 } catch (Exception e) {
177 logger.error("Exception Occured" + e);
181 @RequestMapping(value = { "/auto_Push/PushPolicyToPDP.htm" }, method = {
182 org.springframework.web.bind.annotation.RequestMethod.POST })
183 public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response)
186 ArrayList<Object> selectedPDPS = new ArrayList<>();
187 ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
188 PolicyController controller = getPolicyControllerInstance();
189 this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
190 ObjectMapper mapper = new ObjectMapper();
191 this.container = new PDPGroupContainer(controller.getPapEngine());
192 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
193 JsonNode root = mapper.readTree(request.getReader());
195 String userId = UserUtils.getUserSession(request).getOrgUserId();
197 "****************************************Logging UserID while Pushing Policy to PDP Group*****************************************");
198 logger.info("UserId: " + userId + "Push Policy Data: " + root.get("pushTabData").toString());
200 "***********************************************************************************************************************************");
202 AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
203 for (Object pdpGroupId : adapter.getPdpDatas()) {
204 LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>) pdpGroupId;
205 for (OnapPDPGroup pdpGroup : this.groups) {
206 if (pdpGroup.getId().equals(selectedPDP.get("id"))) {
207 selectedPDPS.add(pdpGroup);
212 for (Object policyId : adapter.getPolicyDatas()) {
213 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>) policyId;
214 String policyName = selected.get("policyName").toString() + "."
215 + selected.get("activeVersion").toString() + ".xml";
216 selectedPoliciesInUI.add(policyName);
219 for (Object pdpDestinationGroupId : selectedPDPS) {
220 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
221 Set<PDPPolicy> selectedPolicies = new HashSet<>();
222 for (String policyId : selectedPoliciesInUI) {
223 logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
226 // Get the current selection
227 String selectedItem = policyId;
229 assert selectedItem != null;
230 // create the id of the target file
231 // Our standard for file naming is:
232 // <domain>.<filename>.<version>.xml
233 // since the file name usually has a ".xml", we need to strip
235 // before adding the other parts
236 String name = selectedItem.replace(File.separator, ".");
238 if (id.endsWith(".xml")) {
239 id = id.replace(".xml", "");
240 id = id.substring(0, id.lastIndexOf('.'));
243 // Default policy to be Root policy; user can change to deferred
246 StdPDPPolicy selectedPolicy = null;
247 String dbCheckName = name;
248 if (dbCheckName.contains("Config_")) {
249 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
250 } else if (dbCheckName.contains("Action_")) {
251 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
252 } else if (dbCheckName.contains("Decision_")) {
253 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
255 String[] split = dbCheckName.split(":");
256 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
257 SimpleBindings policyParams = new SimpleBindings();
258 policyParams.put("split_1", split[1]);
259 policyParams.put("split_0", split[0]);
260 List<Object> queryData = controller.getDataByQuery(query, policyParams);
261 PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
262 File temp = new File(name);
263 BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
264 bw.write(policyEntity.getPolicyData());
266 URI selectedURI = temp.toURI();
270 selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
271 } catch (IOException e) {
272 logger.error("Unable to create policy '" + name + "': " + e.getMessage(), e);
274 StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
275 if (selectedPolicy != null) {
276 // Add Current policies from container
277 for (OnapPDPGroup group : container.getGroups()) {
278 if (group.getId().equals(selectedGroup.getId())) {
279 currentPoliciesInGroup.addAll(group.getPolicies());
282 // copy policy to PAP
284 controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
285 } catch (PAPException e) {
286 logger.error("Exception Occured" + e);
289 selectedPolicies.add(selectedPolicy);
293 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
294 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(),
295 pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
296 updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps());
297 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
298 updatedGroupObject.setStatus(pdpGroup.getStatus());
299 updatedGroupObject.setOperation("push");
301 // replace the original set of Policies with the set from the
302 // container (possibly modified by the user)
303 // do not allow multiple copies of same policy
304 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
305 logger.debug("policyIterator....." + selectedPolicies);
306 while (policyIterator.hasNext()) {
307 PDPPolicy existingPolicy = policyIterator.next();
308 for (PDPPolicy selPolicy : selectedPolicies) {
309 if (selPolicy.getName().equals(existingPolicy.getName())) {
310 if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
311 if (selPolicy.getId().equals(existingPolicy.getId())) {
312 policyIterator.remove();
313 logger.debug("Removing policy: " + selPolicy);
317 policyIterator.remove();
318 logger.debug("Removing Old Policy version: " + selPolicy);
325 currentPoliciesInGroup.addAll(selectedPolicies);
326 updatedGroupObject.setPolicies(currentPoliciesInGroup);
327 this.container.updateGroup(updatedGroupObject);
329 response.setCharacterEncoding(UTF8);
330 response.setContentType("application / json");
331 request.setCharacterEncoding(UTF8);
333 PrintWriter out = response.getWriter();
335 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
336 JSONObject j = new JSONObject(msg);
337 out.write(j.toString());
339 // Why is this here? This defeats the purpose of the loop??
340 // Sonar says to remove it or make it conditional
344 } catch (Exception e) {
345 response.setCharacterEncoding(UTF8);
346 request.setCharacterEncoding(UTF8);
347 PrintWriter out = response.getWriter();
349 out.write(PolicyUtils.CATCH_EXCEPTION);
354 @SuppressWarnings("unchecked")
355 @RequestMapping(value = { "/auto_Push/remove_GroupPolicies.htm" }, method = {
356 org.springframework.web.bind.annotation.RequestMethod.POST })
357 public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
359 PolicyController controller = getPolicyControllerInstance();
360 this.container = new PDPGroupContainer(controller.getPapEngine());
361 ObjectMapper mapper = new ObjectMapper();
362 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
363 JsonNode root = mapper.readTree(request.getReader());
364 StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
365 JsonNode removePolicyData = root.get("data");
367 String userId = UserUtils.getUserSession(request).getOrgUserId();
369 "****************************************Logging UserID while Removing Policy from PDP Group*****************************************");
370 logger.info("UserId: " + userId + "PDP Group Data: " + root.get("activePdpGroup").toString()
371 + "Remove Policy Data: " + root.get("data"));
373 "***********************************************************************************************************************************");
375 policyContainer = new PDPPolicyContainer(group);
376 if (removePolicyData.size() > 0) {
377 for (int i = 0; i < removePolicyData.size(); i++) {
378 String polData = removePolicyData.get(i).toString();
379 this.policyContainer.removeItem(polData);
381 Set<PDPPolicy> changedPolicies = new HashSet<>();
382 changedPolicies.addAll((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);
397 PrintWriter out = response.getWriter();
399 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
400 JSONObject j = new JSONObject(msg);
402 out.write(j.toString());
405 } catch (Exception e) {
406 response.setCharacterEncoding(UTF8);
407 request.setCharacterEncoding(UTF8);
408 PrintWriter out = response.getWriter();
410 out.write(PolicyUtils.CATCH_EXCEPTION);