2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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;
24 import java.io.BufferedWriter;
26 import java.io.FileWriter;
27 import java.io.IOException;
28 import java.io.PrintWriter;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.HashSet;
35 import java.util.Iterator;
36 import java.util.LinkedHashMap;
37 import java.util.List;
41 import javax.script.SimpleBindings;
42 import javax.servlet.http.HttpServletRequest;
43 import javax.servlet.http.HttpServletResponse;
45 import org.json.JSONObject;
46 import org.onap.policy.common.logging.flexlogger.FlexLogger;
47 import org.onap.policy.common.logging.flexlogger.Logger;
48 import org.onap.policy.model.PDPGroupContainer;
49 import org.onap.policy.model.PDPPolicyContainer;
50 import org.onap.policy.model.Roles;
51 import org.onap.policy.rest.adapter.AutoPushTabAdapter;
52 import org.onap.policy.rest.dao.CommonClassDao;
53 import org.onap.policy.rest.jpa.PolicyEntity;
54 import org.onap.policy.rest.jpa.PolicyVersion;
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;
76 @RequestMapping({"/"})
77 public class AutoPushController extends RestrictedBaseController{
79 private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
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;
90 public PolicyController getPolicyController() {
91 return policyController;
94 public void setPolicyController(PolicyController policyController) {
95 this.policyController = policyController;
98 private List<Object> data;
100 public synchronized void refreshGroups() {
101 synchronized(this.groups) {
104 PolicyController controller = getPolicyControllerInstance();
105 this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
106 } catch (PAPException e) {
107 String message = "Unable to retrieve Groups from server: " + e;
108 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
114 private PolicyController getPolicyControllerInstance(){
115 return policyController != null ? getPolicyController() : new PolicyController();
118 @RequestMapping(value={"/get_AutoPushPoliciesContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
119 public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response){
121 Set<String> scopes = null;
122 List<String> roles = null;
123 data = new ArrayList<>();
124 String userId = UserUtils.getUserSession(request).getOrgUserId();
125 Map<String, Object> model = new HashMap<>();
126 ObjectMapper mapper = new ObjectMapper();
127 PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
128 List<Object> userRoles = controller.getRoles(userId);
129 roles = new ArrayList<>();
130 scopes = new HashSet<>();
131 for(Object role: userRoles){
132 Roles userRole = (Roles) role;
133 roles.add(userRole.getRole());
134 if(userRole.getScope() != null){
135 if(userRole.getScope().contains(",")){
136 String[] multipleScopes = userRole.getScope().split(",");
137 for(int i =0; i < multipleScopes.length; i++){
138 scopes.add(multipleScopes[i]);
141 if(!userRole.getScope().equals("")){
142 scopes.add(userRole.getScope());
147 if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) {
148 data = commonClassDao.getData(PolicyVersion.class);
150 if(!scopes.isEmpty()){
151 for(String scope : scopes){
153 String query = "From PolicyVersion where policy_name like :scope and id > 0";
154 SimpleBindings params = new SimpleBindings();
155 params.put("scope", scope);
156 List<Object> filterdatas = commonClassDao.getDataByQuery(query, params);
157 if(filterdatas != null){
158 for(int i =0; i < filterdatas.size(); i++){
159 data.add(filterdatas.get(i));
164 PolicyVersion emptyPolicyName = new PolicyVersion();
165 emptyPolicyName.setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
166 data.add(emptyPolicyName);
169 model.put("policydatas", mapper.writeValueAsString(data));
170 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
171 JSONObject j = new JSONObject(msg);
172 response.getWriter().write(j.toString());
175 logger.error("Exception Occured"+e);
179 @RequestMapping(value={"/auto_Push/PushPolicyToPDP.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
180 public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
182 ArrayList<Object> selectedPDPS = new ArrayList<>();
183 ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
184 PolicyController controller = getPolicyControllerInstance();
185 this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
186 ObjectMapper mapper = new ObjectMapper();
187 this.container = new PDPGroupContainer(controller.getPapEngine());
188 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
189 JsonNode root = mapper.readTree(request.getReader());
191 String userId = UserUtils.getUserSession(request).getOrgUserId();
192 logger.info("****************************************Logging UserID while Pushing Policy to PDP Group*****************************************");
193 logger.info("UserId: " + userId + "Push Policy Data: "+ root.get("pushTabData").toString());
194 logger.info("***********************************************************************************************************************************");
196 AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
197 for (Object pdpGroupId : adapter.getPdpDatas()) {
198 LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>)pdpGroupId;
199 for(OnapPDPGroup pdpGroup : this.groups){
200 if(pdpGroup.getId().equals(selectedPDP.get("id"))){
201 selectedPDPS.add(pdpGroup);
206 for (Object policyId : adapter.getPolicyDatas()) {
207 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId;
208 String policyName = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
209 selectedPoliciesInUI.add(policyName);
212 for (Object pdpDestinationGroupId : selectedPDPS) {
213 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
214 Set<PDPPolicy> selectedPolicies = new HashSet<>();
215 for (String policyId : selectedPoliciesInUI) {
216 logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
219 // Get the current selection
220 String selectedItem = policyId;
222 assert (selectedItem != null);
223 // create the id of the target file
224 // Our standard for file naming is:
225 // <domain>.<filename>.<version>.xml
226 // since the file name usually has a ".xml", we need to strip
228 // before adding the other parts
229 String name = selectedItem.replace(File.separator, ".");
231 if (id.endsWith(".xml")) {
232 id = id.replace(".xml", "");
233 id = id.substring(0, id.lastIndexOf('.'));
236 // Default policy to be Root policy; user can change to deferred
239 StdPDPPolicy selectedPolicy = null;
240 String dbCheckName = name;
241 if(dbCheckName.contains("Config_")){
242 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
243 }else if(dbCheckName.contains("Action_")){
244 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
245 }else if(dbCheckName.contains("Decision_")){
246 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
248 String[] split = dbCheckName.split(":");
249 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
250 SimpleBindings policyParams = new SimpleBindings();
251 policyParams.put("split_1", split[1]);
252 policyParams.put("split_0", split[0]);
253 List<Object> queryData = controller.getDataByQuery(query, policyParams);
254 PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
255 File temp = new File(name);
256 BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
257 bw.write(policyEntity.getPolicyData());
259 URI selectedURI = temp.toURI();
263 selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
264 } catch (IOException e) {
265 logger.error("Unable to create policy '" + name + "': "+ e.getMessage(), e);
267 StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
268 if (selectedPolicy != null) {
269 // Add Current policies from container
270 for (OnapPDPGroup group : container.getGroups()) {
271 if (group.getId().equals(selectedGroup.getId())) {
272 currentPoliciesInGroup.addAll(group.getPolicies());
275 // copy policy to PAP
277 controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
278 } catch (PAPException e) {
279 logger.error("Exception Occured"+e);
282 selectedPolicies.add(selectedPolicy);
286 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
287 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
288 updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps());
289 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
290 updatedGroupObject.setStatus(pdpGroup.getStatus());
292 // replace the original set of Policies with the set from the
293 // container (possibly modified by the user)
294 // do not allow multiple copies of same policy
295 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
296 logger.debug("policyIterator....." + selectedPolicies);
297 while (policyIterator.hasNext()) {
298 PDPPolicy existingPolicy = policyIterator.next();
299 for (PDPPolicy selPolicy : selectedPolicies) {
300 if (selPolicy.getName().equals(existingPolicy.getName())) {
301 if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
302 if (selPolicy.getId().equals(existingPolicy.getId())) {
303 policyIterator.remove();
304 logger.debug("Removing policy: " + selPolicy);
308 policyIterator.remove();
309 logger.debug("Removing Old Policy version: "+ selPolicy);
316 currentPoliciesInGroup.addAll(selectedPolicies);
317 updatedGroupObject.setPolicies(currentPoliciesInGroup);
318 this.container.updateGroup(updatedGroupObject);
320 response.setCharacterEncoding("UTF-8");
321 response.setContentType("application / json");
322 request.setCharacterEncoding("UTF-8");
324 PrintWriter out = response.getWriter();
326 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
327 JSONObject j = new JSONObject(msg);
328 out.write(j.toString());
333 response.setCharacterEncoding("UTF-8");
334 request.setCharacterEncoding("UTF-8");
335 PrintWriter out = response.getWriter();
337 out.write(e.getMessage());
342 @SuppressWarnings("unchecked")
343 @RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
344 public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
346 PolicyController controller = getPolicyControllerInstance();
347 this.container = new PDPGroupContainer(controller.getPapEngine());
348 ObjectMapper mapper = new ObjectMapper();
349 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
350 JsonNode root = mapper.readTree(request.getReader());
351 StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
352 JsonNode removePolicyData = root.get("data");
354 String userId = UserUtils.getUserSession(request).getOrgUserId();
355 logger.info("****************************************Logging UserID while Removing Policy from PDP Group*****************************************");
356 logger.info("UserId: " + userId + "PDP Group Data: "+ root.get("activePdpGroup").toString() + "Remove Policy Data: "+root.get("data"));
357 logger.info("***********************************************************************************************************************************");
359 policyContainer = new PDPPolicyContainer(group);
360 if(removePolicyData.size() > 0){
361 for(int i = 0 ; i < removePolicyData.size(); i++){
362 String polData = removePolicyData.get(i).toString();
363 this.policyContainer.removeItem(polData);
365 Set<PDPPolicy> changedPolicies = new HashSet<>();
366 changedPolicies.addAll((Collection<PDPPolicy>) this.policyContainer.getItemIds());
367 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null);
368 updatedGroupObject.setPolicies(changedPolicies);
369 updatedGroupObject.setOnapPdps(group.getOnapPdps());
370 updatedGroupObject.setPipConfigs(group.getPipConfigs());
371 updatedGroupObject.setStatus(group.getStatus());
372 this.container.updateGroup(updatedGroupObject);
375 response.setCharacterEncoding("UTF-8");
376 response.setContentType("application / json");
377 request.setCharacterEncoding("UTF-8");
379 PrintWriter out = response.getWriter();
381 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
382 JSONObject j = new JSONObject(msg);
384 out.write(j.toString());
389 response.setCharacterEncoding("UTF-8");
390 request.setCharacterEncoding("UTF-8");
391 PrintWriter out = response.getWriter();
393 out.write(e.getMessage());